View.java revision ac6ffce1711b84682521e6c2e55865c60929fd88
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.CallSuper;
22import android.annotation.ColorInt;
23import android.annotation.DrawableRes;
24import android.annotation.FloatRange;
25import android.annotation.IdRes;
26import android.annotation.IntDef;
27import android.annotation.LayoutRes;
28import android.annotation.NonNull;
29import android.annotation.Nullable;
30import android.annotation.Size;
31import android.content.ClipData;
32import android.content.Context;
33import android.content.Intent;
34import android.content.res.ColorStateList;
35import android.content.res.Configuration;
36import android.content.res.Resources;
37import android.content.res.TypedArray;
38import android.graphics.Bitmap;
39import android.graphics.Canvas;
40import android.graphics.Insets;
41import android.graphics.Interpolator;
42import android.graphics.LinearGradient;
43import android.graphics.Matrix;
44import android.graphics.Outline;
45import android.graphics.Paint;
46import android.graphics.PixelFormat;
47import android.graphics.Point;
48import android.graphics.PorterDuff;
49import android.graphics.PorterDuffXfermode;
50import android.graphics.Rect;
51import android.graphics.RectF;
52import android.graphics.Region;
53import android.graphics.Shader;
54import android.graphics.drawable.ColorDrawable;
55import android.graphics.drawable.Drawable;
56import android.hardware.display.DisplayManagerGlobal;
57import android.os.Bundle;
58import android.os.Handler;
59import android.os.IBinder;
60import android.os.Parcel;
61import android.os.Parcelable;
62import android.os.RemoteException;
63import android.os.SystemClock;
64import android.os.SystemProperties;
65import android.os.Trace;
66import android.text.TextUtils;
67import android.util.AttributeSet;
68import android.util.FloatProperty;
69import android.util.LayoutDirection;
70import android.util.Log;
71import android.util.LongSparseLongArray;
72import android.util.Pools.SynchronizedPool;
73import android.util.Property;
74import android.util.SparseArray;
75import android.util.StateSet;
76import android.util.SuperNotCalledException;
77import android.util.TypedValue;
78import android.view.ContextMenu.ContextMenuInfo;
79import android.view.AccessibilityIterators.TextSegmentIterator;
80import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
81import android.view.AccessibilityIterators.WordTextSegmentIterator;
82import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
83import android.view.accessibility.AccessibilityEvent;
84import android.view.accessibility.AccessibilityEventSource;
85import android.view.accessibility.AccessibilityManager;
86import android.view.accessibility.AccessibilityNodeInfo;
87import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
88import android.view.accessibility.AccessibilityNodeProvider;
89import android.view.animation.Animation;
90import android.view.animation.AnimationUtils;
91import android.view.animation.Transformation;
92import android.view.inputmethod.EditorInfo;
93import android.view.inputmethod.InputConnection;
94import android.view.inputmethod.InputMethodManager;
95import android.widget.Checkable;
96import android.widget.ScrollBarDrawable;
97
98import static android.os.Build.VERSION_CODES.*;
99import static java.lang.Math.max;
100
101import com.android.internal.R;
102import com.android.internal.util.Predicate;
103import com.android.internal.view.menu.MenuBuilder;
104import com.google.android.collect.Lists;
105import com.google.android.collect.Maps;
106
107import java.lang.annotation.Retention;
108import java.lang.annotation.RetentionPolicy;
109import java.lang.ref.WeakReference;
110import java.lang.reflect.Field;
111import java.lang.reflect.InvocationTargetException;
112import java.lang.reflect.Method;
113import java.lang.reflect.Modifier;
114import java.util.ArrayList;
115import java.util.Arrays;
116import java.util.Collections;
117import java.util.HashMap;
118import java.util.List;
119import java.util.Locale;
120import java.util.Map;
121import java.util.concurrent.CopyOnWriteArrayList;
122import java.util.concurrent.atomic.AtomicInteger;
123
124/**
125 * <p>
126 * This class represents the basic building block for user interface components. A View
127 * occupies a rectangular area on the screen and is responsible for drawing and
128 * event handling. View is the base class for <em>widgets</em>, which are
129 * used to create interactive UI components (buttons, text fields, etc.). The
130 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
131 * are invisible containers that hold other Views (or other ViewGroups) and define
132 * their layout properties.
133 * </p>
134 *
135 * <div class="special reference">
136 * <h3>Developer Guides</h3>
137 * <p>For information about using this class to develop your application's user interface,
138 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
139 * </div>
140 *
141 * <a name="Using"></a>
142 * <h3>Using Views</h3>
143 * <p>
144 * All of the views in a window are arranged in a single tree. You can add views
145 * either from code or by specifying a tree of views in one or more XML layout
146 * files. There are many specialized subclasses of views that act as controls or
147 * are capable of displaying text, images, or other content.
148 * </p>
149 * <p>
150 * Once you have created a tree of views, there are typically a few types of
151 * common operations you may wish to perform:
152 * <ul>
153 * <li><strong>Set properties:</strong> for example setting the text of a
154 * {@link android.widget.TextView}. The available properties and the methods
155 * that set them will vary among the different subclasses of views. Note that
156 * properties that are known at build time can be set in the XML layout
157 * files.</li>
158 * <li><strong>Set focus:</strong> The framework will handled moving focus in
159 * response to user input. To force focus to a specific view, call
160 * {@link #requestFocus}.</li>
161 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
162 * that will be notified when something interesting happens to the view. For
163 * example, all views will let you set a listener to be notified when the view
164 * gains or loses focus. You can register such a listener using
165 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
166 * Other view subclasses offer more specialized listeners. For example, a Button
167 * exposes a listener to notify clients when the button is clicked.</li>
168 * <li><strong>Set visibility:</strong> You can hide or show views using
169 * {@link #setVisibility(int)}.</li>
170 * </ul>
171 * </p>
172 * <p><em>
173 * Note: The Android framework is responsible for measuring, laying out and
174 * drawing views. You should not call methods that perform these actions on
175 * views yourself unless you are actually implementing a
176 * {@link android.view.ViewGroup}.
177 * </em></p>
178 *
179 * <a name="Lifecycle"></a>
180 * <h3>Implementing a Custom View</h3>
181 *
182 * <p>
183 * To implement a custom view, you will usually begin by providing overrides for
184 * some of the standard methods that the framework calls on all views. You do
185 * not need to override all of these methods. In fact, you can start by just
186 * overriding {@link #onDraw(android.graphics.Canvas)}.
187 * <table border="2" width="85%" align="center" cellpadding="5">
188 *     <thead>
189 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
190 *     </thead>
191 *
192 *     <tbody>
193 *     <tr>
194 *         <td rowspan="2">Creation</td>
195 *         <td>Constructors</td>
196 *         <td>There is a form of the constructor that are called when the view
197 *         is created from code and a form that is called when the view is
198 *         inflated from a layout file. The second form should parse and apply
199 *         any attributes defined in the layout file.
200 *         </td>
201 *     </tr>
202 *     <tr>
203 *         <td><code>{@link #onFinishInflate()}</code></td>
204 *         <td>Called after a view and all of its children has been inflated
205 *         from XML.</td>
206 *     </tr>
207 *
208 *     <tr>
209 *         <td rowspan="3">Layout</td>
210 *         <td><code>{@link #onMeasure(int, int)}</code></td>
211 *         <td>Called to determine the size requirements for this view and all
212 *         of its children.
213 *         </td>
214 *     </tr>
215 *     <tr>
216 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
217 *         <td>Called when this view should assign a size and position to all
218 *         of its children.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
223 *         <td>Called when the size of this view has changed.
224 *         </td>
225 *     </tr>
226 *
227 *     <tr>
228 *         <td>Drawing</td>
229 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
230 *         <td>Called when the view should render its content.
231 *         </td>
232 *     </tr>
233 *
234 *     <tr>
235 *         <td rowspan="4">Event processing</td>
236 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
237 *         <td>Called when a new hardware key event occurs.
238 *         </td>
239 *     </tr>
240 *     <tr>
241 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
242 *         <td>Called when a hardware key up event occurs.
243 *         </td>
244 *     </tr>
245 *     <tr>
246 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
247 *         <td>Called when a trackball motion event occurs.
248 *         </td>
249 *     </tr>
250 *     <tr>
251 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
252 *         <td>Called when a touch screen motion event occurs.
253 *         </td>
254 *     </tr>
255 *
256 *     <tr>
257 *         <td rowspan="2">Focus</td>
258 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
259 *         <td>Called when the view gains or loses focus.
260 *         </td>
261 *     </tr>
262 *
263 *     <tr>
264 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
265 *         <td>Called when the window containing the view gains or loses focus.
266 *         </td>
267 *     </tr>
268 *
269 *     <tr>
270 *         <td rowspan="3">Attaching</td>
271 *         <td><code>{@link #onAttachedToWindow()}</code></td>
272 *         <td>Called when the view is attached to a window.
273 *         </td>
274 *     </tr>
275 *
276 *     <tr>
277 *         <td><code>{@link #onDetachedFromWindow}</code></td>
278 *         <td>Called when the view is detached from its window.
279 *         </td>
280 *     </tr>
281 *
282 *     <tr>
283 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
284 *         <td>Called when the visibility of the window containing the view
285 *         has changed.
286 *         </td>
287 *     </tr>
288 *     </tbody>
289 *
290 * </table>
291 * </p>
292 *
293 * <a name="IDs"></a>
294 * <h3>IDs</h3>
295 * Views may have an integer id associated with them. These ids are typically
296 * assigned in the layout XML files, and are used to find specific views within
297 * the view tree. A common pattern is to:
298 * <ul>
299 * <li>Define a Button in the layout file and assign it a unique ID.
300 * <pre>
301 * &lt;Button
302 *     android:id="@+id/my_button"
303 *     android:layout_width="wrap_content"
304 *     android:layout_height="wrap_content"
305 *     android:text="@string/my_button_text"/&gt;
306 * </pre></li>
307 * <li>From the onCreate method of an Activity, find the Button
308 * <pre class="prettyprint">
309 *      Button myButton = (Button) findViewById(R.id.my_button);
310 * </pre></li>
311 * </ul>
312 * <p>
313 * View IDs need not be unique throughout the tree, but it is good practice to
314 * ensure that they are at least unique within the part of the tree you are
315 * searching.
316 * </p>
317 *
318 * <a name="Position"></a>
319 * <h3>Position</h3>
320 * <p>
321 * The geometry of a view is that of a rectangle. A view has a location,
322 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
323 * two dimensions, expressed as a width and a height. The unit for location
324 * and dimensions is the pixel.
325 * </p>
326 *
327 * <p>
328 * It is possible to retrieve the location of a view by invoking the methods
329 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
330 * coordinate of the rectangle representing the view. The latter returns the
331 * top, or Y, coordinate of the rectangle representing the view. These methods
332 * both return the location of the view relative to its parent. For instance,
333 * when getLeft() returns 20, that means the view is located 20 pixels to the
334 * right of the left edge of its direct parent.
335 * </p>
336 *
337 * <p>
338 * In addition, several convenience methods are offered to avoid unnecessary
339 * computations, namely {@link #getRight()} and {@link #getBottom()}.
340 * These methods return the coordinates of the right and bottom edges of the
341 * rectangle representing the view. For instance, calling {@link #getRight()}
342 * is similar to the following computation: <code>getLeft() + getWidth()</code>
343 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
344 * </p>
345 *
346 * <a name="SizePaddingMargins"></a>
347 * <h3>Size, padding and margins</h3>
348 * <p>
349 * The size of a view is expressed with a width and a height. A view actually
350 * possess two pairs of width and height values.
351 * </p>
352 *
353 * <p>
354 * The first pair is known as <em>measured width</em> and
355 * <em>measured height</em>. These dimensions define how big a view wants to be
356 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
357 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
358 * and {@link #getMeasuredHeight()}.
359 * </p>
360 *
361 * <p>
362 * The second pair is simply known as <em>width</em> and <em>height</em>, or
363 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
364 * dimensions define the actual size of the view on screen, at drawing time and
365 * after layout. These values may, but do not have to, be different from the
366 * measured width and height. The width and height can be obtained by calling
367 * {@link #getWidth()} and {@link #getHeight()}.
368 * </p>
369 *
370 * <p>
371 * To measure its dimensions, a view takes into account its padding. The padding
372 * is expressed in pixels for the left, top, right and bottom parts of the view.
373 * Padding can be used to offset the content of the view by a specific amount of
374 * pixels. For instance, a left padding of 2 will push the view's content by
375 * 2 pixels to the right of the left edge. Padding can be set using the
376 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
377 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
378 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
379 * {@link #getPaddingEnd()}.
380 * </p>
381 *
382 * <p>
383 * Even though a view can define a padding, it does not provide any support for
384 * margins. However, view groups provide such a support. Refer to
385 * {@link android.view.ViewGroup} and
386 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
387 * </p>
388 *
389 * <a name="Layout"></a>
390 * <h3>Layout</h3>
391 * <p>
392 * Layout is a two pass process: a measure pass and a layout pass. The measuring
393 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
394 * of the view tree. Each view pushes dimension specifications down the tree
395 * during the recursion. At the end of the measure pass, every view has stored
396 * its measurements. The second pass happens in
397 * {@link #layout(int,int,int,int)} and is also top-down. During
398 * this pass each parent is responsible for positioning all of its children
399 * using the sizes computed in the measure pass.
400 * </p>
401 *
402 * <p>
403 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
404 * {@link #getMeasuredHeight()} values must be set, along with those for all of
405 * that view's descendants. A view's measured width and measured height values
406 * must respect the constraints imposed by the view's parents. This guarantees
407 * that at the end of the measure pass, all parents accept all of their
408 * children's measurements. A parent view may call measure() more than once on
409 * its children. For example, the parent may measure each child once with
410 * unspecified dimensions to find out how big they want to be, then call
411 * measure() on them again with actual numbers if the sum of all the children's
412 * unconstrained sizes is too big or too small.
413 * </p>
414 *
415 * <p>
416 * The measure pass uses two classes to communicate dimensions. The
417 * {@link MeasureSpec} class is used by views to tell their parents how they
418 * want to be measured and positioned. The base LayoutParams class just
419 * describes how big the view wants to be for both width and height. For each
420 * dimension, it can specify one of:
421 * <ul>
422 * <li> an exact number
423 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
424 * (minus padding)
425 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
426 * enclose its content (plus padding).
427 * </ul>
428 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
429 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
430 * an X and Y value.
431 * </p>
432 *
433 * <p>
434 * MeasureSpecs are used to push requirements down the tree from parent to
435 * child. A MeasureSpec can be in one of three modes:
436 * <ul>
437 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
438 * of a child view. For example, a LinearLayout may call measure() on its child
439 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
440 * tall the child view wants to be given a width of 240 pixels.
441 * <li>EXACTLY: This is used by the parent to impose an exact size on the
442 * child. The child must use this size, and guarantee that all of its
443 * descendants will fit within this size.
444 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
445 * child. The child must guarantee that it and all of its descendants will fit
446 * within this size.
447 * </ul>
448 * </p>
449 *
450 * <p>
451 * To initiate a layout, call {@link #requestLayout}. This method is typically
452 * called by a view on itself when it believes that is can no longer fit within
453 * its current bounds.
454 * </p>
455 *
456 * <a name="Drawing"></a>
457 * <h3>Drawing</h3>
458 * <p>
459 * Drawing is handled by walking the tree and recording the drawing commands of
460 * any View that needs to update. After this, the drawing commands of the
461 * entire tree are issued to screen, clipped to the newly damaged area.
462 * </p>
463 *
464 * <p>
465 * The tree is largely recorded and drawn in order, with parents drawn before
466 * (i.e., behind) their children, with siblings drawn in the order they appear
467 * in the tree. If you set a background drawable for a View, then the View will
468 * draw it before calling back to its <code>onDraw()</code> method. The child
469 * drawing order can be overridden with
470 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
471 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
472 * </p>
473 *
474 * <p>
475 * To force a view to draw, call {@link #invalidate()}.
476 * </p>
477 *
478 * <a name="EventHandlingThreading"></a>
479 * <h3>Event Handling and Threading</h3>
480 * <p>
481 * The basic cycle of a view is as follows:
482 * <ol>
483 * <li>An event comes in and is dispatched to the appropriate view. The view
484 * handles the event and notifies any listeners.</li>
485 * <li>If in the course of processing the event, the view's bounds may need
486 * to be changed, the view will call {@link #requestLayout()}.</li>
487 * <li>Similarly, if in the course of processing the event the view's appearance
488 * may need to be changed, the view will call {@link #invalidate()}.</li>
489 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
490 * the framework will take care of measuring, laying out, and drawing the tree
491 * as appropriate.</li>
492 * </ol>
493 * </p>
494 *
495 * <p><em>Note: The entire view tree is single threaded. You must always be on
496 * the UI thread when calling any method on any view.</em>
497 * If you are doing work on other threads and want to update the state of a view
498 * from that thread, you should use a {@link Handler}.
499 * </p>
500 *
501 * <a name="FocusHandling"></a>
502 * <h3>Focus Handling</h3>
503 * <p>
504 * The framework will handle routine focus movement in response to user input.
505 * This includes changing the focus as views are removed or hidden, or as new
506 * views become available. Views indicate their willingness to take focus
507 * through the {@link #isFocusable} method. To change whether a view can take
508 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
509 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
510 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
511 * </p>
512 * <p>
513 * Focus movement is based on an algorithm which finds the nearest neighbor in a
514 * given direction. In rare cases, the default algorithm may not match the
515 * intended behavior of the developer. In these situations, you can provide
516 * explicit overrides by using these XML attributes in the layout file:
517 * <pre>
518 * nextFocusDown
519 * nextFocusLeft
520 * nextFocusRight
521 * nextFocusUp
522 * </pre>
523 * </p>
524 *
525 *
526 * <p>
527 * To get a particular view to take focus, call {@link #requestFocus()}.
528 * </p>
529 *
530 * <a name="TouchMode"></a>
531 * <h3>Touch Mode</h3>
532 * <p>
533 * When a user is navigating a user interface via directional keys such as a D-pad, it is
534 * necessary to give focus to actionable items such as buttons so the user can see
535 * what will take input.  If the device has touch capabilities, however, and the user
536 * begins interacting with the interface by touching it, it is no longer necessary to
537 * always highlight, or give focus to, a particular view.  This motivates a mode
538 * for interaction named 'touch mode'.
539 * </p>
540 * <p>
541 * For a touch capable device, once the user touches the screen, the device
542 * will enter touch mode.  From this point onward, only views for which
543 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
544 * Other views that are touchable, like buttons, will not take focus when touched; they will
545 * only fire the on click listeners.
546 * </p>
547 * <p>
548 * Any time a user hits a directional key, such as a D-pad direction, the view device will
549 * exit touch mode, and find a view to take focus, so that the user may resume interacting
550 * with the user interface without touching the screen again.
551 * </p>
552 * <p>
553 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
554 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
555 * </p>
556 *
557 * <a name="Scrolling"></a>
558 * <h3>Scrolling</h3>
559 * <p>
560 * The framework provides basic support for views that wish to internally
561 * scroll their content. This includes keeping track of the X and Y scroll
562 * offset as well as mechanisms for drawing scrollbars. See
563 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
564 * {@link #awakenScrollBars()} for more details.
565 * </p>
566 *
567 * <a name="Tags"></a>
568 * <h3>Tags</h3>
569 * <p>
570 * Unlike IDs, tags are not used to identify views. Tags are essentially an
571 * extra piece of information that can be associated with a view. They are most
572 * often used as a convenience to store data related to views in the views
573 * themselves rather than by putting them in a separate structure.
574 * </p>
575 *
576 * <a name="Properties"></a>
577 * <h3>Properties</h3>
578 * <p>
579 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
580 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
581 * available both in the {@link Property} form as well as in similarly-named setter/getter
582 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
583 * be used to set persistent state associated with these rendering-related properties on the view.
584 * The properties and methods can also be used in conjunction with
585 * {@link android.animation.Animator Animator}-based animations, described more in the
586 * <a href="#Animation">Animation</a> section.
587 * </p>
588 *
589 * <a name="Animation"></a>
590 * <h3>Animation</h3>
591 * <p>
592 * Starting with Android 3.0, the preferred way of animating views is to use the
593 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
594 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
595 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
596 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
597 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
598 * makes animating these View properties particularly easy and efficient.
599 * </p>
600 * <p>
601 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
602 * You can attach an {@link Animation} object to a view using
603 * {@link #setAnimation(Animation)} or
604 * {@link #startAnimation(Animation)}. The animation can alter the scale,
605 * rotation, translation and alpha of a view over time. If the animation is
606 * attached to a view that has children, the animation will affect the entire
607 * subtree rooted by that node. When an animation is started, the framework will
608 * take care of redrawing the appropriate views until the animation completes.
609 * </p>
610 *
611 * <a name="Security"></a>
612 * <h3>Security</h3>
613 * <p>
614 * Sometimes it is essential that an application be able to verify that an action
615 * is being performed with the full knowledge and consent of the user, such as
616 * granting a permission request, making a purchase or clicking on an advertisement.
617 * Unfortunately, a malicious application could try to spoof the user into
618 * performing these actions, unaware, by concealing the intended purpose of the view.
619 * As a remedy, the framework offers a touch filtering mechanism that can be used to
620 * improve the security of views that provide access to sensitive functionality.
621 * </p><p>
622 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
623 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
624 * will discard touches that are received whenever the view's window is obscured by
625 * another visible window.  As a result, the view will not receive touches whenever a
626 * toast, dialog or other window appears above the view's window.
627 * </p><p>
628 * For more fine-grained control over security, consider overriding the
629 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
630 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
631 * </p>
632 *
633 * @attr ref android.R.styleable#View_alpha
634 * @attr ref android.R.styleable#View_assistBlocked
635 * @attr ref android.R.styleable#View_background
636 * @attr ref android.R.styleable#View_clickable
637 * @attr ref android.R.styleable#View_contentDescription
638 * @attr ref android.R.styleable#View_drawingCacheQuality
639 * @attr ref android.R.styleable#View_duplicateParentState
640 * @attr ref android.R.styleable#View_id
641 * @attr ref android.R.styleable#View_requiresFadingEdge
642 * @attr ref android.R.styleable#View_fadeScrollbars
643 * @attr ref android.R.styleable#View_fadingEdgeLength
644 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
645 * @attr ref android.R.styleable#View_fitsSystemWindows
646 * @attr ref android.R.styleable#View_isScrollContainer
647 * @attr ref android.R.styleable#View_focusable
648 * @attr ref android.R.styleable#View_focusableInTouchMode
649 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
650 * @attr ref android.R.styleable#View_keepScreenOn
651 * @attr ref android.R.styleable#View_layerType
652 * @attr ref android.R.styleable#View_layoutDirection
653 * @attr ref android.R.styleable#View_longClickable
654 * @attr ref android.R.styleable#View_minHeight
655 * @attr ref android.R.styleable#View_minWidth
656 * @attr ref android.R.styleable#View_nextFocusDown
657 * @attr ref android.R.styleable#View_nextFocusLeft
658 * @attr ref android.R.styleable#View_nextFocusRight
659 * @attr ref android.R.styleable#View_nextFocusUp
660 * @attr ref android.R.styleable#View_onClick
661 * @attr ref android.R.styleable#View_padding
662 * @attr ref android.R.styleable#View_paddingBottom
663 * @attr ref android.R.styleable#View_paddingLeft
664 * @attr ref android.R.styleable#View_paddingRight
665 * @attr ref android.R.styleable#View_paddingTop
666 * @attr ref android.R.styleable#View_paddingStart
667 * @attr ref android.R.styleable#View_paddingEnd
668 * @attr ref android.R.styleable#View_saveEnabled
669 * @attr ref android.R.styleable#View_rotation
670 * @attr ref android.R.styleable#View_rotationX
671 * @attr ref android.R.styleable#View_rotationY
672 * @attr ref android.R.styleable#View_scaleX
673 * @attr ref android.R.styleable#View_scaleY
674 * @attr ref android.R.styleable#View_scrollX
675 * @attr ref android.R.styleable#View_scrollY
676 * @attr ref android.R.styleable#View_scrollbarSize
677 * @attr ref android.R.styleable#View_scrollbarStyle
678 * @attr ref android.R.styleable#View_scrollbars
679 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
680 * @attr ref android.R.styleable#View_scrollbarFadeDuration
681 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
682 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
683 * @attr ref android.R.styleable#View_scrollbarThumbVertical
684 * @attr ref android.R.styleable#View_scrollbarTrackVertical
685 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
686 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
687 * @attr ref android.R.styleable#View_stateListAnimator
688 * @attr ref android.R.styleable#View_transitionName
689 * @attr ref android.R.styleable#View_soundEffectsEnabled
690 * @attr ref android.R.styleable#View_tag
691 * @attr ref android.R.styleable#View_textAlignment
692 * @attr ref android.R.styleable#View_textDirection
693 * @attr ref android.R.styleable#View_transformPivotX
694 * @attr ref android.R.styleable#View_transformPivotY
695 * @attr ref android.R.styleable#View_translationX
696 * @attr ref android.R.styleable#View_translationY
697 * @attr ref android.R.styleable#View_translationZ
698 * @attr ref android.R.styleable#View_visibility
699 *
700 * @see android.view.ViewGroup
701 */
702public class View implements Drawable.Callback, KeyEvent.Callback,
703        AccessibilityEventSource {
704    private static final boolean DBG = false;
705
706    /**
707     * The logging tag used by this class with android.util.Log.
708     */
709    protected static final String VIEW_LOG_TAG = "View";
710
711    /**
712     * When set to true, apps will draw debugging information about their layouts.
713     *
714     * @hide
715     */
716    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
717
718    /**
719     * When set to true, this view will save its attribute data.
720     *
721     * @hide
722     */
723    public static boolean mDebugViewAttributes = false;
724
725    /**
726     * Used to mark a View that has no ID.
727     */
728    public static final int NO_ID = -1;
729
730    /**
731     * Signals that compatibility booleans have been initialized according to
732     * target SDK versions.
733     */
734    private static boolean sCompatibilityDone = false;
735
736    /**
737     * Use the old (broken) way of building MeasureSpecs.
738     */
739    private static boolean sUseBrokenMakeMeasureSpec = false;
740
741    /**
742     * Ignore any optimizations using the measure cache.
743     */
744    private static boolean sIgnoreMeasureCache = false;
745
746    /**
747     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
748     * calling setFlags.
749     */
750    private static final int NOT_FOCUSABLE = 0x00000000;
751
752    /**
753     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
754     * setFlags.
755     */
756    private static final int FOCUSABLE = 0x00000001;
757
758    /**
759     * Mask for use with setFlags indicating bits used for focus.
760     */
761    private static final int FOCUSABLE_MASK = 0x00000001;
762
763    /**
764     * This view will adjust its padding to fit sytem windows (e.g. status bar)
765     */
766    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
767
768    /** @hide */
769    @IntDef({VISIBLE, INVISIBLE, GONE})
770    @Retention(RetentionPolicy.SOURCE)
771    public @interface Visibility {}
772
773    /**
774     * This view is visible.
775     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
776     * android:visibility}.
777     */
778    public static final int VISIBLE = 0x00000000;
779
780    /**
781     * This view is invisible, but it still takes up space for layout purposes.
782     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
783     * android:visibility}.
784     */
785    public static final int INVISIBLE = 0x00000004;
786
787    /**
788     * This view is invisible, and it doesn't take any space for layout
789     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
790     * android:visibility}.
791     */
792    public static final int GONE = 0x00000008;
793
794    /**
795     * Mask for use with setFlags indicating bits used for visibility.
796     * {@hide}
797     */
798    static final int VISIBILITY_MASK = 0x0000000C;
799
800    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
801
802    /**
803     * This view is enabled. Interpretation varies by subclass.
804     * Use with ENABLED_MASK when calling setFlags.
805     * {@hide}
806     */
807    static final int ENABLED = 0x00000000;
808
809    /**
810     * This view is disabled. Interpretation varies by subclass.
811     * Use with ENABLED_MASK when calling setFlags.
812     * {@hide}
813     */
814    static final int DISABLED = 0x00000020;
815
816   /**
817    * Mask for use with setFlags indicating bits used for indicating whether
818    * this view is enabled
819    * {@hide}
820    */
821    static final int ENABLED_MASK = 0x00000020;
822
823    /**
824     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
825     * called and further optimizations will be performed. It is okay to have
826     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
827     * {@hide}
828     */
829    static final int WILL_NOT_DRAW = 0x00000080;
830
831    /**
832     * Mask for use with setFlags indicating bits used for indicating whether
833     * this view is will draw
834     * {@hide}
835     */
836    static final int DRAW_MASK = 0x00000080;
837
838    /**
839     * <p>This view doesn't show scrollbars.</p>
840     * {@hide}
841     */
842    static final int SCROLLBARS_NONE = 0x00000000;
843
844    /**
845     * <p>This view shows horizontal scrollbars.</p>
846     * {@hide}
847     */
848    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
849
850    /**
851     * <p>This view shows vertical scrollbars.</p>
852     * {@hide}
853     */
854    static final int SCROLLBARS_VERTICAL = 0x00000200;
855
856    /**
857     * <p>Mask for use with setFlags indicating bits used for indicating which
858     * scrollbars are enabled.</p>
859     * {@hide}
860     */
861    static final int SCROLLBARS_MASK = 0x00000300;
862
863    /**
864     * Indicates that the view should filter touches when its window is obscured.
865     * Refer to the class comments for more information about this security feature.
866     * {@hide}
867     */
868    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
869
870    /**
871     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
872     * that they are optional and should be skipped if the window has
873     * requested system UI flags that ignore those insets for layout.
874     */
875    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
876
877    /**
878     * <p>This view doesn't show fading edges.</p>
879     * {@hide}
880     */
881    static final int FADING_EDGE_NONE = 0x00000000;
882
883    /**
884     * <p>This view shows horizontal fading edges.</p>
885     * {@hide}
886     */
887    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
888
889    /**
890     * <p>This view shows vertical fading edges.</p>
891     * {@hide}
892     */
893    static final int FADING_EDGE_VERTICAL = 0x00002000;
894
895    /**
896     * <p>Mask for use with setFlags indicating bits used for indicating which
897     * fading edges are enabled.</p>
898     * {@hide}
899     */
900    static final int FADING_EDGE_MASK = 0x00003000;
901
902    /**
903     * <p>Indicates this view can be clicked. When clickable, a View reacts
904     * to clicks by notifying the OnClickListener.<p>
905     * {@hide}
906     */
907    static final int CLICKABLE = 0x00004000;
908
909    /**
910     * <p>Indicates this view is caching its drawing into a bitmap.</p>
911     * {@hide}
912     */
913    static final int DRAWING_CACHE_ENABLED = 0x00008000;
914
915    /**
916     * <p>Indicates that no icicle should be saved for this view.<p>
917     * {@hide}
918     */
919    static final int SAVE_DISABLED = 0x000010000;
920
921    /**
922     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
923     * property.</p>
924     * {@hide}
925     */
926    static final int SAVE_DISABLED_MASK = 0x000010000;
927
928    /**
929     * <p>Indicates that no drawing cache should ever be created for this view.<p>
930     * {@hide}
931     */
932    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
933
934    /**
935     * <p>Indicates this view can take / keep focus when int touch mode.</p>
936     * {@hide}
937     */
938    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
939
940    /** @hide */
941    @Retention(RetentionPolicy.SOURCE)
942    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
943    public @interface DrawingCacheQuality {}
944
945    /**
946     * <p>Enables low quality mode for the drawing cache.</p>
947     */
948    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
949
950    /**
951     * <p>Enables high quality mode for the drawing cache.</p>
952     */
953    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
954
955    /**
956     * <p>Enables automatic quality mode for the drawing cache.</p>
957     */
958    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
959
960    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
961            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
962    };
963
964    /**
965     * <p>Mask for use with setFlags indicating bits used for the cache
966     * quality property.</p>
967     * {@hide}
968     */
969    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
970
971    /**
972     * <p>
973     * Indicates this view can be long clicked. When long clickable, a View
974     * reacts to long clicks by notifying the OnLongClickListener or showing a
975     * context menu.
976     * </p>
977     * {@hide}
978     */
979    static final int LONG_CLICKABLE = 0x00200000;
980
981    /**
982     * <p>Indicates that this view gets its drawable states from its direct parent
983     * and ignores its original internal states.</p>
984     *
985     * @hide
986     */
987    static final int DUPLICATE_PARENT_STATE = 0x00400000;
988
989    /** @hide */
990    @IntDef({
991        SCROLLBARS_INSIDE_OVERLAY,
992        SCROLLBARS_INSIDE_INSET,
993        SCROLLBARS_OUTSIDE_OVERLAY,
994        SCROLLBARS_OUTSIDE_INSET
995    })
996    @Retention(RetentionPolicy.SOURCE)
997    public @interface ScrollBarStyle {}
998
999    /**
1000     * The scrollbar style to display the scrollbars inside the content area,
1001     * without increasing the padding. The scrollbars will be overlaid with
1002     * translucency on the view's content.
1003     */
1004    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1005
1006    /**
1007     * The scrollbar style to display the scrollbars inside the padded area,
1008     * increasing the padding of the view. The scrollbars will not overlap the
1009     * content area of the view.
1010     */
1011    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1012
1013    /**
1014     * The scrollbar style to display the scrollbars at the edge of the view,
1015     * without increasing the padding. The scrollbars will be overlaid with
1016     * translucency.
1017     */
1018    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1019
1020    /**
1021     * The scrollbar style to display the scrollbars at the edge of the view,
1022     * increasing the padding of the view. The scrollbars will only overlap the
1023     * background, if any.
1024     */
1025    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1026
1027    /**
1028     * Mask to check if the scrollbar style is overlay or inset.
1029     * {@hide}
1030     */
1031    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1032
1033    /**
1034     * Mask to check if the scrollbar style is inside or outside.
1035     * {@hide}
1036     */
1037    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1038
1039    /**
1040     * Mask for scrollbar style.
1041     * {@hide}
1042     */
1043    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1044
1045    /**
1046     * View flag indicating that the screen should remain on while the
1047     * window containing this view is visible to the user.  This effectively
1048     * takes care of automatically setting the WindowManager's
1049     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1050     */
1051    public static final int KEEP_SCREEN_ON = 0x04000000;
1052
1053    /**
1054     * View flag indicating whether this view should have sound effects enabled
1055     * for events such as clicking and touching.
1056     */
1057    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1058
1059    /**
1060     * View flag indicating whether this view should have haptic feedback
1061     * enabled for events such as long presses.
1062     */
1063    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1064
1065    /**
1066     * <p>Indicates that the view hierarchy should stop saving state when
1067     * it reaches this view.  If state saving is initiated immediately at
1068     * the view, it will be allowed.
1069     * {@hide}
1070     */
1071    static final int PARENT_SAVE_DISABLED = 0x20000000;
1072
1073    /**
1074     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1075     * {@hide}
1076     */
1077    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1078
1079    /** @hide */
1080    @IntDef(flag = true,
1081            value = {
1082                FOCUSABLES_ALL,
1083                FOCUSABLES_TOUCH_MODE
1084            })
1085    @Retention(RetentionPolicy.SOURCE)
1086    public @interface FocusableMode {}
1087
1088    /**
1089     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1090     * should add all focusable Views regardless if they are focusable in touch mode.
1091     */
1092    public static final int FOCUSABLES_ALL = 0x00000000;
1093
1094    /**
1095     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1096     * should add only Views focusable in touch mode.
1097     */
1098    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1099
1100    /** @hide */
1101    @IntDef({
1102            FOCUS_BACKWARD,
1103            FOCUS_FORWARD,
1104            FOCUS_LEFT,
1105            FOCUS_UP,
1106            FOCUS_RIGHT,
1107            FOCUS_DOWN
1108    })
1109    @Retention(RetentionPolicy.SOURCE)
1110    public @interface FocusDirection {}
1111
1112    /** @hide */
1113    @IntDef({
1114            FOCUS_LEFT,
1115            FOCUS_UP,
1116            FOCUS_RIGHT,
1117            FOCUS_DOWN
1118    })
1119    @Retention(RetentionPolicy.SOURCE)
1120    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1121
1122    /**
1123     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1124     * item.
1125     */
1126    public static final int FOCUS_BACKWARD = 0x00000001;
1127
1128    /**
1129     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1130     * item.
1131     */
1132    public static final int FOCUS_FORWARD = 0x00000002;
1133
1134    /**
1135     * Use with {@link #focusSearch(int)}. Move focus to the left.
1136     */
1137    public static final int FOCUS_LEFT = 0x00000011;
1138
1139    /**
1140     * Use with {@link #focusSearch(int)}. Move focus up.
1141     */
1142    public static final int FOCUS_UP = 0x00000021;
1143
1144    /**
1145     * Use with {@link #focusSearch(int)}. Move focus to the right.
1146     */
1147    public static final int FOCUS_RIGHT = 0x00000042;
1148
1149    /**
1150     * Use with {@link #focusSearch(int)}. Move focus down.
1151     */
1152    public static final int FOCUS_DOWN = 0x00000082;
1153
1154    /**
1155     * Bits of {@link #getMeasuredWidthAndState()} and
1156     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1157     */
1158    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1159
1160    /**
1161     * Bits of {@link #getMeasuredWidthAndState()} and
1162     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1163     */
1164    public static final int MEASURED_STATE_MASK = 0xff000000;
1165
1166    /**
1167     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1168     * for functions that combine both width and height into a single int,
1169     * such as {@link #getMeasuredState()} and the childState argument of
1170     * {@link #resolveSizeAndState(int, int, int)}.
1171     */
1172    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1173
1174    /**
1175     * Bit of {@link #getMeasuredWidthAndState()} and
1176     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1177     * is smaller that the space the view would like to have.
1178     */
1179    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1180
1181    /**
1182     * Base View state sets
1183     */
1184    // Singles
1185    /**
1186     * Indicates the view has no states set. States are used with
1187     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1188     * view depending on its state.
1189     *
1190     * @see android.graphics.drawable.Drawable
1191     * @see #getDrawableState()
1192     */
1193    protected static final int[] EMPTY_STATE_SET;
1194    /**
1195     * Indicates the view is enabled. States are used with
1196     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1197     * view depending on its state.
1198     *
1199     * @see android.graphics.drawable.Drawable
1200     * @see #getDrawableState()
1201     */
1202    protected static final int[] ENABLED_STATE_SET;
1203    /**
1204     * Indicates the view is focused. States are used with
1205     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1206     * view depending on its state.
1207     *
1208     * @see android.graphics.drawable.Drawable
1209     * @see #getDrawableState()
1210     */
1211    protected static final int[] FOCUSED_STATE_SET;
1212    /**
1213     * Indicates the view is selected. States are used with
1214     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1215     * view depending on its state.
1216     *
1217     * @see android.graphics.drawable.Drawable
1218     * @see #getDrawableState()
1219     */
1220    protected static final int[] SELECTED_STATE_SET;
1221    /**
1222     * Indicates the view is pressed. States are used with
1223     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1224     * view depending on its state.
1225     *
1226     * @see android.graphics.drawable.Drawable
1227     * @see #getDrawableState()
1228     */
1229    protected static final int[] PRESSED_STATE_SET;
1230    /**
1231     * Indicates the view's window has focus. States are used with
1232     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1233     * view depending on its state.
1234     *
1235     * @see android.graphics.drawable.Drawable
1236     * @see #getDrawableState()
1237     */
1238    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1239    // Doubles
1240    /**
1241     * Indicates the view is enabled and has the focus.
1242     *
1243     * @see #ENABLED_STATE_SET
1244     * @see #FOCUSED_STATE_SET
1245     */
1246    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1247    /**
1248     * Indicates the view is enabled and selected.
1249     *
1250     * @see #ENABLED_STATE_SET
1251     * @see #SELECTED_STATE_SET
1252     */
1253    protected static final int[] ENABLED_SELECTED_STATE_SET;
1254    /**
1255     * Indicates the view is enabled and that its window has focus.
1256     *
1257     * @see #ENABLED_STATE_SET
1258     * @see #WINDOW_FOCUSED_STATE_SET
1259     */
1260    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1261    /**
1262     * Indicates the view is focused and selected.
1263     *
1264     * @see #FOCUSED_STATE_SET
1265     * @see #SELECTED_STATE_SET
1266     */
1267    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1268    /**
1269     * Indicates the view has the focus and that its window has the focus.
1270     *
1271     * @see #FOCUSED_STATE_SET
1272     * @see #WINDOW_FOCUSED_STATE_SET
1273     */
1274    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1275    /**
1276     * Indicates the view is selected and that its window has the focus.
1277     *
1278     * @see #SELECTED_STATE_SET
1279     * @see #WINDOW_FOCUSED_STATE_SET
1280     */
1281    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1282    // Triples
1283    /**
1284     * Indicates the view is enabled, focused and selected.
1285     *
1286     * @see #ENABLED_STATE_SET
1287     * @see #FOCUSED_STATE_SET
1288     * @see #SELECTED_STATE_SET
1289     */
1290    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1291    /**
1292     * Indicates the view is enabled, focused and its window has the focus.
1293     *
1294     * @see #ENABLED_STATE_SET
1295     * @see #FOCUSED_STATE_SET
1296     * @see #WINDOW_FOCUSED_STATE_SET
1297     */
1298    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1299    /**
1300     * Indicates the view is enabled, selected and its window has the focus.
1301     *
1302     * @see #ENABLED_STATE_SET
1303     * @see #SELECTED_STATE_SET
1304     * @see #WINDOW_FOCUSED_STATE_SET
1305     */
1306    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1307    /**
1308     * Indicates the view is focused, selected and its window has the focus.
1309     *
1310     * @see #FOCUSED_STATE_SET
1311     * @see #SELECTED_STATE_SET
1312     * @see #WINDOW_FOCUSED_STATE_SET
1313     */
1314    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1315    /**
1316     * Indicates the view is enabled, focused, selected and its window
1317     * has the focus.
1318     *
1319     * @see #ENABLED_STATE_SET
1320     * @see #FOCUSED_STATE_SET
1321     * @see #SELECTED_STATE_SET
1322     * @see #WINDOW_FOCUSED_STATE_SET
1323     */
1324    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1325    /**
1326     * Indicates the view is pressed and its window has the focus.
1327     *
1328     * @see #PRESSED_STATE_SET
1329     * @see #WINDOW_FOCUSED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed and selected.
1334     *
1335     * @see #PRESSED_STATE_SET
1336     * @see #SELECTED_STATE_SET
1337     */
1338    protected static final int[] PRESSED_SELECTED_STATE_SET;
1339    /**
1340     * Indicates the view is pressed, selected and its window has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #SELECTED_STATE_SET
1344     * @see #WINDOW_FOCUSED_STATE_SET
1345     */
1346    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1347    /**
1348     * Indicates the view is pressed and focused.
1349     *
1350     * @see #PRESSED_STATE_SET
1351     * @see #FOCUSED_STATE_SET
1352     */
1353    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1354    /**
1355     * Indicates the view is pressed, focused and its window has the focus.
1356     *
1357     * @see #PRESSED_STATE_SET
1358     * @see #FOCUSED_STATE_SET
1359     * @see #WINDOW_FOCUSED_STATE_SET
1360     */
1361    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1362    /**
1363     * Indicates the view is pressed, focused and selected.
1364     *
1365     * @see #PRESSED_STATE_SET
1366     * @see #SELECTED_STATE_SET
1367     * @see #FOCUSED_STATE_SET
1368     */
1369    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1370    /**
1371     * Indicates the view is pressed, focused, selected and its window has the focus.
1372     *
1373     * @see #PRESSED_STATE_SET
1374     * @see #FOCUSED_STATE_SET
1375     * @see #SELECTED_STATE_SET
1376     * @see #WINDOW_FOCUSED_STATE_SET
1377     */
1378    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1379    /**
1380     * Indicates the view is pressed and enabled.
1381     *
1382     * @see #PRESSED_STATE_SET
1383     * @see #ENABLED_STATE_SET
1384     */
1385    protected static final int[] PRESSED_ENABLED_STATE_SET;
1386    /**
1387     * Indicates the view is pressed, enabled and its window has the focus.
1388     *
1389     * @see #PRESSED_STATE_SET
1390     * @see #ENABLED_STATE_SET
1391     * @see #WINDOW_FOCUSED_STATE_SET
1392     */
1393    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1394    /**
1395     * Indicates the view is pressed, enabled and selected.
1396     *
1397     * @see #PRESSED_STATE_SET
1398     * @see #ENABLED_STATE_SET
1399     * @see #SELECTED_STATE_SET
1400     */
1401    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1402    /**
1403     * Indicates the view is pressed, enabled, selected and its window has the
1404     * focus.
1405     *
1406     * @see #PRESSED_STATE_SET
1407     * @see #ENABLED_STATE_SET
1408     * @see #SELECTED_STATE_SET
1409     * @see #WINDOW_FOCUSED_STATE_SET
1410     */
1411    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1412    /**
1413     * Indicates the view is pressed, enabled and focused.
1414     *
1415     * @see #PRESSED_STATE_SET
1416     * @see #ENABLED_STATE_SET
1417     * @see #FOCUSED_STATE_SET
1418     */
1419    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1420    /**
1421     * Indicates the view is pressed, enabled, focused and its window has the
1422     * focus.
1423     *
1424     * @see #PRESSED_STATE_SET
1425     * @see #ENABLED_STATE_SET
1426     * @see #FOCUSED_STATE_SET
1427     * @see #WINDOW_FOCUSED_STATE_SET
1428     */
1429    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1430    /**
1431     * Indicates the view is pressed, enabled, focused and selected.
1432     *
1433     * @see #PRESSED_STATE_SET
1434     * @see #ENABLED_STATE_SET
1435     * @see #SELECTED_STATE_SET
1436     * @see #FOCUSED_STATE_SET
1437     */
1438    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1439    /**
1440     * Indicates the view is pressed, enabled, focused, selected and its window
1441     * has the focus.
1442     *
1443     * @see #PRESSED_STATE_SET
1444     * @see #ENABLED_STATE_SET
1445     * @see #SELECTED_STATE_SET
1446     * @see #FOCUSED_STATE_SET
1447     * @see #WINDOW_FOCUSED_STATE_SET
1448     */
1449    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1450
1451    static {
1452        EMPTY_STATE_SET = StateSet.get(0);
1453
1454        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1455
1456        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1457        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1458                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1459
1460        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1461        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1462                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1463        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1464                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1465        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1466                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1467                        | StateSet.VIEW_STATE_FOCUSED);
1468
1469        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1470        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1471                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1472        ENABLED_SELECTED_STATE_SET = StateSet.get(
1473                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1474        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1475                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1476                        | StateSet.VIEW_STATE_ENABLED);
1477        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1478                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1479        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1480                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1481                        | StateSet.VIEW_STATE_ENABLED);
1482        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1483                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1484                        | StateSet.VIEW_STATE_ENABLED);
1485        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1486                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1487                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1488
1489        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1490        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1491                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1492        PRESSED_SELECTED_STATE_SET = StateSet.get(
1493                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1494        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1495                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1496                        | StateSet.VIEW_STATE_PRESSED);
1497        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1498                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1499        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1500                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1501                        | StateSet.VIEW_STATE_PRESSED);
1502        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1503                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1504                        | StateSet.VIEW_STATE_PRESSED);
1505        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1506                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1507                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1508        PRESSED_ENABLED_STATE_SET = StateSet.get(
1509                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1510        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1511                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1512                        | StateSet.VIEW_STATE_PRESSED);
1513        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1514                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1515                        | StateSet.VIEW_STATE_PRESSED);
1516        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1517                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1518                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1519        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1520                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1521                        | StateSet.VIEW_STATE_PRESSED);
1522        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1523                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1524                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1525        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1526                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1527                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1528        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1529                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1530                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1531                        | StateSet.VIEW_STATE_PRESSED);
1532    }
1533
1534    /**
1535     * Accessibility event types that are dispatched for text population.
1536     */
1537    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1538            AccessibilityEvent.TYPE_VIEW_CLICKED
1539            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1540            | AccessibilityEvent.TYPE_VIEW_SELECTED
1541            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1542            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1543            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1544            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1545            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1546            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1547            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1548            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1549
1550    /**
1551     * Temporary Rect currently for use in setBackground().  This will probably
1552     * be extended in the future to hold our own class with more than just
1553     * a Rect. :)
1554     */
1555    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1556
1557    /**
1558     * Map used to store views' tags.
1559     */
1560    private SparseArray<Object> mKeyedTags;
1561
1562    /**
1563     * The next available accessibility id.
1564     */
1565    private static int sNextAccessibilityViewId;
1566
1567    /**
1568     * The animation currently associated with this view.
1569     * @hide
1570     */
1571    protected Animation mCurrentAnimation = null;
1572
1573    /**
1574     * Width as measured during measure pass.
1575     * {@hide}
1576     */
1577    @ViewDebug.ExportedProperty(category = "measurement")
1578    int mMeasuredWidth;
1579
1580    /**
1581     * Height as measured during measure pass.
1582     * {@hide}
1583     */
1584    @ViewDebug.ExportedProperty(category = "measurement")
1585    int mMeasuredHeight;
1586
1587    /**
1588     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1589     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1590     * its display list. This flag, used only when hw accelerated, allows us to clear the
1591     * flag while retaining this information until it's needed (at getDisplayList() time and
1592     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1593     *
1594     * {@hide}
1595     */
1596    boolean mRecreateDisplayList = false;
1597
1598    /**
1599     * The view's identifier.
1600     * {@hide}
1601     *
1602     * @see #setId(int)
1603     * @see #getId()
1604     */
1605    @IdRes
1606    @ViewDebug.ExportedProperty(resolveId = true)
1607    int mID = NO_ID;
1608
1609    /**
1610     * The stable ID of this view for accessibility purposes.
1611     */
1612    int mAccessibilityViewId = NO_ID;
1613
1614    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1615
1616    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1617
1618    /**
1619     * The view's tag.
1620     * {@hide}
1621     *
1622     * @see #setTag(Object)
1623     * @see #getTag()
1624     */
1625    protected Object mTag = null;
1626
1627    // for mPrivateFlags:
1628    /** {@hide} */
1629    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1630    /** {@hide} */
1631    static final int PFLAG_FOCUSED                     = 0x00000002;
1632    /** {@hide} */
1633    static final int PFLAG_SELECTED                    = 0x00000004;
1634    /** {@hide} */
1635    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1636    /** {@hide} */
1637    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1638    /** {@hide} */
1639    static final int PFLAG_DRAWN                       = 0x00000020;
1640    /**
1641     * When this flag is set, this view is running an animation on behalf of its
1642     * children and should therefore not cancel invalidate requests, even if they
1643     * lie outside of this view's bounds.
1644     *
1645     * {@hide}
1646     */
1647    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1648    /** {@hide} */
1649    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1650    /** {@hide} */
1651    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1652    /** {@hide} */
1653    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1654    /** {@hide} */
1655    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1656    /** {@hide} */
1657    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1658    /** {@hide} */
1659    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1660    /** {@hide} */
1661    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1662
1663    private static final int PFLAG_PRESSED             = 0x00004000;
1664
1665    /** {@hide} */
1666    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1667    /**
1668     * Flag used to indicate that this view should be drawn once more (and only once
1669     * more) after its animation has completed.
1670     * {@hide}
1671     */
1672    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1673
1674    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1675
1676    /**
1677     * Indicates that the View returned true when onSetAlpha() was called and that
1678     * the alpha must be restored.
1679     * {@hide}
1680     */
1681    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1682
1683    /**
1684     * Set by {@link #setScrollContainer(boolean)}.
1685     */
1686    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1687
1688    /**
1689     * Set by {@link #setScrollContainer(boolean)}.
1690     */
1691    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1692
1693    /**
1694     * View flag indicating whether this view was invalidated (fully or partially.)
1695     *
1696     * @hide
1697     */
1698    static final int PFLAG_DIRTY                       = 0x00200000;
1699
1700    /**
1701     * View flag indicating whether this view was invalidated by an opaque
1702     * invalidate request.
1703     *
1704     * @hide
1705     */
1706    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1707
1708    /**
1709     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1710     *
1711     * @hide
1712     */
1713    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1714
1715    /**
1716     * Indicates whether the background is opaque.
1717     *
1718     * @hide
1719     */
1720    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1721
1722    /**
1723     * Indicates whether the scrollbars are opaque.
1724     *
1725     * @hide
1726     */
1727    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1728
1729    /**
1730     * Indicates whether the view is opaque.
1731     *
1732     * @hide
1733     */
1734    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1735
1736    /**
1737     * Indicates a prepressed state;
1738     * the short time between ACTION_DOWN and recognizing
1739     * a 'real' press. Prepressed is used to recognize quick taps
1740     * even when they are shorter than ViewConfiguration.getTapTimeout().
1741     *
1742     * @hide
1743     */
1744    private static final int PFLAG_PREPRESSED          = 0x02000000;
1745
1746    /**
1747     * Indicates whether the view is temporarily detached.
1748     *
1749     * @hide
1750     */
1751    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1752
1753    /**
1754     * Indicates that we should awaken scroll bars once attached
1755     *
1756     * @hide
1757     */
1758    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1759
1760    /**
1761     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1762     * @hide
1763     */
1764    private static final int PFLAG_HOVERED             = 0x10000000;
1765
1766    /**
1767     * no longer needed, should be reused
1768     */
1769    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1770
1771    /** {@hide} */
1772    static final int PFLAG_ACTIVATED                   = 0x40000000;
1773
1774    /**
1775     * Indicates that this view was specifically invalidated, not just dirtied because some
1776     * child view was invalidated. The flag is used to determine when we need to recreate
1777     * a view's display list (as opposed to just returning a reference to its existing
1778     * display list).
1779     *
1780     * @hide
1781     */
1782    static final int PFLAG_INVALIDATED                 = 0x80000000;
1783
1784    /**
1785     * Masks for mPrivateFlags2, as generated by dumpFlags():
1786     *
1787     * |-------|-------|-------|-------|
1788     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1789     *                                1  PFLAG2_DRAG_HOVERED
1790     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1791     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1792     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1793     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1794     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1795     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1796     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1797     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1798     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1799     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1800     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1801     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1802     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1803     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1804     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1805     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1806     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1807     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1808     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1809     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1810     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1811     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1812     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1813     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1814     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1815     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1816     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1817     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1818     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1819     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1820     *    1                              PFLAG2_PADDING_RESOLVED
1821     *   1                               PFLAG2_DRAWABLE_RESOLVED
1822     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1823     * |-------|-------|-------|-------|
1824     */
1825
1826    /**
1827     * Indicates that this view has reported that it can accept the current drag's content.
1828     * Cleared when the drag operation concludes.
1829     * @hide
1830     */
1831    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1832
1833    /**
1834     * Indicates that this view is currently directly under the drag location in a
1835     * drag-and-drop operation involving content that it can accept.  Cleared when
1836     * the drag exits the view, or when the drag operation concludes.
1837     * @hide
1838     */
1839    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1840
1841    /** @hide */
1842    @IntDef({
1843        LAYOUT_DIRECTION_LTR,
1844        LAYOUT_DIRECTION_RTL,
1845        LAYOUT_DIRECTION_INHERIT,
1846        LAYOUT_DIRECTION_LOCALE
1847    })
1848    @Retention(RetentionPolicy.SOURCE)
1849    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1850    public @interface LayoutDir {}
1851
1852    /** @hide */
1853    @IntDef({
1854        LAYOUT_DIRECTION_LTR,
1855        LAYOUT_DIRECTION_RTL
1856    })
1857    @Retention(RetentionPolicy.SOURCE)
1858    public @interface ResolvedLayoutDir {}
1859
1860    /**
1861     * Horizontal layout direction of this view is from Left to Right.
1862     * Use with {@link #setLayoutDirection}.
1863     */
1864    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1865
1866    /**
1867     * Horizontal layout direction of this view is from Right to Left.
1868     * Use with {@link #setLayoutDirection}.
1869     */
1870    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1871
1872    /**
1873     * Horizontal layout direction of this view is inherited from its parent.
1874     * Use with {@link #setLayoutDirection}.
1875     */
1876    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1877
1878    /**
1879     * Horizontal layout direction of this view is from deduced from the default language
1880     * script for the locale. Use with {@link #setLayoutDirection}.
1881     */
1882    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1883
1884    /**
1885     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1886     * @hide
1887     */
1888    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1889
1890    /**
1891     * Mask for use with private flags indicating bits used for horizontal layout direction.
1892     * @hide
1893     */
1894    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1895
1896    /**
1897     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1898     * right-to-left direction.
1899     * @hide
1900     */
1901    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1902
1903    /**
1904     * Indicates whether the view horizontal layout direction has been resolved.
1905     * @hide
1906     */
1907    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1908
1909    /**
1910     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1911     * @hide
1912     */
1913    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1914            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1915
1916    /*
1917     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1918     * flag value.
1919     * @hide
1920     */
1921    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1922            LAYOUT_DIRECTION_LTR,
1923            LAYOUT_DIRECTION_RTL,
1924            LAYOUT_DIRECTION_INHERIT,
1925            LAYOUT_DIRECTION_LOCALE
1926    };
1927
1928    /**
1929     * Default horizontal layout direction.
1930     */
1931    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1932
1933    /**
1934     * Default horizontal layout direction.
1935     * @hide
1936     */
1937    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1938
1939    /**
1940     * Text direction is inherited through {@link ViewGroup}
1941     */
1942    public static final int TEXT_DIRECTION_INHERIT = 0;
1943
1944    /**
1945     * Text direction is using "first strong algorithm". The first strong directional character
1946     * determines the paragraph direction. If there is no strong directional character, the
1947     * paragraph direction is the view's resolved layout direction.
1948     */
1949    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1950
1951    /**
1952     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1953     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1954     * If there are neither, the paragraph direction is the view's resolved layout direction.
1955     */
1956    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1957
1958    /**
1959     * Text direction is forced to LTR.
1960     */
1961    public static final int TEXT_DIRECTION_LTR = 3;
1962
1963    /**
1964     * Text direction is forced to RTL.
1965     */
1966    public static final int TEXT_DIRECTION_RTL = 4;
1967
1968    /**
1969     * Text direction is coming from the system Locale.
1970     */
1971    public static final int TEXT_DIRECTION_LOCALE = 5;
1972
1973    /**
1974     * Text direction is using "first strong algorithm". The first strong directional character
1975     * determines the paragraph direction. If there is no strong directional character, the
1976     * paragraph direction is LTR.
1977     */
1978    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
1979
1980    /**
1981     * Text direction is using "first strong algorithm". The first strong directional character
1982     * determines the paragraph direction. If there is no strong directional character, the
1983     * paragraph direction is RTL.
1984     */
1985    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
1986
1987    /**
1988     * Default text direction is inherited
1989     */
1990    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1991
1992    /**
1993     * Default resolved text direction
1994     * @hide
1995     */
1996    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1997
1998    /**
1999     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2000     * @hide
2001     */
2002    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2003
2004    /**
2005     * Mask for use with private flags indicating bits used for text direction.
2006     * @hide
2007     */
2008    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2009            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2010
2011    /**
2012     * Array of text direction flags for mapping attribute "textDirection" to correct
2013     * flag value.
2014     * @hide
2015     */
2016    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2017            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2018            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2019            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2020            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2021            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2022            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2023            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2024            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2025    };
2026
2027    /**
2028     * Indicates whether the view text direction has been resolved.
2029     * @hide
2030     */
2031    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2032            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2033
2034    /**
2035     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2036     * @hide
2037     */
2038    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2039
2040    /**
2041     * Mask for use with private flags indicating bits used for resolved text direction.
2042     * @hide
2043     */
2044    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2045            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2046
2047    /**
2048     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2049     * @hide
2050     */
2051    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2052            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2053
2054    /** @hide */
2055    @IntDef({
2056        TEXT_ALIGNMENT_INHERIT,
2057        TEXT_ALIGNMENT_GRAVITY,
2058        TEXT_ALIGNMENT_CENTER,
2059        TEXT_ALIGNMENT_TEXT_START,
2060        TEXT_ALIGNMENT_TEXT_END,
2061        TEXT_ALIGNMENT_VIEW_START,
2062        TEXT_ALIGNMENT_VIEW_END
2063    })
2064    @Retention(RetentionPolicy.SOURCE)
2065    public @interface TextAlignment {}
2066
2067    /**
2068     * Default text alignment. The text alignment of this View is inherited from its parent.
2069     * Use with {@link #setTextAlignment(int)}
2070     */
2071    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2072
2073    /**
2074     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2075     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2076     *
2077     * Use with {@link #setTextAlignment(int)}
2078     */
2079    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2080
2081    /**
2082     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2083     *
2084     * Use with {@link #setTextAlignment(int)}
2085     */
2086    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2087
2088    /**
2089     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2090     *
2091     * Use with {@link #setTextAlignment(int)}
2092     */
2093    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2094
2095    /**
2096     * Center the paragraph, e.g. ALIGN_CENTER.
2097     *
2098     * Use with {@link #setTextAlignment(int)}
2099     */
2100    public static final int TEXT_ALIGNMENT_CENTER = 4;
2101
2102    /**
2103     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2104     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2105     *
2106     * Use with {@link #setTextAlignment(int)}
2107     */
2108    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2109
2110    /**
2111     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2112     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2113     *
2114     * Use with {@link #setTextAlignment(int)}
2115     */
2116    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2117
2118    /**
2119     * Default text alignment is inherited
2120     */
2121    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2122
2123    /**
2124     * Default resolved text alignment
2125     * @hide
2126     */
2127    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2128
2129    /**
2130      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2131      * @hide
2132      */
2133    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2134
2135    /**
2136      * Mask for use with private flags indicating bits used for text alignment.
2137      * @hide
2138      */
2139    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2140
2141    /**
2142     * Array of text direction flags for mapping attribute "textAlignment" to correct
2143     * flag value.
2144     * @hide
2145     */
2146    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2147            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2148            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2149            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2150            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2151            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2152            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2153            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2154    };
2155
2156    /**
2157     * Indicates whether the view text alignment has been resolved.
2158     * @hide
2159     */
2160    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2161
2162    /**
2163     * Bit shift to get the resolved text alignment.
2164     * @hide
2165     */
2166    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2167
2168    /**
2169     * Mask for use with private flags indicating bits used for text alignment.
2170     * @hide
2171     */
2172    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2173            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2174
2175    /**
2176     * Indicates whether if the view text alignment has been resolved to gravity
2177     */
2178    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2179            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2180
2181    // Accessiblity constants for mPrivateFlags2
2182
2183    /**
2184     * Shift for the bits in {@link #mPrivateFlags2} related to the
2185     * "importantForAccessibility" attribute.
2186     */
2187    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2188
2189    /**
2190     * Automatically determine whether a view is important for accessibility.
2191     */
2192    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2193
2194    /**
2195     * The view is important for accessibility.
2196     */
2197    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2198
2199    /**
2200     * The view is not important for accessibility.
2201     */
2202    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2203
2204    /**
2205     * The view is not important for accessibility, nor are any of its
2206     * descendant views.
2207     */
2208    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2209
2210    /**
2211     * The default whether the view is important for accessibility.
2212     */
2213    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2214
2215    /**
2216     * Mask for obtainig the bits which specify how to determine
2217     * whether a view is important for accessibility.
2218     */
2219    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2220        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2221        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2222        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2223
2224    /**
2225     * Shift for the bits in {@link #mPrivateFlags2} related to the
2226     * "accessibilityLiveRegion" attribute.
2227     */
2228    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2229
2230    /**
2231     * Live region mode specifying that accessibility services should not
2232     * automatically announce changes to this view. This is the default live
2233     * region mode for most views.
2234     * <p>
2235     * Use with {@link #setAccessibilityLiveRegion(int)}.
2236     */
2237    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2238
2239    /**
2240     * Live region mode specifying that accessibility services should announce
2241     * changes to this view.
2242     * <p>
2243     * Use with {@link #setAccessibilityLiveRegion(int)}.
2244     */
2245    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2246
2247    /**
2248     * Live region mode specifying that accessibility services should interrupt
2249     * ongoing speech to immediately announce changes to this view.
2250     * <p>
2251     * Use with {@link #setAccessibilityLiveRegion(int)}.
2252     */
2253    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2254
2255    /**
2256     * The default whether the view is important for accessibility.
2257     */
2258    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2259
2260    /**
2261     * Mask for obtaining the bits which specify a view's accessibility live
2262     * region mode.
2263     */
2264    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2265            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2266            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2267
2268    /**
2269     * Flag indicating whether a view has accessibility focus.
2270     */
2271    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2272
2273    /**
2274     * Flag whether the accessibility state of the subtree rooted at this view changed.
2275     */
2276    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2277
2278    /**
2279     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2280     * is used to check whether later changes to the view's transform should invalidate the
2281     * view to force the quickReject test to run again.
2282     */
2283    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2284
2285    /**
2286     * Flag indicating that start/end padding has been resolved into left/right padding
2287     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2288     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2289     * during measurement. In some special cases this is required such as when an adapter-based
2290     * view measures prospective children without attaching them to a window.
2291     */
2292    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2293
2294    /**
2295     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2296     */
2297    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2298
2299    /**
2300     * Indicates that the view is tracking some sort of transient state
2301     * that the app should not need to be aware of, but that the framework
2302     * should take special care to preserve.
2303     */
2304    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2305
2306    /**
2307     * Group of bits indicating that RTL properties resolution is done.
2308     */
2309    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2310            PFLAG2_TEXT_DIRECTION_RESOLVED |
2311            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2312            PFLAG2_PADDING_RESOLVED |
2313            PFLAG2_DRAWABLE_RESOLVED;
2314
2315    // There are a couple of flags left in mPrivateFlags2
2316
2317    /* End of masks for mPrivateFlags2 */
2318
2319    /**
2320     * Masks for mPrivateFlags3, as generated by dumpFlags():
2321     *
2322     * |-------|-------|-------|-------|
2323     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2324     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2325     *                               1   PFLAG3_IS_LAID_OUT
2326     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2327     *                             1     PFLAG3_CALLED_SUPER
2328     *                            1      PFLAG3_APPLYING_INSETS
2329     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2330     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2331     *                         1         PFLAG3_ASSIST_BLOCKED
2332     * |-------|-------|-------|-------|
2333     */
2334
2335    /**
2336     * Flag indicating that view has a transform animation set on it. This is used to track whether
2337     * an animation is cleared between successive frames, in order to tell the associated
2338     * DisplayList to clear its animation matrix.
2339     */
2340    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2341
2342    /**
2343     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2344     * animation is cleared between successive frames, in order to tell the associated
2345     * DisplayList to restore its alpha value.
2346     */
2347    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2348
2349    /**
2350     * Flag indicating that the view has been through at least one layout since it
2351     * was last attached to a window.
2352     */
2353    static final int PFLAG3_IS_LAID_OUT = 0x4;
2354
2355    /**
2356     * Flag indicating that a call to measure() was skipped and should be done
2357     * instead when layout() is invoked.
2358     */
2359    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2360
2361    /**
2362     * Flag indicating that an overridden method correctly called down to
2363     * the superclass implementation as required by the API spec.
2364     */
2365    static final int PFLAG3_CALLED_SUPER = 0x10;
2366
2367    /**
2368     * Flag indicating that we're in the process of applying window insets.
2369     */
2370    static final int PFLAG3_APPLYING_INSETS = 0x20;
2371
2372    /**
2373     * Flag indicating that we're in the process of fitting system windows using the old method.
2374     */
2375    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2376
2377    /**
2378     * Flag indicating that nested scrolling is enabled for this view.
2379     * The view will optionally cooperate with views up its parent chain to allow for
2380     * integrated nested scrolling along the same axis.
2381     */
2382    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2383
2384    /* End of masks for mPrivateFlags3 */
2385
2386    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2387
2388    /**
2389     * <p>Indicates that we are allowing {@link android.view.ViewAssistStructure} to traverse
2390     * into this view.<p>
2391     */
2392    static final int PFLAG3_ASSIST_BLOCKED = 0x100;
2393
2394    /**
2395     * Always allow a user to over-scroll this view, provided it is a
2396     * view that can scroll.
2397     *
2398     * @see #getOverScrollMode()
2399     * @see #setOverScrollMode(int)
2400     */
2401    public static final int OVER_SCROLL_ALWAYS = 0;
2402
2403    /**
2404     * Allow a user to over-scroll this view only if the content is large
2405     * enough to meaningfully scroll, provided it is a view that can scroll.
2406     *
2407     * @see #getOverScrollMode()
2408     * @see #setOverScrollMode(int)
2409     */
2410    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2411
2412    /**
2413     * Never allow a user to over-scroll this view.
2414     *
2415     * @see #getOverScrollMode()
2416     * @see #setOverScrollMode(int)
2417     */
2418    public static final int OVER_SCROLL_NEVER = 2;
2419
2420    /**
2421     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2422     * requested the system UI (status bar) to be visible (the default).
2423     *
2424     * @see #setSystemUiVisibility(int)
2425     */
2426    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2427
2428    /**
2429     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2430     * system UI to enter an unobtrusive "low profile" mode.
2431     *
2432     * <p>This is for use in games, book readers, video players, or any other
2433     * "immersive" application where the usual system chrome is deemed too distracting.
2434     *
2435     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2436     *
2437     * @see #setSystemUiVisibility(int)
2438     */
2439    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2440
2441    /**
2442     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2443     * system navigation be temporarily hidden.
2444     *
2445     * <p>This is an even less obtrusive state than that called for by
2446     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2447     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2448     * those to disappear. This is useful (in conjunction with the
2449     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2450     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2451     * window flags) for displaying content using every last pixel on the display.
2452     *
2453     * <p>There is a limitation: because navigation controls are so important, the least user
2454     * interaction will cause them to reappear immediately.  When this happens, both
2455     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2456     * so that both elements reappear at the same time.
2457     *
2458     * @see #setSystemUiVisibility(int)
2459     */
2460    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2461
2462    /**
2463     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2464     * into the normal fullscreen mode so that its content can take over the screen
2465     * while still allowing the user to interact with the application.
2466     *
2467     * <p>This has the same visual effect as
2468     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2469     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2470     * meaning that non-critical screen decorations (such as the status bar) will be
2471     * hidden while the user is in the View's window, focusing the experience on
2472     * that content.  Unlike the window flag, if you are using ActionBar in
2473     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2474     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2475     * hide the action bar.
2476     *
2477     * <p>This approach to going fullscreen is best used over the window flag when
2478     * it is a transient state -- that is, the application does this at certain
2479     * points in its user interaction where it wants to allow the user to focus
2480     * on content, but not as a continuous state.  For situations where the application
2481     * would like to simply stay full screen the entire time (such as a game that
2482     * wants to take over the screen), the
2483     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2484     * is usually a better approach.  The state set here will be removed by the system
2485     * in various situations (such as the user moving to another application) like
2486     * the other system UI states.
2487     *
2488     * <p>When using this flag, the application should provide some easy facility
2489     * for the user to go out of it.  A common example would be in an e-book
2490     * reader, where tapping on the screen brings back whatever screen and UI
2491     * decorations that had been hidden while the user was immersed in reading
2492     * the book.
2493     *
2494     * @see #setSystemUiVisibility(int)
2495     */
2496    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2497
2498    /**
2499     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2500     * flags, we would like a stable view of the content insets given to
2501     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2502     * will always represent the worst case that the application can expect
2503     * as a continuous state.  In the stock Android UI this is the space for
2504     * the system bar, nav bar, and status bar, but not more transient elements
2505     * such as an input method.
2506     *
2507     * The stable layout your UI sees is based on the system UI modes you can
2508     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2509     * then you will get a stable layout for changes of the
2510     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2511     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2512     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2513     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2514     * with a stable layout.  (Note that you should avoid using
2515     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2516     *
2517     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2518     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2519     * then a hidden status bar will be considered a "stable" state for purposes
2520     * here.  This allows your UI to continually hide the status bar, while still
2521     * using the system UI flags to hide the action bar while still retaining
2522     * a stable layout.  Note that changing the window fullscreen flag will never
2523     * provide a stable layout for a clean transition.
2524     *
2525     * <p>If you are using ActionBar in
2526     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2527     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2528     * insets it adds to those given to the application.
2529     */
2530    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2531
2532    /**
2533     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2534     * to be laid out as if it has requested
2535     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2536     * allows it to avoid artifacts when switching in and out of that mode, at
2537     * the expense that some of its user interface may be covered by screen
2538     * decorations when they are shown.  You can perform layout of your inner
2539     * UI elements to account for the navigation system UI through the
2540     * {@link #fitSystemWindows(Rect)} method.
2541     */
2542    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2543
2544    /**
2545     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2546     * to be laid out as if it has requested
2547     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2548     * allows it to avoid artifacts when switching in and out of that mode, at
2549     * the expense that some of its user interface may be covered by screen
2550     * decorations when they are shown.  You can perform layout of your inner
2551     * UI elements to account for non-fullscreen system UI through the
2552     * {@link #fitSystemWindows(Rect)} method.
2553     */
2554    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2555
2556    /**
2557     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2558     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2559     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2560     * user interaction.
2561     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2562     * has an effect when used in combination with that flag.</p>
2563     */
2564    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2565
2566    /**
2567     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2568     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2569     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2570     * experience while also hiding the system bars.  If this flag is not set,
2571     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2572     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2573     * if the user swipes from the top of the screen.
2574     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2575     * system gestures, such as swiping from the top of the screen.  These transient system bars
2576     * will overlay app’s content, may have some degree of transparency, and will automatically
2577     * hide after a short timeout.
2578     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2579     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2580     * with one or both of those flags.</p>
2581     */
2582    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2583
2584    /**
2585     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2586     * is compatible with light status bar backgrounds.
2587     *
2588     * <p>For this to take effect, the window must request
2589     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2590     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2591     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2592     *         FLAG_TRANSLUCENT_STATUS}.
2593     *
2594     * @see android.R.attr#windowHasLightStatusBar
2595     */
2596    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2597
2598    /**
2599     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2600     */
2601    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2602
2603    /**
2604     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2605     */
2606    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2607
2608    /**
2609     * @hide
2610     *
2611     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2612     * out of the public fields to keep the undefined bits out of the developer's way.
2613     *
2614     * Flag to make the status bar not expandable.  Unless you also
2615     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2616     */
2617    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2618
2619    /**
2620     * @hide
2621     *
2622     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2623     * out of the public fields to keep the undefined bits out of the developer's way.
2624     *
2625     * Flag to hide notification icons and scrolling ticker text.
2626     */
2627    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2628
2629    /**
2630     * @hide
2631     *
2632     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2633     * out of the public fields to keep the undefined bits out of the developer's way.
2634     *
2635     * Flag to disable incoming notification alerts.  This will not block
2636     * icons, but it will block sound, vibrating and other visual or aural notifications.
2637     */
2638    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2639
2640    /**
2641     * @hide
2642     *
2643     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2644     * out of the public fields to keep the undefined bits out of the developer's way.
2645     *
2646     * Flag to hide only the scrolling ticker.  Note that
2647     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2648     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2649     */
2650    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2651
2652    /**
2653     * @hide
2654     *
2655     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2656     * out of the public fields to keep the undefined bits out of the developer's way.
2657     *
2658     * Flag to hide the center system info area.
2659     */
2660    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2661
2662    /**
2663     * @hide
2664     *
2665     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2666     * out of the public fields to keep the undefined bits out of the developer's way.
2667     *
2668     * Flag to hide only the home button.  Don't use this
2669     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2670     */
2671    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2672
2673    /**
2674     * @hide
2675     *
2676     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2677     * out of the public fields to keep the undefined bits out of the developer's way.
2678     *
2679     * Flag to hide only the back button. Don't use this
2680     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2681     */
2682    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2683
2684    /**
2685     * @hide
2686     *
2687     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2688     * out of the public fields to keep the undefined bits out of the developer's way.
2689     *
2690     * Flag to hide only the clock.  You might use this if your activity has
2691     * its own clock making the status bar's clock redundant.
2692     */
2693    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2694
2695    /**
2696     * @hide
2697     *
2698     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2699     * out of the public fields to keep the undefined bits out of the developer's way.
2700     *
2701     * Flag to hide only the recent apps button. Don't use this
2702     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2703     */
2704    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2705
2706    /**
2707     * @hide
2708     *
2709     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2710     * out of the public fields to keep the undefined bits out of the developer's way.
2711     *
2712     * Flag to disable the global search gesture. Don't use this
2713     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2714     */
2715    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2716
2717    /**
2718     * @hide
2719     *
2720     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2721     * out of the public fields to keep the undefined bits out of the developer's way.
2722     *
2723     * Flag to specify that the status bar is displayed in transient mode.
2724     */
2725    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2726
2727    /**
2728     * @hide
2729     *
2730     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2731     * out of the public fields to keep the undefined bits out of the developer's way.
2732     *
2733     * Flag to specify that the navigation bar is displayed in transient mode.
2734     */
2735    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2736
2737    /**
2738     * @hide
2739     *
2740     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2741     * out of the public fields to keep the undefined bits out of the developer's way.
2742     *
2743     * Flag to specify that the hidden status bar would like to be shown.
2744     */
2745    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2746
2747    /**
2748     * @hide
2749     *
2750     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2751     * out of the public fields to keep the undefined bits out of the developer's way.
2752     *
2753     * Flag to specify that the hidden navigation bar would like to be shown.
2754     */
2755    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2756
2757    /**
2758     * @hide
2759     *
2760     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2761     * out of the public fields to keep the undefined bits out of the developer's way.
2762     *
2763     * Flag to specify that the status bar is displayed in translucent mode.
2764     */
2765    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2766
2767    /**
2768     * @hide
2769     *
2770     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2771     * out of the public fields to keep the undefined bits out of the developer's way.
2772     *
2773     * Flag to specify that the navigation bar is displayed in translucent mode.
2774     */
2775    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2776
2777    /**
2778     * @hide
2779     *
2780     * Whether Recents is visible or not.
2781     */
2782    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2783
2784    /**
2785     * @hide
2786     *
2787     * Makes system ui transparent.
2788     */
2789    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2790
2791    /**
2792     * @hide
2793     */
2794    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2795
2796    /**
2797     * These are the system UI flags that can be cleared by events outside
2798     * of an application.  Currently this is just the ability to tap on the
2799     * screen while hiding the navigation bar to have it return.
2800     * @hide
2801     */
2802    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2803            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2804            | SYSTEM_UI_FLAG_FULLSCREEN;
2805
2806    /**
2807     * Flags that can impact the layout in relation to system UI.
2808     */
2809    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2810            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2811            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2812
2813    /** @hide */
2814    @IntDef(flag = true,
2815            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2816    @Retention(RetentionPolicy.SOURCE)
2817    public @interface FindViewFlags {}
2818
2819    /**
2820     * Find views that render the specified text.
2821     *
2822     * @see #findViewsWithText(ArrayList, CharSequence, int)
2823     */
2824    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2825
2826    /**
2827     * Find find views that contain the specified content description.
2828     *
2829     * @see #findViewsWithText(ArrayList, CharSequence, int)
2830     */
2831    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2832
2833    /**
2834     * Find views that contain {@link AccessibilityNodeProvider}. Such
2835     * a View is a root of virtual view hierarchy and may contain the searched
2836     * text. If this flag is set Views with providers are automatically
2837     * added and it is a responsibility of the client to call the APIs of
2838     * the provider to determine whether the virtual tree rooted at this View
2839     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2840     * representing the virtual views with this text.
2841     *
2842     * @see #findViewsWithText(ArrayList, CharSequence, int)
2843     *
2844     * @hide
2845     */
2846    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2847
2848    /**
2849     * The undefined cursor position.
2850     *
2851     * @hide
2852     */
2853    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2854
2855    /**
2856     * Indicates that the screen has changed state and is now off.
2857     *
2858     * @see #onScreenStateChanged(int)
2859     */
2860    public static final int SCREEN_STATE_OFF = 0x0;
2861
2862    /**
2863     * Indicates that the screen has changed state and is now on.
2864     *
2865     * @see #onScreenStateChanged(int)
2866     */
2867    public static final int SCREEN_STATE_ON = 0x1;
2868
2869    /**
2870     * Indicates no axis of view scrolling.
2871     */
2872    public static final int SCROLL_AXIS_NONE = 0;
2873
2874    /**
2875     * Indicates scrolling along the horizontal axis.
2876     */
2877    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2878
2879    /**
2880     * Indicates scrolling along the vertical axis.
2881     */
2882    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2883
2884    /**
2885     * Controls the over-scroll mode for this view.
2886     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2887     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2888     * and {@link #OVER_SCROLL_NEVER}.
2889     */
2890    private int mOverScrollMode;
2891
2892    /**
2893     * The parent this view is attached to.
2894     * {@hide}
2895     *
2896     * @see #getParent()
2897     */
2898    protected ViewParent mParent;
2899
2900    /**
2901     * {@hide}
2902     */
2903    AttachInfo mAttachInfo;
2904
2905    /**
2906     * {@hide}
2907     */
2908    @ViewDebug.ExportedProperty(flagMapping = {
2909        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2910                name = "FORCE_LAYOUT"),
2911        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2912                name = "LAYOUT_REQUIRED"),
2913        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2914            name = "DRAWING_CACHE_INVALID", outputIf = false),
2915        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2916        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2917        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2918        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2919    }, formatToHexString = true)
2920    int mPrivateFlags;
2921    int mPrivateFlags2;
2922    int mPrivateFlags3;
2923
2924    /**
2925     * This view's request for the visibility of the status bar.
2926     * @hide
2927     */
2928    @ViewDebug.ExportedProperty(flagMapping = {
2929        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2930                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2931                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2932        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2933                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2934                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2935        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2936                                equals = SYSTEM_UI_FLAG_VISIBLE,
2937                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2938    }, formatToHexString = true)
2939    int mSystemUiVisibility;
2940
2941    /**
2942     * Reference count for transient state.
2943     * @see #setHasTransientState(boolean)
2944     */
2945    int mTransientStateCount = 0;
2946
2947    /**
2948     * Count of how many windows this view has been attached to.
2949     */
2950    int mWindowAttachCount;
2951
2952    /**
2953     * The layout parameters associated with this view and used by the parent
2954     * {@link android.view.ViewGroup} to determine how this view should be
2955     * laid out.
2956     * {@hide}
2957     */
2958    protected ViewGroup.LayoutParams mLayoutParams;
2959
2960    /**
2961     * The view flags hold various views states.
2962     * {@hide}
2963     */
2964    @ViewDebug.ExportedProperty(formatToHexString = true)
2965    int mViewFlags;
2966
2967    static class TransformationInfo {
2968        /**
2969         * The transform matrix for the View. This transform is calculated internally
2970         * based on the translation, rotation, and scale properties.
2971         *
2972         * Do *not* use this variable directly; instead call getMatrix(), which will
2973         * load the value from the View's RenderNode.
2974         */
2975        private final Matrix mMatrix = new Matrix();
2976
2977        /**
2978         * The inverse transform matrix for the View. This transform is calculated
2979         * internally based on the translation, rotation, and scale properties.
2980         *
2981         * Do *not* use this variable directly; instead call getInverseMatrix(),
2982         * which will load the value from the View's RenderNode.
2983         */
2984        private Matrix mInverseMatrix;
2985
2986        /**
2987         * The opacity of the View. This is a value from 0 to 1, where 0 means
2988         * completely transparent and 1 means completely opaque.
2989         */
2990        @ViewDebug.ExportedProperty
2991        float mAlpha = 1f;
2992
2993        /**
2994         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2995         * property only used by transitions, which is composited with the other alpha
2996         * values to calculate the final visual alpha value.
2997         */
2998        float mTransitionAlpha = 1f;
2999    }
3000
3001    TransformationInfo mTransformationInfo;
3002
3003    /**
3004     * Current clip bounds. to which all drawing of this view are constrained.
3005     */
3006    Rect mClipBounds = null;
3007
3008    private boolean mLastIsOpaque;
3009
3010    /**
3011     * The distance in pixels from the left edge of this view's parent
3012     * to the left edge of this view.
3013     * {@hide}
3014     */
3015    @ViewDebug.ExportedProperty(category = "layout")
3016    protected int mLeft;
3017    /**
3018     * The distance in pixels from the left edge of this view's parent
3019     * to the right edge of this view.
3020     * {@hide}
3021     */
3022    @ViewDebug.ExportedProperty(category = "layout")
3023    protected int mRight;
3024    /**
3025     * The distance in pixels from the top edge of this view's parent
3026     * to the top edge of this view.
3027     * {@hide}
3028     */
3029    @ViewDebug.ExportedProperty(category = "layout")
3030    protected int mTop;
3031    /**
3032     * The distance in pixels from the top edge of this view's parent
3033     * to the bottom edge of this view.
3034     * {@hide}
3035     */
3036    @ViewDebug.ExportedProperty(category = "layout")
3037    protected int mBottom;
3038
3039    /**
3040     * The offset, in pixels, by which the content of this view is scrolled
3041     * horizontally.
3042     * {@hide}
3043     */
3044    @ViewDebug.ExportedProperty(category = "scrolling")
3045    protected int mScrollX;
3046    /**
3047     * The offset, in pixels, by which the content of this view is scrolled
3048     * vertically.
3049     * {@hide}
3050     */
3051    @ViewDebug.ExportedProperty(category = "scrolling")
3052    protected int mScrollY;
3053
3054    /**
3055     * The left padding in pixels, that is the distance in pixels between the
3056     * left edge of this view and the left edge of its content.
3057     * {@hide}
3058     */
3059    @ViewDebug.ExportedProperty(category = "padding")
3060    protected int mPaddingLeft = 0;
3061    /**
3062     * The right padding in pixels, that is the distance in pixels between the
3063     * right edge of this view and the right edge of its content.
3064     * {@hide}
3065     */
3066    @ViewDebug.ExportedProperty(category = "padding")
3067    protected int mPaddingRight = 0;
3068    /**
3069     * The top padding in pixels, that is the distance in pixels between the
3070     * top edge of this view and the top edge of its content.
3071     * {@hide}
3072     */
3073    @ViewDebug.ExportedProperty(category = "padding")
3074    protected int mPaddingTop;
3075    /**
3076     * The bottom padding in pixels, that is the distance in pixels between the
3077     * bottom edge of this view and the bottom edge of its content.
3078     * {@hide}
3079     */
3080    @ViewDebug.ExportedProperty(category = "padding")
3081    protected int mPaddingBottom;
3082
3083    /**
3084     * The layout insets in pixels, that is the distance in pixels between the
3085     * visible edges of this view its bounds.
3086     */
3087    private Insets mLayoutInsets;
3088
3089    /**
3090     * Briefly describes the view and is primarily used for accessibility support.
3091     */
3092    private CharSequence mContentDescription;
3093
3094    /**
3095     * Specifies the id of a view for which this view serves as a label for
3096     * accessibility purposes.
3097     */
3098    private int mLabelForId = View.NO_ID;
3099
3100    /**
3101     * Predicate for matching labeled view id with its label for
3102     * accessibility purposes.
3103     */
3104    private MatchLabelForPredicate mMatchLabelForPredicate;
3105
3106    /**
3107     * Specifies a view before which this one is visited in accessibility traversal.
3108     */
3109    private int mAccessibilityTraversalBeforeId = NO_ID;
3110
3111    /**
3112     * Specifies a view after which this one is visited in accessibility traversal.
3113     */
3114    private int mAccessibilityTraversalAfterId = NO_ID;
3115
3116    /**
3117     * Predicate for matching a view by its id.
3118     */
3119    private MatchIdPredicate mMatchIdPredicate;
3120
3121    /**
3122     * Cache the paddingRight set by the user to append to the scrollbar's size.
3123     *
3124     * @hide
3125     */
3126    @ViewDebug.ExportedProperty(category = "padding")
3127    protected int mUserPaddingRight;
3128
3129    /**
3130     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3131     *
3132     * @hide
3133     */
3134    @ViewDebug.ExportedProperty(category = "padding")
3135    protected int mUserPaddingBottom;
3136
3137    /**
3138     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3139     *
3140     * @hide
3141     */
3142    @ViewDebug.ExportedProperty(category = "padding")
3143    protected int mUserPaddingLeft;
3144
3145    /**
3146     * Cache the paddingStart set by the user to append to the scrollbar's size.
3147     *
3148     */
3149    @ViewDebug.ExportedProperty(category = "padding")
3150    int mUserPaddingStart;
3151
3152    /**
3153     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3154     *
3155     */
3156    @ViewDebug.ExportedProperty(category = "padding")
3157    int mUserPaddingEnd;
3158
3159    /**
3160     * Cache initial left padding.
3161     *
3162     * @hide
3163     */
3164    int mUserPaddingLeftInitial;
3165
3166    /**
3167     * Cache initial right padding.
3168     *
3169     * @hide
3170     */
3171    int mUserPaddingRightInitial;
3172
3173    /**
3174     * Default undefined padding
3175     */
3176    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3177
3178    /**
3179     * Cache if a left padding has been defined
3180     */
3181    private boolean mLeftPaddingDefined = false;
3182
3183    /**
3184     * Cache if a right padding has been defined
3185     */
3186    private boolean mRightPaddingDefined = false;
3187
3188    /**
3189     * @hide
3190     */
3191    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3192    /**
3193     * @hide
3194     */
3195    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3196
3197    private LongSparseLongArray mMeasureCache;
3198
3199    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3200    private Drawable mBackground;
3201    private TintInfo mBackgroundTint;
3202
3203    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3204    private ForegroundInfo mForegroundInfo;
3205
3206    /**
3207     * RenderNode used for backgrounds.
3208     * <p>
3209     * When non-null and valid, this is expected to contain an up-to-date copy
3210     * of the background drawable. It is cleared on temporary detach, and reset
3211     * on cleanup.
3212     */
3213    private RenderNode mBackgroundRenderNode;
3214
3215    private int mBackgroundResource;
3216    private boolean mBackgroundSizeChanged;
3217
3218    private String mTransitionName;
3219
3220    static class TintInfo {
3221        ColorStateList mTintList;
3222        PorterDuff.Mode mTintMode;
3223        boolean mHasTintMode;
3224        boolean mHasTintList;
3225    }
3226
3227    private static class ForegroundInfo {
3228        private Drawable mDrawable;
3229        private TintInfo mTintInfo;
3230        private int mGravity = Gravity.FILL;
3231        private boolean mInsidePadding = true;
3232        private boolean mBoundsChanged = true;
3233        private final Rect mSelfBounds = new Rect();
3234        private final Rect mOverlayBounds = new Rect();
3235    }
3236
3237    static class ListenerInfo {
3238        /**
3239         * Listener used to dispatch focus change events.
3240         * This field should be made private, so it is hidden from the SDK.
3241         * {@hide}
3242         */
3243        protected OnFocusChangeListener mOnFocusChangeListener;
3244
3245        /**
3246         * Listeners for layout change events.
3247         */
3248        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3249
3250        protected OnScrollChangeListener mOnScrollChangeListener;
3251
3252        /**
3253         * Listeners for attach events.
3254         */
3255        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3256
3257        /**
3258         * Listener used to dispatch click events.
3259         * This field should be made private, so it is hidden from the SDK.
3260         * {@hide}
3261         */
3262        public OnClickListener mOnClickListener;
3263
3264        /**
3265         * Listener used to dispatch long click events.
3266         * This field should be made private, so it is hidden from the SDK.
3267         * {@hide}
3268         */
3269        protected OnLongClickListener mOnLongClickListener;
3270
3271        /**
3272         * Listener used to build the context menu.
3273         * This field should be made private, so it is hidden from the SDK.
3274         * {@hide}
3275         */
3276        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3277
3278        private OnKeyListener mOnKeyListener;
3279
3280        private OnTouchListener mOnTouchListener;
3281
3282        private OnHoverListener mOnHoverListener;
3283
3284        private OnGenericMotionListener mOnGenericMotionListener;
3285
3286        private OnDragListener mOnDragListener;
3287
3288        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3289
3290        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3291    }
3292
3293    ListenerInfo mListenerInfo;
3294
3295    /**
3296     * The application environment this view lives in.
3297     * This field should be made private, so it is hidden from the SDK.
3298     * {@hide}
3299     */
3300    @ViewDebug.ExportedProperty(deepExport = true)
3301    protected Context mContext;
3302
3303    private final Resources mResources;
3304
3305    private ScrollabilityCache mScrollCache;
3306
3307    private int[] mDrawableState = null;
3308
3309    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3310
3311    /**
3312     * Animator that automatically runs based on state changes.
3313     */
3314    private StateListAnimator mStateListAnimator;
3315
3316    /**
3317     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3318     * the user may specify which view to go to next.
3319     */
3320    private int mNextFocusLeftId = View.NO_ID;
3321
3322    /**
3323     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3324     * the user may specify which view to go to next.
3325     */
3326    private int mNextFocusRightId = View.NO_ID;
3327
3328    /**
3329     * When this view has focus and the next focus is {@link #FOCUS_UP},
3330     * the user may specify which view to go to next.
3331     */
3332    private int mNextFocusUpId = View.NO_ID;
3333
3334    /**
3335     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3336     * the user may specify which view to go to next.
3337     */
3338    private int mNextFocusDownId = View.NO_ID;
3339
3340    /**
3341     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3342     * the user may specify which view to go to next.
3343     */
3344    int mNextFocusForwardId = View.NO_ID;
3345
3346    private CheckForLongPress mPendingCheckForLongPress;
3347    private CheckForTap mPendingCheckForTap = null;
3348    private PerformClick mPerformClick;
3349    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3350
3351    private UnsetPressedState mUnsetPressedState;
3352
3353    /**
3354     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3355     * up event while a long press is invoked as soon as the long press duration is reached, so
3356     * a long press could be performed before the tap is checked, in which case the tap's action
3357     * should not be invoked.
3358     */
3359    private boolean mHasPerformedLongPress;
3360
3361    /**
3362     * The minimum height of the view. We'll try our best to have the height
3363     * of this view to at least this amount.
3364     */
3365    @ViewDebug.ExportedProperty(category = "measurement")
3366    private int mMinHeight;
3367
3368    /**
3369     * The minimum width of the view. We'll try our best to have the width
3370     * of this view to at least this amount.
3371     */
3372    @ViewDebug.ExportedProperty(category = "measurement")
3373    private int mMinWidth;
3374
3375    /**
3376     * The delegate to handle touch events that are physically in this view
3377     * but should be handled by another view.
3378     */
3379    private TouchDelegate mTouchDelegate = null;
3380
3381    /**
3382     * Solid color to use as a background when creating the drawing cache. Enables
3383     * the cache to use 16 bit bitmaps instead of 32 bit.
3384     */
3385    private int mDrawingCacheBackgroundColor = 0;
3386
3387    /**
3388     * Special tree observer used when mAttachInfo is null.
3389     */
3390    private ViewTreeObserver mFloatingTreeObserver;
3391
3392    /**
3393     * Cache the touch slop from the context that created the view.
3394     */
3395    private int mTouchSlop;
3396
3397    /**
3398     * Object that handles automatic animation of view properties.
3399     */
3400    private ViewPropertyAnimator mAnimator = null;
3401
3402    /**
3403     * Flag indicating that a drag can cross window boundaries.  When
3404     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3405     * with this flag set, all visible applications will be able to participate
3406     * in the drag operation and receive the dragged content.
3407     *
3408     * @hide
3409     */
3410    public static final int DRAG_FLAG_GLOBAL = 1;
3411
3412    /**
3413     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3414     */
3415    private float mVerticalScrollFactor;
3416
3417    /**
3418     * Position of the vertical scroll bar.
3419     */
3420    private int mVerticalScrollbarPosition;
3421
3422    /**
3423     * Position the scroll bar at the default position as determined by the system.
3424     */
3425    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3426
3427    /**
3428     * Position the scroll bar along the left edge.
3429     */
3430    public static final int SCROLLBAR_POSITION_LEFT = 1;
3431
3432    /**
3433     * Position the scroll bar along the right edge.
3434     */
3435    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3436
3437    /**
3438     * Indicates that the view does not have a layer.
3439     *
3440     * @see #getLayerType()
3441     * @see #setLayerType(int, android.graphics.Paint)
3442     * @see #LAYER_TYPE_SOFTWARE
3443     * @see #LAYER_TYPE_HARDWARE
3444     */
3445    public static final int LAYER_TYPE_NONE = 0;
3446
3447    /**
3448     * <p>Indicates that the view has a software layer. A software layer is backed
3449     * by a bitmap and causes the view to be rendered using Android's software
3450     * rendering pipeline, even if hardware acceleration is enabled.</p>
3451     *
3452     * <p>Software layers have various usages:</p>
3453     * <p>When the application is not using hardware acceleration, a software layer
3454     * is useful to apply a specific color filter and/or blending mode and/or
3455     * translucency to a view and all its children.</p>
3456     * <p>When the application is using hardware acceleration, a software layer
3457     * is useful to render drawing primitives not supported by the hardware
3458     * accelerated pipeline. It can also be used to cache a complex view tree
3459     * into a texture and reduce the complexity of drawing operations. For instance,
3460     * when animating a complex view tree with a translation, a software layer can
3461     * be used to render the view tree only once.</p>
3462     * <p>Software layers should be avoided when the affected view tree updates
3463     * often. Every update will require to re-render the software layer, which can
3464     * potentially be slow (particularly when hardware acceleration is turned on
3465     * since the layer will have to be uploaded into a hardware texture after every
3466     * update.)</p>
3467     *
3468     * @see #getLayerType()
3469     * @see #setLayerType(int, android.graphics.Paint)
3470     * @see #LAYER_TYPE_NONE
3471     * @see #LAYER_TYPE_HARDWARE
3472     */
3473    public static final int LAYER_TYPE_SOFTWARE = 1;
3474
3475    /**
3476     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3477     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3478     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3479     * rendering pipeline, but only if hardware acceleration is turned on for the
3480     * view hierarchy. When hardware acceleration is turned off, hardware layers
3481     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3482     *
3483     * <p>A hardware layer is useful to apply a specific color filter and/or
3484     * blending mode and/or translucency to a view and all its children.</p>
3485     * <p>A hardware layer can be used to cache a complex view tree into a
3486     * texture and reduce the complexity of drawing operations. For instance,
3487     * when animating a complex view tree with a translation, a hardware layer can
3488     * be used to render the view tree only once.</p>
3489     * <p>A hardware layer can also be used to increase the rendering quality when
3490     * rotation transformations are applied on a view. It can also be used to
3491     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3492     *
3493     * @see #getLayerType()
3494     * @see #setLayerType(int, android.graphics.Paint)
3495     * @see #LAYER_TYPE_NONE
3496     * @see #LAYER_TYPE_SOFTWARE
3497     */
3498    public static final int LAYER_TYPE_HARDWARE = 2;
3499
3500    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3501            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3502            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3503            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3504    })
3505    int mLayerType = LAYER_TYPE_NONE;
3506    Paint mLayerPaint;
3507
3508    /**
3509     * Set to true when drawing cache is enabled and cannot be created.
3510     *
3511     * @hide
3512     */
3513    public boolean mCachingFailed;
3514    private Bitmap mDrawingCache;
3515    private Bitmap mUnscaledDrawingCache;
3516
3517    /**
3518     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3519     * <p>
3520     * When non-null and valid, this is expected to contain an up-to-date copy
3521     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3522     * cleanup.
3523     */
3524    final RenderNode mRenderNode;
3525
3526    /**
3527     * Set to true when the view is sending hover accessibility events because it
3528     * is the innermost hovered view.
3529     */
3530    private boolean mSendingHoverAccessibilityEvents;
3531
3532    /**
3533     * Delegate for injecting accessibility functionality.
3534     */
3535    AccessibilityDelegate mAccessibilityDelegate;
3536
3537    /**
3538     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3539     * and add/remove objects to/from the overlay directly through the Overlay methods.
3540     */
3541    ViewOverlay mOverlay;
3542
3543    /**
3544     * The currently active parent view for receiving delegated nested scrolling events.
3545     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3546     * by {@link #stopNestedScroll()} at the same point where we clear
3547     * requestDisallowInterceptTouchEvent.
3548     */
3549    private ViewParent mNestedScrollingParent;
3550
3551    /**
3552     * Consistency verifier for debugging purposes.
3553     * @hide
3554     */
3555    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3556            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3557                    new InputEventConsistencyVerifier(this, 0) : null;
3558
3559    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3560
3561    private int[] mTempNestedScrollConsumed;
3562
3563    /**
3564     * An overlay is going to draw this View instead of being drawn as part of this
3565     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3566     * when this view is invalidated.
3567     */
3568    GhostView mGhostView;
3569
3570    /**
3571     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3572     * @hide
3573     */
3574    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3575    public String[] mAttributes;
3576
3577    /**
3578     * Maps a Resource id to its name.
3579     */
3580    private static SparseArray<String> mAttributeMap;
3581
3582    /**
3583     * @hide
3584     */
3585    String mStartActivityRequestWho;
3586
3587    /**
3588     * Simple constructor to use when creating a view from code.
3589     *
3590     * @param context The Context the view is running in, through which it can
3591     *        access the current theme, resources, etc.
3592     */
3593    public View(Context context) {
3594        mContext = context;
3595        mResources = context != null ? context.getResources() : null;
3596        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3597        // Set some flags defaults
3598        mPrivateFlags2 =
3599                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3600                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3601                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3602                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3603                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3604                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3605        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3606        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3607        mUserPaddingStart = UNDEFINED_PADDING;
3608        mUserPaddingEnd = UNDEFINED_PADDING;
3609        mRenderNode = RenderNode.create(getClass().getName(), this);
3610
3611        if (!sCompatibilityDone && context != null) {
3612            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3613
3614            // Older apps may need this compatibility hack for measurement.
3615            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3616
3617            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3618            // of whether a layout was requested on that View.
3619            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3620
3621            Canvas.sCompatibilityRestore = targetSdkVersion < MNC;
3622
3623            sCompatibilityDone = true;
3624        }
3625    }
3626
3627    /**
3628     * Constructor that is called when inflating a view from XML. This is called
3629     * when a view is being constructed from an XML file, supplying attributes
3630     * that were specified in the XML file. This version uses a default style of
3631     * 0, so the only attribute values applied are those in the Context's Theme
3632     * and the given AttributeSet.
3633     *
3634     * <p>
3635     * The method onFinishInflate() will be called after all children have been
3636     * added.
3637     *
3638     * @param context The Context the view is running in, through which it can
3639     *        access the current theme, resources, etc.
3640     * @param attrs The attributes of the XML tag that is inflating the view.
3641     * @see #View(Context, AttributeSet, int)
3642     */
3643    public View(Context context, @Nullable AttributeSet attrs) {
3644        this(context, attrs, 0);
3645    }
3646
3647    /**
3648     * Perform inflation from XML and apply a class-specific base style from a
3649     * theme attribute. This constructor of View allows subclasses to use their
3650     * own base style when they are inflating. For example, a Button class's
3651     * constructor would call this version of the super class constructor and
3652     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3653     * allows the theme's button style to modify all of the base view attributes
3654     * (in particular its background) as well as the Button class's attributes.
3655     *
3656     * @param context The Context the view is running in, through which it can
3657     *        access the current theme, resources, etc.
3658     * @param attrs The attributes of the XML tag that is inflating the view.
3659     * @param defStyleAttr An attribute in the current theme that contains a
3660     *        reference to a style resource that supplies default values for
3661     *        the view. Can be 0 to not look for defaults.
3662     * @see #View(Context, AttributeSet)
3663     */
3664    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
3665        this(context, attrs, defStyleAttr, 0);
3666    }
3667
3668    /**
3669     * Perform inflation from XML and apply a class-specific base style from a
3670     * theme attribute or style resource. This constructor of View allows
3671     * subclasses to use their own base style when they are inflating.
3672     * <p>
3673     * When determining the final value of a particular attribute, there are
3674     * four inputs that come into play:
3675     * <ol>
3676     * <li>Any attribute values in the given AttributeSet.
3677     * <li>The style resource specified in the AttributeSet (named "style").
3678     * <li>The default style specified by <var>defStyleAttr</var>.
3679     * <li>The default style specified by <var>defStyleRes</var>.
3680     * <li>The base values in this theme.
3681     * </ol>
3682     * <p>
3683     * Each of these inputs is considered in-order, with the first listed taking
3684     * precedence over the following ones. In other words, if in the
3685     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3686     * , then the button's text will <em>always</em> be black, regardless of
3687     * what is specified in any of the styles.
3688     *
3689     * @param context The Context the view is running in, through which it can
3690     *        access the current theme, resources, etc.
3691     * @param attrs The attributes of the XML tag that is inflating the view.
3692     * @param defStyleAttr An attribute in the current theme that contains a
3693     *        reference to a style resource that supplies default values for
3694     *        the view. Can be 0 to not look for defaults.
3695     * @param defStyleRes A resource identifier of a style resource that
3696     *        supplies default values for the view, used only if
3697     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3698     *        to not look for defaults.
3699     * @see #View(Context, AttributeSet, int)
3700     */
3701    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3702        this(context);
3703
3704        final TypedArray a = context.obtainStyledAttributes(
3705                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3706
3707        if (mDebugViewAttributes) {
3708            saveAttributeData(attrs, a);
3709        }
3710
3711        Drawable background = null;
3712
3713        int leftPadding = -1;
3714        int topPadding = -1;
3715        int rightPadding = -1;
3716        int bottomPadding = -1;
3717        int startPadding = UNDEFINED_PADDING;
3718        int endPadding = UNDEFINED_PADDING;
3719
3720        int padding = -1;
3721
3722        int viewFlagValues = 0;
3723        int viewFlagMasks = 0;
3724
3725        boolean setScrollContainer = false;
3726
3727        int x = 0;
3728        int y = 0;
3729
3730        float tx = 0;
3731        float ty = 0;
3732        float tz = 0;
3733        float elevation = 0;
3734        float rotation = 0;
3735        float rotationX = 0;
3736        float rotationY = 0;
3737        float sx = 1f;
3738        float sy = 1f;
3739        boolean transformSet = false;
3740
3741        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3742        int overScrollMode = mOverScrollMode;
3743        boolean initializeScrollbars = false;
3744
3745        boolean startPaddingDefined = false;
3746        boolean endPaddingDefined = false;
3747        boolean leftPaddingDefined = false;
3748        boolean rightPaddingDefined = false;
3749
3750        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3751
3752        final int N = a.getIndexCount();
3753        for (int i = 0; i < N; i++) {
3754            int attr = a.getIndex(i);
3755            switch (attr) {
3756                case com.android.internal.R.styleable.View_background:
3757                    background = a.getDrawable(attr);
3758                    break;
3759                case com.android.internal.R.styleable.View_padding:
3760                    padding = a.getDimensionPixelSize(attr, -1);
3761                    mUserPaddingLeftInitial = padding;
3762                    mUserPaddingRightInitial = padding;
3763                    leftPaddingDefined = true;
3764                    rightPaddingDefined = true;
3765                    break;
3766                 case com.android.internal.R.styleable.View_paddingLeft:
3767                    leftPadding = a.getDimensionPixelSize(attr, -1);
3768                    mUserPaddingLeftInitial = leftPadding;
3769                    leftPaddingDefined = true;
3770                    break;
3771                case com.android.internal.R.styleable.View_paddingTop:
3772                    topPadding = a.getDimensionPixelSize(attr, -1);
3773                    break;
3774                case com.android.internal.R.styleable.View_paddingRight:
3775                    rightPadding = a.getDimensionPixelSize(attr, -1);
3776                    mUserPaddingRightInitial = rightPadding;
3777                    rightPaddingDefined = true;
3778                    break;
3779                case com.android.internal.R.styleable.View_paddingBottom:
3780                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3781                    break;
3782                case com.android.internal.R.styleable.View_paddingStart:
3783                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3784                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3785                    break;
3786                case com.android.internal.R.styleable.View_paddingEnd:
3787                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3788                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3789                    break;
3790                case com.android.internal.R.styleable.View_scrollX:
3791                    x = a.getDimensionPixelOffset(attr, 0);
3792                    break;
3793                case com.android.internal.R.styleable.View_scrollY:
3794                    y = a.getDimensionPixelOffset(attr, 0);
3795                    break;
3796                case com.android.internal.R.styleable.View_alpha:
3797                    setAlpha(a.getFloat(attr, 1f));
3798                    break;
3799                case com.android.internal.R.styleable.View_transformPivotX:
3800                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3801                    break;
3802                case com.android.internal.R.styleable.View_transformPivotY:
3803                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3804                    break;
3805                case com.android.internal.R.styleable.View_translationX:
3806                    tx = a.getDimensionPixelOffset(attr, 0);
3807                    transformSet = true;
3808                    break;
3809                case com.android.internal.R.styleable.View_translationY:
3810                    ty = a.getDimensionPixelOffset(attr, 0);
3811                    transformSet = true;
3812                    break;
3813                case com.android.internal.R.styleable.View_translationZ:
3814                    tz = a.getDimensionPixelOffset(attr, 0);
3815                    transformSet = true;
3816                    break;
3817                case com.android.internal.R.styleable.View_elevation:
3818                    elevation = a.getDimensionPixelOffset(attr, 0);
3819                    transformSet = true;
3820                    break;
3821                case com.android.internal.R.styleable.View_rotation:
3822                    rotation = a.getFloat(attr, 0);
3823                    transformSet = true;
3824                    break;
3825                case com.android.internal.R.styleable.View_rotationX:
3826                    rotationX = a.getFloat(attr, 0);
3827                    transformSet = true;
3828                    break;
3829                case com.android.internal.R.styleable.View_rotationY:
3830                    rotationY = a.getFloat(attr, 0);
3831                    transformSet = true;
3832                    break;
3833                case com.android.internal.R.styleable.View_scaleX:
3834                    sx = a.getFloat(attr, 1f);
3835                    transformSet = true;
3836                    break;
3837                case com.android.internal.R.styleable.View_scaleY:
3838                    sy = a.getFloat(attr, 1f);
3839                    transformSet = true;
3840                    break;
3841                case com.android.internal.R.styleable.View_id:
3842                    mID = a.getResourceId(attr, NO_ID);
3843                    break;
3844                case com.android.internal.R.styleable.View_tag:
3845                    mTag = a.getText(attr);
3846                    break;
3847                case com.android.internal.R.styleable.View_fitsSystemWindows:
3848                    if (a.getBoolean(attr, false)) {
3849                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3850                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3851                    }
3852                    break;
3853                case com.android.internal.R.styleable.View_focusable:
3854                    if (a.getBoolean(attr, false)) {
3855                        viewFlagValues |= FOCUSABLE;
3856                        viewFlagMasks |= FOCUSABLE_MASK;
3857                    }
3858                    break;
3859                case com.android.internal.R.styleable.View_focusableInTouchMode:
3860                    if (a.getBoolean(attr, false)) {
3861                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3862                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3863                    }
3864                    break;
3865                case com.android.internal.R.styleable.View_clickable:
3866                    if (a.getBoolean(attr, false)) {
3867                        viewFlagValues |= CLICKABLE;
3868                        viewFlagMasks |= CLICKABLE;
3869                    }
3870                    break;
3871                case com.android.internal.R.styleable.View_longClickable:
3872                    if (a.getBoolean(attr, false)) {
3873                        viewFlagValues |= LONG_CLICKABLE;
3874                        viewFlagMasks |= LONG_CLICKABLE;
3875                    }
3876                    break;
3877                case com.android.internal.R.styleable.View_saveEnabled:
3878                    if (!a.getBoolean(attr, true)) {
3879                        viewFlagValues |= SAVE_DISABLED;
3880                        viewFlagMasks |= SAVE_DISABLED_MASK;
3881                    }
3882                    break;
3883                case com.android.internal.R.styleable.View_assistBlocked:
3884                    if (a.getBoolean(attr, false)) {
3885                        mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
3886                    }
3887                    break;
3888                case com.android.internal.R.styleable.View_duplicateParentState:
3889                    if (a.getBoolean(attr, false)) {
3890                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3891                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3892                    }
3893                    break;
3894                case com.android.internal.R.styleable.View_visibility:
3895                    final int visibility = a.getInt(attr, 0);
3896                    if (visibility != 0) {
3897                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3898                        viewFlagMasks |= VISIBILITY_MASK;
3899                    }
3900                    break;
3901                case com.android.internal.R.styleable.View_layoutDirection:
3902                    // Clear any layout direction flags (included resolved bits) already set
3903                    mPrivateFlags2 &=
3904                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3905                    // Set the layout direction flags depending on the value of the attribute
3906                    final int layoutDirection = a.getInt(attr, -1);
3907                    final int value = (layoutDirection != -1) ?
3908                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3909                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3910                    break;
3911                case com.android.internal.R.styleable.View_drawingCacheQuality:
3912                    final int cacheQuality = a.getInt(attr, 0);
3913                    if (cacheQuality != 0) {
3914                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3915                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3916                    }
3917                    break;
3918                case com.android.internal.R.styleable.View_contentDescription:
3919                    setContentDescription(a.getString(attr));
3920                    break;
3921                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
3922                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
3923                    break;
3924                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
3925                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
3926                    break;
3927                case com.android.internal.R.styleable.View_labelFor:
3928                    setLabelFor(a.getResourceId(attr, NO_ID));
3929                    break;
3930                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3931                    if (!a.getBoolean(attr, true)) {
3932                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3933                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3934                    }
3935                    break;
3936                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3937                    if (!a.getBoolean(attr, true)) {
3938                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3939                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3940                    }
3941                    break;
3942                case R.styleable.View_scrollbars:
3943                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3944                    if (scrollbars != SCROLLBARS_NONE) {
3945                        viewFlagValues |= scrollbars;
3946                        viewFlagMasks |= SCROLLBARS_MASK;
3947                        initializeScrollbars = true;
3948                    }
3949                    break;
3950                //noinspection deprecation
3951                case R.styleable.View_fadingEdge:
3952                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3953                        // Ignore the attribute starting with ICS
3954                        break;
3955                    }
3956                    // With builds < ICS, fall through and apply fading edges
3957                case R.styleable.View_requiresFadingEdge:
3958                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3959                    if (fadingEdge != FADING_EDGE_NONE) {
3960                        viewFlagValues |= fadingEdge;
3961                        viewFlagMasks |= FADING_EDGE_MASK;
3962                        initializeFadingEdgeInternal(a);
3963                    }
3964                    break;
3965                case R.styleable.View_scrollbarStyle:
3966                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3967                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3968                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3969                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3970                    }
3971                    break;
3972                case R.styleable.View_isScrollContainer:
3973                    setScrollContainer = true;
3974                    if (a.getBoolean(attr, false)) {
3975                        setScrollContainer(true);
3976                    }
3977                    break;
3978                case com.android.internal.R.styleable.View_keepScreenOn:
3979                    if (a.getBoolean(attr, false)) {
3980                        viewFlagValues |= KEEP_SCREEN_ON;
3981                        viewFlagMasks |= KEEP_SCREEN_ON;
3982                    }
3983                    break;
3984                case R.styleable.View_filterTouchesWhenObscured:
3985                    if (a.getBoolean(attr, false)) {
3986                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3987                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3988                    }
3989                    break;
3990                case R.styleable.View_nextFocusLeft:
3991                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3992                    break;
3993                case R.styleable.View_nextFocusRight:
3994                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3995                    break;
3996                case R.styleable.View_nextFocusUp:
3997                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3998                    break;
3999                case R.styleable.View_nextFocusDown:
4000                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4001                    break;
4002                case R.styleable.View_nextFocusForward:
4003                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4004                    break;
4005                case R.styleable.View_minWidth:
4006                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4007                    break;
4008                case R.styleable.View_minHeight:
4009                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4010                    break;
4011                case R.styleable.View_onClick:
4012                    if (context.isRestricted()) {
4013                        throw new IllegalStateException("The android:onClick attribute cannot "
4014                                + "be used within a restricted context");
4015                    }
4016
4017                    final String handlerName = a.getString(attr);
4018                    if (handlerName != null) {
4019                        setOnClickListener(new OnClickListener() {
4020                            private Method mHandler;
4021
4022                            public void onClick(View v) {
4023                                if (mHandler == null) {
4024                                    try {
4025                                        mHandler = getContext().getClass().getMethod(handlerName,
4026                                                View.class);
4027                                    } catch (NoSuchMethodException e) {
4028                                        int id = getId();
4029                                        String idText = id == NO_ID ? "" : " with id '"
4030                                                + getContext().getResources().getResourceEntryName(
4031                                                    id) + "'";
4032                                        throw new IllegalStateException("Could not find a method " +
4033                                                handlerName + "(View) in the activity "
4034                                                + getContext().getClass() + " for onClick handler"
4035                                                + " on view " + View.this.getClass() + idText, e);
4036                                    }
4037                                }
4038
4039                                try {
4040                                    mHandler.invoke(getContext(), View.this);
4041                                } catch (IllegalAccessException e) {
4042                                    throw new IllegalStateException("Could not execute non "
4043                                            + "public method of the activity", e);
4044                                } catch (InvocationTargetException e) {
4045                                    throw new IllegalStateException("Could not execute "
4046                                            + "method of the activity", e);
4047                                }
4048                            }
4049                        });
4050                    }
4051                    break;
4052                case R.styleable.View_overScrollMode:
4053                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4054                    break;
4055                case R.styleable.View_verticalScrollbarPosition:
4056                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4057                    break;
4058                case R.styleable.View_layerType:
4059                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4060                    break;
4061                case R.styleable.View_textDirection:
4062                    // Clear any text direction flag already set
4063                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4064                    // Set the text direction flags depending on the value of the attribute
4065                    final int textDirection = a.getInt(attr, -1);
4066                    if (textDirection != -1) {
4067                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4068                    }
4069                    break;
4070                case R.styleable.View_textAlignment:
4071                    // Clear any text alignment flag already set
4072                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4073                    // Set the text alignment flag depending on the value of the attribute
4074                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4075                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4076                    break;
4077                case R.styleable.View_importantForAccessibility:
4078                    setImportantForAccessibility(a.getInt(attr,
4079                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4080                    break;
4081                case R.styleable.View_accessibilityLiveRegion:
4082                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4083                    break;
4084                case R.styleable.View_transitionName:
4085                    setTransitionName(a.getString(attr));
4086                    break;
4087                case R.styleable.View_nestedScrollingEnabled:
4088                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4089                    break;
4090                case R.styleable.View_stateListAnimator:
4091                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4092                            a.getResourceId(attr, 0)));
4093                    break;
4094                case R.styleable.View_backgroundTint:
4095                    // This will get applied later during setBackground().
4096                    if (mBackgroundTint == null) {
4097                        mBackgroundTint = new TintInfo();
4098                    }
4099                    mBackgroundTint.mTintList = a.getColorStateList(
4100                            R.styleable.View_backgroundTint);
4101                    mBackgroundTint.mHasTintList = true;
4102                    break;
4103                case R.styleable.View_backgroundTintMode:
4104                    // This will get applied later during setBackground().
4105                    if (mBackgroundTint == null) {
4106                        mBackgroundTint = new TintInfo();
4107                    }
4108                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4109                            R.styleable.View_backgroundTintMode, -1), null);
4110                    mBackgroundTint.mHasTintMode = true;
4111                    break;
4112                case R.styleable.View_outlineProvider:
4113                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4114                            PROVIDER_BACKGROUND));
4115                    break;
4116                case R.styleable.View_foreground:
4117                    setForeground(a.getDrawable(attr));
4118                    break;
4119                case R.styleable.View_foregroundGravity:
4120                    setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4121                    break;
4122                case R.styleable.View_foregroundTintMode:
4123                    setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4124                    break;
4125                case R.styleable.View_foregroundTint:
4126                    setForegroundTintList(a.getColorStateList(attr));
4127                    break;
4128                case R.styleable.View_foregroundInsidePadding:
4129                    if (mForegroundInfo == null) {
4130                        mForegroundInfo = new ForegroundInfo();
4131                    }
4132                    mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4133                            mForegroundInfo.mInsidePadding);
4134                    break;
4135            }
4136        }
4137
4138        setOverScrollMode(overScrollMode);
4139
4140        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4141        // the resolved layout direction). Those cached values will be used later during padding
4142        // resolution.
4143        mUserPaddingStart = startPadding;
4144        mUserPaddingEnd = endPadding;
4145
4146        if (background != null) {
4147            setBackground(background);
4148        }
4149
4150        // setBackground above will record that padding is currently provided by the background.
4151        // If we have padding specified via xml, record that here instead and use it.
4152        mLeftPaddingDefined = leftPaddingDefined;
4153        mRightPaddingDefined = rightPaddingDefined;
4154
4155        if (padding >= 0) {
4156            leftPadding = padding;
4157            topPadding = padding;
4158            rightPadding = padding;
4159            bottomPadding = padding;
4160            mUserPaddingLeftInitial = padding;
4161            mUserPaddingRightInitial = padding;
4162        }
4163
4164        if (isRtlCompatibilityMode()) {
4165            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4166            // left / right padding are used if defined (meaning here nothing to do). If they are not
4167            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4168            // start / end and resolve them as left / right (layout direction is not taken into account).
4169            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4170            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4171            // defined.
4172            if (!mLeftPaddingDefined && startPaddingDefined) {
4173                leftPadding = startPadding;
4174            }
4175            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4176            if (!mRightPaddingDefined && endPaddingDefined) {
4177                rightPadding = endPadding;
4178            }
4179            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4180        } else {
4181            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4182            // values defined. Otherwise, left /right values are used.
4183            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4184            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4185            // defined.
4186            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4187
4188            if (mLeftPaddingDefined && !hasRelativePadding) {
4189                mUserPaddingLeftInitial = leftPadding;
4190            }
4191            if (mRightPaddingDefined && !hasRelativePadding) {
4192                mUserPaddingRightInitial = rightPadding;
4193            }
4194        }
4195
4196        internalSetPadding(
4197                mUserPaddingLeftInitial,
4198                topPadding >= 0 ? topPadding : mPaddingTop,
4199                mUserPaddingRightInitial,
4200                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4201
4202        if (viewFlagMasks != 0) {
4203            setFlags(viewFlagValues, viewFlagMasks);
4204        }
4205
4206        if (initializeScrollbars) {
4207            initializeScrollbarsInternal(a);
4208        }
4209
4210        a.recycle();
4211
4212        // Needs to be called after mViewFlags is set
4213        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4214            recomputePadding();
4215        }
4216
4217        if (x != 0 || y != 0) {
4218            scrollTo(x, y);
4219        }
4220
4221        if (transformSet) {
4222            setTranslationX(tx);
4223            setTranslationY(ty);
4224            setTranslationZ(tz);
4225            setElevation(elevation);
4226            setRotation(rotation);
4227            setRotationX(rotationX);
4228            setRotationY(rotationY);
4229            setScaleX(sx);
4230            setScaleY(sy);
4231        }
4232
4233        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4234            setScrollContainer(true);
4235        }
4236
4237        computeOpaqueFlags();
4238    }
4239
4240    /**
4241     * Non-public constructor for use in testing
4242     */
4243    View() {
4244        mResources = null;
4245        mRenderNode = RenderNode.create(getClass().getName(), this);
4246    }
4247
4248    private static SparseArray<String> getAttributeMap() {
4249        if (mAttributeMap == null) {
4250            mAttributeMap = new SparseArray<String>();
4251        }
4252        return mAttributeMap;
4253    }
4254
4255    private void saveAttributeData(AttributeSet attrs, TypedArray a) {
4256        int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2;
4257        mAttributes = new String[length];
4258
4259        int i = 0;
4260        if (attrs != null) {
4261            for (i = 0; i < attrs.getAttributeCount(); i += 2) {
4262                mAttributes[i] = attrs.getAttributeName(i);
4263                mAttributes[i + 1] = attrs.getAttributeValue(i);
4264            }
4265
4266        }
4267
4268        SparseArray<String> attributeMap = getAttributeMap();
4269        for (int j = 0; j < a.length(); ++j) {
4270            if (a.hasValue(j)) {
4271                try {
4272                    int resourceId = a.getResourceId(j, 0);
4273                    if (resourceId == 0) {
4274                        continue;
4275                    }
4276
4277                    String resourceName = attributeMap.get(resourceId);
4278                    if (resourceName == null) {
4279                        resourceName = a.getResources().getResourceName(resourceId);
4280                        attributeMap.put(resourceId, resourceName);
4281                    }
4282
4283                    mAttributes[i] = resourceName;
4284                    mAttributes[i + 1] = a.getText(j).toString();
4285                    i += 2;
4286                } catch (Resources.NotFoundException e) {
4287                    // if we can't get the resource name, we just ignore it
4288                }
4289            }
4290        }
4291    }
4292
4293    public String toString() {
4294        StringBuilder out = new StringBuilder(128);
4295        out.append(getClass().getName());
4296        out.append('{');
4297        out.append(Integer.toHexString(System.identityHashCode(this)));
4298        out.append(' ');
4299        switch (mViewFlags&VISIBILITY_MASK) {
4300            case VISIBLE: out.append('V'); break;
4301            case INVISIBLE: out.append('I'); break;
4302            case GONE: out.append('G'); break;
4303            default: out.append('.'); break;
4304        }
4305        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4306        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4307        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4308        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4309        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4310        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4311        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4312        out.append(' ');
4313        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4314        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4315        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4316        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4317            out.append('p');
4318        } else {
4319            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4320        }
4321        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4322        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4323        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4324        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4325        out.append(' ');
4326        out.append(mLeft);
4327        out.append(',');
4328        out.append(mTop);
4329        out.append('-');
4330        out.append(mRight);
4331        out.append(',');
4332        out.append(mBottom);
4333        final int id = getId();
4334        if (id != NO_ID) {
4335            out.append(" #");
4336            out.append(Integer.toHexString(id));
4337            final Resources r = mResources;
4338            if (Resources.resourceHasPackage(id) && r != null) {
4339                try {
4340                    String pkgname;
4341                    switch (id&0xff000000) {
4342                        case 0x7f000000:
4343                            pkgname="app";
4344                            break;
4345                        case 0x01000000:
4346                            pkgname="android";
4347                            break;
4348                        default:
4349                            pkgname = r.getResourcePackageName(id);
4350                            break;
4351                    }
4352                    String typename = r.getResourceTypeName(id);
4353                    String entryname = r.getResourceEntryName(id);
4354                    out.append(" ");
4355                    out.append(pkgname);
4356                    out.append(":");
4357                    out.append(typename);
4358                    out.append("/");
4359                    out.append(entryname);
4360                } catch (Resources.NotFoundException e) {
4361                }
4362            }
4363        }
4364        out.append("}");
4365        return out.toString();
4366    }
4367
4368    /**
4369     * <p>
4370     * Initializes the fading edges from a given set of styled attributes. This
4371     * method should be called by subclasses that need fading edges and when an
4372     * instance of these subclasses is created programmatically rather than
4373     * being inflated from XML. This method is automatically called when the XML
4374     * is inflated.
4375     * </p>
4376     *
4377     * @param a the styled attributes set to initialize the fading edges from
4378     *
4379     * @removed
4380     */
4381    protected void initializeFadingEdge(TypedArray a) {
4382        // This method probably shouldn't have been included in the SDK to begin with.
4383        // It relies on 'a' having been initialized using an attribute filter array that is
4384        // not publicly available to the SDK. The old method has been renamed
4385        // to initializeFadingEdgeInternal and hidden for framework use only;
4386        // this one initializes using defaults to make it safe to call for apps.
4387
4388        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4389
4390        initializeFadingEdgeInternal(arr);
4391
4392        arr.recycle();
4393    }
4394
4395    /**
4396     * <p>
4397     * Initializes the fading edges from a given set of styled attributes. This
4398     * method should be called by subclasses that need fading edges and when an
4399     * instance of these subclasses is created programmatically rather than
4400     * being inflated from XML. This method is automatically called when the XML
4401     * is inflated.
4402     * </p>
4403     *
4404     * @param a the styled attributes set to initialize the fading edges from
4405     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4406     */
4407    protected void initializeFadingEdgeInternal(TypedArray a) {
4408        initScrollCache();
4409
4410        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4411                R.styleable.View_fadingEdgeLength,
4412                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4413    }
4414
4415    /**
4416     * Returns the size of the vertical faded edges used to indicate that more
4417     * content in this view is visible.
4418     *
4419     * @return The size in pixels of the vertical faded edge or 0 if vertical
4420     *         faded edges are not enabled for this view.
4421     * @attr ref android.R.styleable#View_fadingEdgeLength
4422     */
4423    public int getVerticalFadingEdgeLength() {
4424        if (isVerticalFadingEdgeEnabled()) {
4425            ScrollabilityCache cache = mScrollCache;
4426            if (cache != null) {
4427                return cache.fadingEdgeLength;
4428            }
4429        }
4430        return 0;
4431    }
4432
4433    /**
4434     * Set the size of the faded edge used to indicate that more content in this
4435     * view is available.  Will not change whether the fading edge is enabled; use
4436     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4437     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4438     * for the vertical or horizontal fading edges.
4439     *
4440     * @param length The size in pixels of the faded edge used to indicate that more
4441     *        content in this view is visible.
4442     */
4443    public void setFadingEdgeLength(int length) {
4444        initScrollCache();
4445        mScrollCache.fadingEdgeLength = length;
4446    }
4447
4448    /**
4449     * Returns the size of the horizontal faded edges used to indicate that more
4450     * content in this view is visible.
4451     *
4452     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4453     *         faded edges are not enabled for this view.
4454     * @attr ref android.R.styleable#View_fadingEdgeLength
4455     */
4456    public int getHorizontalFadingEdgeLength() {
4457        if (isHorizontalFadingEdgeEnabled()) {
4458            ScrollabilityCache cache = mScrollCache;
4459            if (cache != null) {
4460                return cache.fadingEdgeLength;
4461            }
4462        }
4463        return 0;
4464    }
4465
4466    /**
4467     * Returns the width of the vertical scrollbar.
4468     *
4469     * @return The width in pixels of the vertical scrollbar or 0 if there
4470     *         is no vertical scrollbar.
4471     */
4472    public int getVerticalScrollbarWidth() {
4473        ScrollabilityCache cache = mScrollCache;
4474        if (cache != null) {
4475            ScrollBarDrawable scrollBar = cache.scrollBar;
4476            if (scrollBar != null) {
4477                int size = scrollBar.getSize(true);
4478                if (size <= 0) {
4479                    size = cache.scrollBarSize;
4480                }
4481                return size;
4482            }
4483            return 0;
4484        }
4485        return 0;
4486    }
4487
4488    /**
4489     * Returns the height of the horizontal scrollbar.
4490     *
4491     * @return The height in pixels of the horizontal scrollbar or 0 if
4492     *         there is no horizontal scrollbar.
4493     */
4494    protected int getHorizontalScrollbarHeight() {
4495        ScrollabilityCache cache = mScrollCache;
4496        if (cache != null) {
4497            ScrollBarDrawable scrollBar = cache.scrollBar;
4498            if (scrollBar != null) {
4499                int size = scrollBar.getSize(false);
4500                if (size <= 0) {
4501                    size = cache.scrollBarSize;
4502                }
4503                return size;
4504            }
4505            return 0;
4506        }
4507        return 0;
4508    }
4509
4510    /**
4511     * <p>
4512     * Initializes the scrollbars from a given set of styled attributes. This
4513     * method should be called by subclasses that need scrollbars and when an
4514     * instance of these subclasses is created programmatically rather than
4515     * being inflated from XML. This method is automatically called when the XML
4516     * is inflated.
4517     * </p>
4518     *
4519     * @param a the styled attributes set to initialize the scrollbars from
4520     *
4521     * @removed
4522     */
4523    protected void initializeScrollbars(TypedArray a) {
4524        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4525        // using the View filter array which is not available to the SDK. As such, internal
4526        // framework usage now uses initializeScrollbarsInternal and we grab a default
4527        // TypedArray with the right filter instead here.
4528        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4529
4530        initializeScrollbarsInternal(arr);
4531
4532        // We ignored the method parameter. Recycle the one we actually did use.
4533        arr.recycle();
4534    }
4535
4536    /**
4537     * <p>
4538     * Initializes the scrollbars from a given set of styled attributes. This
4539     * method should be called by subclasses that need scrollbars and when an
4540     * instance of these subclasses is created programmatically rather than
4541     * being inflated from XML. This method is automatically called when the XML
4542     * is inflated.
4543     * </p>
4544     *
4545     * @param a the styled attributes set to initialize the scrollbars from
4546     * @hide
4547     */
4548    protected void initializeScrollbarsInternal(TypedArray a) {
4549        initScrollCache();
4550
4551        final ScrollabilityCache scrollabilityCache = mScrollCache;
4552
4553        if (scrollabilityCache.scrollBar == null) {
4554            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4555            scrollabilityCache.scrollBar.setCallback(this);
4556            scrollabilityCache.scrollBar.setState(getDrawableState());
4557        }
4558
4559        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4560
4561        if (!fadeScrollbars) {
4562            scrollabilityCache.state = ScrollabilityCache.ON;
4563        }
4564        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4565
4566
4567        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4568                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4569                        .getScrollBarFadeDuration());
4570        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4571                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4572                ViewConfiguration.getScrollDefaultDelay());
4573
4574
4575        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4576                com.android.internal.R.styleable.View_scrollbarSize,
4577                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4578
4579        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4580        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4581
4582        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4583        if (thumb != null) {
4584            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4585        }
4586
4587        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4588                false);
4589        if (alwaysDraw) {
4590            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4591        }
4592
4593        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4594        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4595
4596        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4597        if (thumb != null) {
4598            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4599        }
4600
4601        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4602                false);
4603        if (alwaysDraw) {
4604            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4605        }
4606
4607        // Apply layout direction to the new Drawables if needed
4608        final int layoutDirection = getLayoutDirection();
4609        if (track != null) {
4610            track.setLayoutDirection(layoutDirection);
4611        }
4612        if (thumb != null) {
4613            thumb.setLayoutDirection(layoutDirection);
4614        }
4615
4616        // Re-apply user/background padding so that scrollbar(s) get added
4617        resolvePadding();
4618    }
4619
4620    /**
4621     * <p>
4622     * Initalizes the scrollability cache if necessary.
4623     * </p>
4624     */
4625    private void initScrollCache() {
4626        if (mScrollCache == null) {
4627            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4628        }
4629    }
4630
4631    private ScrollabilityCache getScrollCache() {
4632        initScrollCache();
4633        return mScrollCache;
4634    }
4635
4636    /**
4637     * Set the position of the vertical scroll bar. Should be one of
4638     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4639     * {@link #SCROLLBAR_POSITION_RIGHT}.
4640     *
4641     * @param position Where the vertical scroll bar should be positioned.
4642     */
4643    public void setVerticalScrollbarPosition(int position) {
4644        if (mVerticalScrollbarPosition != position) {
4645            mVerticalScrollbarPosition = position;
4646            computeOpaqueFlags();
4647            resolvePadding();
4648        }
4649    }
4650
4651    /**
4652     * @return The position where the vertical scroll bar will show, if applicable.
4653     * @see #setVerticalScrollbarPosition(int)
4654     */
4655    public int getVerticalScrollbarPosition() {
4656        return mVerticalScrollbarPosition;
4657    }
4658
4659    ListenerInfo getListenerInfo() {
4660        if (mListenerInfo != null) {
4661            return mListenerInfo;
4662        }
4663        mListenerInfo = new ListenerInfo();
4664        return mListenerInfo;
4665    }
4666
4667    /**
4668     * Register a callback to be invoked when the scroll X or Y positions of
4669     * this view change.
4670     * <p>
4671     * <b>Note:</b> Some views handle scrolling independently from View and may
4672     * have their own separate listeners for scroll-type events. For example,
4673     * {@link android.widget.ListView ListView} allows clients to register an
4674     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
4675     * to listen for changes in list scroll position.
4676     *
4677     * @param l The listener to notify when the scroll X or Y position changes.
4678     * @see android.view.View#getScrollX()
4679     * @see android.view.View#getScrollY()
4680     */
4681    public void setOnScrollChangeListener(OnScrollChangeListener l) {
4682        getListenerInfo().mOnScrollChangeListener = l;
4683    }
4684
4685    /**
4686     * Register a callback to be invoked when focus of this view changed.
4687     *
4688     * @param l The callback that will run.
4689     */
4690    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4691        getListenerInfo().mOnFocusChangeListener = l;
4692    }
4693
4694    /**
4695     * Add a listener that will be called when the bounds of the view change due to
4696     * layout processing.
4697     *
4698     * @param listener The listener that will be called when layout bounds change.
4699     */
4700    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4701        ListenerInfo li = getListenerInfo();
4702        if (li.mOnLayoutChangeListeners == null) {
4703            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4704        }
4705        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4706            li.mOnLayoutChangeListeners.add(listener);
4707        }
4708    }
4709
4710    /**
4711     * Remove a listener for layout changes.
4712     *
4713     * @param listener The listener for layout bounds change.
4714     */
4715    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4716        ListenerInfo li = mListenerInfo;
4717        if (li == null || li.mOnLayoutChangeListeners == null) {
4718            return;
4719        }
4720        li.mOnLayoutChangeListeners.remove(listener);
4721    }
4722
4723    /**
4724     * Add a listener for attach state changes.
4725     *
4726     * This listener will be called whenever this view is attached or detached
4727     * from a window. Remove the listener using
4728     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4729     *
4730     * @param listener Listener to attach
4731     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4732     */
4733    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4734        ListenerInfo li = getListenerInfo();
4735        if (li.mOnAttachStateChangeListeners == null) {
4736            li.mOnAttachStateChangeListeners
4737                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4738        }
4739        li.mOnAttachStateChangeListeners.add(listener);
4740    }
4741
4742    /**
4743     * Remove a listener for attach state changes. The listener will receive no further
4744     * notification of window attach/detach events.
4745     *
4746     * @param listener Listener to remove
4747     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4748     */
4749    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4750        ListenerInfo li = mListenerInfo;
4751        if (li == null || li.mOnAttachStateChangeListeners == null) {
4752            return;
4753        }
4754        li.mOnAttachStateChangeListeners.remove(listener);
4755    }
4756
4757    /**
4758     * Returns the focus-change callback registered for this view.
4759     *
4760     * @return The callback, or null if one is not registered.
4761     */
4762    public OnFocusChangeListener getOnFocusChangeListener() {
4763        ListenerInfo li = mListenerInfo;
4764        return li != null ? li.mOnFocusChangeListener : null;
4765    }
4766
4767    /**
4768     * Register a callback to be invoked when this view is clicked. If this view is not
4769     * clickable, it becomes clickable.
4770     *
4771     * @param l The callback that will run
4772     *
4773     * @see #setClickable(boolean)
4774     */
4775    public void setOnClickListener(@Nullable OnClickListener l) {
4776        if (!isClickable()) {
4777            setClickable(true);
4778        }
4779        getListenerInfo().mOnClickListener = l;
4780    }
4781
4782    /**
4783     * Return whether this view has an attached OnClickListener.  Returns
4784     * true if there is a listener, false if there is none.
4785     */
4786    public boolean hasOnClickListeners() {
4787        ListenerInfo li = mListenerInfo;
4788        return (li != null && li.mOnClickListener != null);
4789    }
4790
4791    /**
4792     * Register a callback to be invoked when this view is clicked and held. If this view is not
4793     * long clickable, it becomes long clickable.
4794     *
4795     * @param l The callback that will run
4796     *
4797     * @see #setLongClickable(boolean)
4798     */
4799    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
4800        if (!isLongClickable()) {
4801            setLongClickable(true);
4802        }
4803        getListenerInfo().mOnLongClickListener = l;
4804    }
4805
4806    /**
4807     * Register a callback to be invoked when the context menu for this view is
4808     * being built. If this view is not long clickable, it becomes long clickable.
4809     *
4810     * @param l The callback that will run
4811     *
4812     */
4813    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4814        if (!isLongClickable()) {
4815            setLongClickable(true);
4816        }
4817        getListenerInfo().mOnCreateContextMenuListener = l;
4818    }
4819
4820    /**
4821     * Call this view's OnClickListener, if it is defined.  Performs all normal
4822     * actions associated with clicking: reporting accessibility event, playing
4823     * a sound, etc.
4824     *
4825     * @return True there was an assigned OnClickListener that was called, false
4826     *         otherwise is returned.
4827     */
4828    public boolean performClick() {
4829        final boolean result;
4830        final ListenerInfo li = mListenerInfo;
4831        if (li != null && li.mOnClickListener != null) {
4832            playSoundEffect(SoundEffectConstants.CLICK);
4833            li.mOnClickListener.onClick(this);
4834            result = true;
4835        } else {
4836            result = false;
4837        }
4838
4839        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4840        return result;
4841    }
4842
4843    /**
4844     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4845     * this only calls the listener, and does not do any associated clicking
4846     * actions like reporting an accessibility event.
4847     *
4848     * @return True there was an assigned OnClickListener that was called, false
4849     *         otherwise is returned.
4850     */
4851    public boolean callOnClick() {
4852        ListenerInfo li = mListenerInfo;
4853        if (li != null && li.mOnClickListener != null) {
4854            li.mOnClickListener.onClick(this);
4855            return true;
4856        }
4857        return false;
4858    }
4859
4860    /**
4861     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4862     * OnLongClickListener did not consume the event.
4863     *
4864     * @return True if one of the above receivers consumed the event, false otherwise.
4865     */
4866    public boolean performLongClick() {
4867        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4868
4869        boolean handled = false;
4870        ListenerInfo li = mListenerInfo;
4871        if (li != null && li.mOnLongClickListener != null) {
4872            handled = li.mOnLongClickListener.onLongClick(View.this);
4873        }
4874        if (!handled) {
4875            handled = showContextMenu();
4876        }
4877        if (handled) {
4878            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4879        }
4880        return handled;
4881    }
4882
4883    /**
4884     * Performs button-related actions during a touch down event.
4885     *
4886     * @param event The event.
4887     * @return True if the down was consumed.
4888     *
4889     * @hide
4890     */
4891    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4892        if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE &&
4893            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4894            showContextMenu(event.getX(), event.getY(), event.getMetaState());
4895            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
4896            return true;
4897        }
4898        return false;
4899    }
4900
4901    /**
4902     * Bring up the context menu for this view.
4903     *
4904     * @return Whether a context menu was displayed.
4905     */
4906    public boolean showContextMenu() {
4907        return getParent().showContextMenuForChild(this);
4908    }
4909
4910    /**
4911     * Bring up the context menu for this view, referring to the item under the specified point.
4912     *
4913     * @param x The referenced x coordinate.
4914     * @param y The referenced y coordinate.
4915     * @param metaState The keyboard modifiers that were pressed.
4916     * @return Whether a context menu was displayed.
4917     *
4918     * @hide
4919     */
4920    public boolean showContextMenu(float x, float y, int metaState) {
4921        return showContextMenu();
4922    }
4923
4924    /**
4925     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
4926     *
4927     * @param callback Callback that will control the lifecycle of the action mode
4928     * @return The new action mode if it is started, null otherwise
4929     *
4930     * @see ActionMode
4931     * @see #startActionMode(android.view.ActionMode.Callback, int)
4932     */
4933    public ActionMode startActionMode(ActionMode.Callback callback) {
4934        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
4935    }
4936
4937    /**
4938     * Start an action mode with the given type.
4939     *
4940     * @param callback Callback that will control the lifecycle of the action mode
4941     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
4942     * @return The new action mode if it is started, null otherwise
4943     *
4944     * @see ActionMode
4945     */
4946    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
4947        ViewParent parent = getParent();
4948        if (parent == null) return null;
4949        try {
4950            return parent.startActionModeForChild(this, callback, type);
4951        } catch (AbstractMethodError ame) {
4952            // Older implementations of custom views might not implement this.
4953            return parent.startActionModeForChild(this, callback);
4954        }
4955    }
4956
4957    /**
4958     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
4959     * Context, creating a unique View identifier to retrieve the result.
4960     *
4961     * @param intent The Intent to be started.
4962     * @param requestCode The request code to use.
4963     * @hide
4964     */
4965    public void startActivityForResult(Intent intent, int requestCode) {
4966        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
4967        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
4968    }
4969
4970    /**
4971     * If this View corresponds to the calling who, dispatches the activity result.
4972     * @param who The identifier for the targeted View to receive the result.
4973     * @param requestCode The integer request code originally supplied to
4974     *                    startActivityForResult(), allowing you to identify who this
4975     *                    result came from.
4976     * @param resultCode The integer result code returned by the child activity
4977     *                   through its setResult().
4978     * @param data An Intent, which can return result data to the caller
4979     *               (various data can be attached to Intent "extras").
4980     * @return {@code true} if the activity result was dispatched.
4981     * @hide
4982     */
4983    public boolean dispatchActivityResult(
4984            String who, int requestCode, int resultCode, Intent data) {
4985        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
4986            onActivityResult(requestCode, resultCode, data);
4987            mStartActivityRequestWho = null;
4988            return true;
4989        }
4990        return false;
4991    }
4992
4993    /**
4994     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
4995     *
4996     * @param requestCode The integer request code originally supplied to
4997     *                    startActivityForResult(), allowing you to identify who this
4998     *                    result came from.
4999     * @param resultCode The integer result code returned by the child activity
5000     *                   through its setResult().
5001     * @param data An Intent, which can return result data to the caller
5002     *               (various data can be attached to Intent "extras").
5003     * @hide
5004     */
5005    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5006        // Do nothing.
5007    }
5008
5009    /**
5010     * Register a callback to be invoked when a hardware key is pressed in this view.
5011     * Key presses in software input methods will generally not trigger the methods of
5012     * this listener.
5013     * @param l the key listener to attach to this view
5014     */
5015    public void setOnKeyListener(OnKeyListener l) {
5016        getListenerInfo().mOnKeyListener = l;
5017    }
5018
5019    /**
5020     * Register a callback to be invoked when a touch event is sent to this view.
5021     * @param l the touch listener to attach to this view
5022     */
5023    public void setOnTouchListener(OnTouchListener l) {
5024        getListenerInfo().mOnTouchListener = l;
5025    }
5026
5027    /**
5028     * Register a callback to be invoked when a generic motion event is sent to this view.
5029     * @param l the generic motion listener to attach to this view
5030     */
5031    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5032        getListenerInfo().mOnGenericMotionListener = l;
5033    }
5034
5035    /**
5036     * Register a callback to be invoked when a hover event is sent to this view.
5037     * @param l the hover listener to attach to this view
5038     */
5039    public void setOnHoverListener(OnHoverListener l) {
5040        getListenerInfo().mOnHoverListener = l;
5041    }
5042
5043    /**
5044     * Register a drag event listener callback object for this View. The parameter is
5045     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5046     * View, the system calls the
5047     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5048     * @param l An implementation of {@link android.view.View.OnDragListener}.
5049     */
5050    public void setOnDragListener(OnDragListener l) {
5051        getListenerInfo().mOnDragListener = l;
5052    }
5053
5054    /**
5055     * Give this view focus. This will cause
5056     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5057     *
5058     * Note: this does not check whether this {@link View} should get focus, it just
5059     * gives it focus no matter what.  It should only be called internally by framework
5060     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5061     *
5062     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5063     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5064     *        focus moved when requestFocus() is called. It may not always
5065     *        apply, in which case use the default View.FOCUS_DOWN.
5066     * @param previouslyFocusedRect The rectangle of the view that had focus
5067     *        prior in this View's coordinate system.
5068     */
5069    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5070        if (DBG) {
5071            System.out.println(this + " requestFocus()");
5072        }
5073
5074        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5075            mPrivateFlags |= PFLAG_FOCUSED;
5076
5077            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5078
5079            if (mParent != null) {
5080                mParent.requestChildFocus(this, this);
5081            }
5082
5083            if (mAttachInfo != null) {
5084                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5085            }
5086
5087            onFocusChanged(true, direction, previouslyFocusedRect);
5088            refreshDrawableState();
5089        }
5090    }
5091
5092    /**
5093     * Populates <code>outRect</code> with the hotspot bounds. By default,
5094     * the hotspot bounds are identical to the screen bounds.
5095     *
5096     * @param outRect rect to populate with hotspot bounds
5097     * @hide Only for internal use by views and widgets.
5098     */
5099    public void getHotspotBounds(Rect outRect) {
5100        final Drawable background = getBackground();
5101        if (background != null) {
5102            background.getHotspotBounds(outRect);
5103        } else {
5104            getBoundsOnScreen(outRect);
5105        }
5106    }
5107
5108    /**
5109     * Request that a rectangle of this view be visible on the screen,
5110     * scrolling if necessary just enough.
5111     *
5112     * <p>A View should call this if it maintains some notion of which part
5113     * of its content is interesting.  For example, a text editing view
5114     * should call this when its cursor moves.
5115     *
5116     * @param rectangle The rectangle.
5117     * @return Whether any parent scrolled.
5118     */
5119    public boolean requestRectangleOnScreen(Rect rectangle) {
5120        return requestRectangleOnScreen(rectangle, false);
5121    }
5122
5123    /**
5124     * Request that a rectangle of this view be visible on the screen,
5125     * scrolling if necessary just enough.
5126     *
5127     * <p>A View should call this if it maintains some notion of which part
5128     * of its content is interesting.  For example, a text editing view
5129     * should call this when its cursor moves.
5130     *
5131     * <p>When <code>immediate</code> is set to true, scrolling will not be
5132     * animated.
5133     *
5134     * @param rectangle The rectangle.
5135     * @param immediate True to forbid animated scrolling, false otherwise
5136     * @return Whether any parent scrolled.
5137     */
5138    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5139        if (mParent == null) {
5140            return false;
5141        }
5142
5143        View child = this;
5144
5145        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5146        position.set(rectangle);
5147
5148        ViewParent parent = mParent;
5149        boolean scrolled = false;
5150        while (parent != null) {
5151            rectangle.set((int) position.left, (int) position.top,
5152                    (int) position.right, (int) position.bottom);
5153
5154            scrolled |= parent.requestChildRectangleOnScreen(child,
5155                    rectangle, immediate);
5156
5157            if (!child.hasIdentityMatrix()) {
5158                child.getMatrix().mapRect(position);
5159            }
5160
5161            position.offset(child.mLeft, child.mTop);
5162
5163            if (!(parent instanceof View)) {
5164                break;
5165            }
5166
5167            View parentView = (View) parent;
5168
5169            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5170
5171            child = parentView;
5172            parent = child.getParent();
5173        }
5174
5175        return scrolled;
5176    }
5177
5178    /**
5179     * Called when this view wants to give up focus. If focus is cleared
5180     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5181     * <p>
5182     * <strong>Note:</strong> When a View clears focus the framework is trying
5183     * to give focus to the first focusable View from the top. Hence, if this
5184     * View is the first from the top that can take focus, then all callbacks
5185     * related to clearing focus will be invoked after which the framework will
5186     * give focus to this view.
5187     * </p>
5188     */
5189    public void clearFocus() {
5190        if (DBG) {
5191            System.out.println(this + " clearFocus()");
5192        }
5193
5194        clearFocusInternal(null, true, true);
5195    }
5196
5197    /**
5198     * Clears focus from the view, optionally propagating the change up through
5199     * the parent hierarchy and requesting that the root view place new focus.
5200     *
5201     * @param propagate whether to propagate the change up through the parent
5202     *            hierarchy
5203     * @param refocus when propagate is true, specifies whether to request the
5204     *            root view place new focus
5205     */
5206    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5207        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5208            mPrivateFlags &= ~PFLAG_FOCUSED;
5209
5210            if (propagate && mParent != null) {
5211                mParent.clearChildFocus(this);
5212            }
5213
5214            onFocusChanged(false, 0, null);
5215            refreshDrawableState();
5216
5217            if (propagate && (!refocus || !rootViewRequestFocus())) {
5218                notifyGlobalFocusCleared(this);
5219            }
5220        }
5221    }
5222
5223    void notifyGlobalFocusCleared(View oldFocus) {
5224        if (oldFocus != null && mAttachInfo != null) {
5225            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5226        }
5227    }
5228
5229    boolean rootViewRequestFocus() {
5230        final View root = getRootView();
5231        return root != null && root.requestFocus();
5232    }
5233
5234    /**
5235     * Called internally by the view system when a new view is getting focus.
5236     * This is what clears the old focus.
5237     * <p>
5238     * <b>NOTE:</b> The parent view's focused child must be updated manually
5239     * after calling this method. Otherwise, the view hierarchy may be left in
5240     * an inconstent state.
5241     */
5242    void unFocus(View focused) {
5243        if (DBG) {
5244            System.out.println(this + " unFocus()");
5245        }
5246
5247        clearFocusInternal(focused, false, false);
5248    }
5249
5250    /**
5251     * Returns true if this view has focus itself, or is the ancestor of the
5252     * view that has focus.
5253     *
5254     * @return True if this view has or contains focus, false otherwise.
5255     */
5256    @ViewDebug.ExportedProperty(category = "focus")
5257    public boolean hasFocus() {
5258        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5259    }
5260
5261    /**
5262     * Returns true if this view is focusable or if it contains a reachable View
5263     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5264     * is a View whose parents do not block descendants focus.
5265     *
5266     * Only {@link #VISIBLE} views are considered focusable.
5267     *
5268     * @return True if the view is focusable or if the view contains a focusable
5269     *         View, false otherwise.
5270     *
5271     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5272     * @see ViewGroup#getTouchscreenBlocksFocus()
5273     */
5274    public boolean hasFocusable() {
5275        if (!isFocusableInTouchMode()) {
5276            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5277                final ViewGroup g = (ViewGroup) p;
5278                if (g.shouldBlockFocusForTouchscreen()) {
5279                    return false;
5280                }
5281            }
5282        }
5283        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5284    }
5285
5286    /**
5287     * Called by the view system when the focus state of this view changes.
5288     * When the focus change event is caused by directional navigation, direction
5289     * and previouslyFocusedRect provide insight into where the focus is coming from.
5290     * When overriding, be sure to call up through to the super class so that
5291     * the standard focus handling will occur.
5292     *
5293     * @param gainFocus True if the View has focus; false otherwise.
5294     * @param direction The direction focus has moved when requestFocus()
5295     *                  is called to give this view focus. Values are
5296     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5297     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5298     *                  It may not always apply, in which case use the default.
5299     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5300     *        system, of the previously focused view.  If applicable, this will be
5301     *        passed in as finer grained information about where the focus is coming
5302     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5303     */
5304    @CallSuper
5305    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5306            @Nullable Rect previouslyFocusedRect) {
5307        if (gainFocus) {
5308            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5309        } else {
5310            notifyViewAccessibilityStateChangedIfNeeded(
5311                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5312        }
5313
5314        InputMethodManager imm = InputMethodManager.peekInstance();
5315        if (!gainFocus) {
5316            if (isPressed()) {
5317                setPressed(false);
5318            }
5319            if (imm != null && mAttachInfo != null
5320                    && mAttachInfo.mHasWindowFocus) {
5321                imm.focusOut(this);
5322            }
5323            onFocusLost();
5324        } else if (imm != null && mAttachInfo != null
5325                && mAttachInfo.mHasWindowFocus) {
5326            imm.focusIn(this);
5327        }
5328
5329        invalidate(true);
5330        ListenerInfo li = mListenerInfo;
5331        if (li != null && li.mOnFocusChangeListener != null) {
5332            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5333        }
5334
5335        if (mAttachInfo != null) {
5336            mAttachInfo.mKeyDispatchState.reset(this);
5337        }
5338    }
5339
5340    /**
5341     * Sends an accessibility event of the given type. If accessibility is
5342     * not enabled this method has no effect. The default implementation calls
5343     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5344     * to populate information about the event source (this View), then calls
5345     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5346     * populate the text content of the event source including its descendants,
5347     * and last calls
5348     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5349     * on its parent to request sending of the event to interested parties.
5350     * <p>
5351     * If an {@link AccessibilityDelegate} has been specified via calling
5352     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5353     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5354     * responsible for handling this call.
5355     * </p>
5356     *
5357     * @param eventType The type of the event to send, as defined by several types from
5358     * {@link android.view.accessibility.AccessibilityEvent}, such as
5359     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5360     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5361     *
5362     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5363     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5364     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5365     * @see AccessibilityDelegate
5366     */
5367    public void sendAccessibilityEvent(int eventType) {
5368        if (mAccessibilityDelegate != null) {
5369            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5370        } else {
5371            sendAccessibilityEventInternal(eventType);
5372        }
5373    }
5374
5375    /**
5376     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5377     * {@link AccessibilityEvent} to make an announcement which is related to some
5378     * sort of a context change for which none of the events representing UI transitions
5379     * is a good fit. For example, announcing a new page in a book. If accessibility
5380     * is not enabled this method does nothing.
5381     *
5382     * @param text The announcement text.
5383     */
5384    public void announceForAccessibility(CharSequence text) {
5385        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5386            AccessibilityEvent event = AccessibilityEvent.obtain(
5387                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5388            onInitializeAccessibilityEvent(event);
5389            event.getText().add(text);
5390            event.setContentDescription(null);
5391            mParent.requestSendAccessibilityEvent(this, event);
5392        }
5393    }
5394
5395    /**
5396     * @see #sendAccessibilityEvent(int)
5397     *
5398     * Note: Called from the default {@link AccessibilityDelegate}.
5399     *
5400     * @hide
5401     */
5402    public void sendAccessibilityEventInternal(int eventType) {
5403        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5404            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5405        }
5406    }
5407
5408    /**
5409     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5410     * takes as an argument an empty {@link AccessibilityEvent} and does not
5411     * perform a check whether accessibility is enabled.
5412     * <p>
5413     * If an {@link AccessibilityDelegate} has been specified via calling
5414     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5415     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5416     * is responsible for handling this call.
5417     * </p>
5418     *
5419     * @param event The event to send.
5420     *
5421     * @see #sendAccessibilityEvent(int)
5422     */
5423    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5424        if (mAccessibilityDelegate != null) {
5425            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5426        } else {
5427            sendAccessibilityEventUncheckedInternal(event);
5428        }
5429    }
5430
5431    /**
5432     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5433     *
5434     * Note: Called from the default {@link AccessibilityDelegate}.
5435     *
5436     * @hide
5437     */
5438    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5439        if (!isShown()) {
5440            return;
5441        }
5442        onInitializeAccessibilityEvent(event);
5443        // Only a subset of accessibility events populates text content.
5444        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5445            dispatchPopulateAccessibilityEvent(event);
5446        }
5447        // In the beginning we called #isShown(), so we know that getParent() is not null.
5448        getParent().requestSendAccessibilityEvent(this, event);
5449    }
5450
5451    /**
5452     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5453     * to its children for adding their text content to the event. Note that the
5454     * event text is populated in a separate dispatch path since we add to the
5455     * event not only the text of the source but also the text of all its descendants.
5456     * A typical implementation will call
5457     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5458     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5459     * on each child. Override this method if custom population of the event text
5460     * content is required.
5461     * <p>
5462     * If an {@link AccessibilityDelegate} has been specified via calling
5463     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5464     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5465     * is responsible for handling this call.
5466     * </p>
5467     * <p>
5468     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5469     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5470     * </p>
5471     *
5472     * @param event The event.
5473     *
5474     * @return True if the event population was completed.
5475     */
5476    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5477        if (mAccessibilityDelegate != null) {
5478            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5479        } else {
5480            return dispatchPopulateAccessibilityEventInternal(event);
5481        }
5482    }
5483
5484    /**
5485     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5486     *
5487     * Note: Called from the default {@link AccessibilityDelegate}.
5488     *
5489     * @hide
5490     */
5491    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5492        onPopulateAccessibilityEvent(event);
5493        return false;
5494    }
5495
5496    /**
5497     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5498     * giving a chance to this View to populate the accessibility event with its
5499     * text content. While this method is free to modify event
5500     * attributes other than text content, doing so should normally be performed in
5501     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5502     * <p>
5503     * Example: Adding formatted date string to an accessibility event in addition
5504     *          to the text added by the super implementation:
5505     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5506     *     super.onPopulateAccessibilityEvent(event);
5507     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5508     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5509     *         mCurrentDate.getTimeInMillis(), flags);
5510     *     event.getText().add(selectedDateUtterance);
5511     * }</pre>
5512     * <p>
5513     * If an {@link AccessibilityDelegate} has been specified via calling
5514     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5515     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5516     * is responsible for handling this call.
5517     * </p>
5518     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5519     * information to the event, in case the default implementation has basic information to add.
5520     * </p>
5521     *
5522     * @param event The accessibility event which to populate.
5523     *
5524     * @see #sendAccessibilityEvent(int)
5525     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5526     */
5527    @CallSuper
5528    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5529        if (mAccessibilityDelegate != null) {
5530            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5531        } else {
5532            onPopulateAccessibilityEventInternal(event);
5533        }
5534    }
5535
5536    /**
5537     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5538     *
5539     * Note: Called from the default {@link AccessibilityDelegate}.
5540     *
5541     * @hide
5542     */
5543    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5544    }
5545
5546    /**
5547     * Initializes an {@link AccessibilityEvent} with information about
5548     * this View which is the event source. In other words, the source of
5549     * an accessibility event is the view whose state change triggered firing
5550     * the event.
5551     * <p>
5552     * Example: Setting the password property of an event in addition
5553     *          to properties set by the super implementation:
5554     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5555     *     super.onInitializeAccessibilityEvent(event);
5556     *     event.setPassword(true);
5557     * }</pre>
5558     * <p>
5559     * If an {@link AccessibilityDelegate} has been specified via calling
5560     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5561     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5562     * is responsible for handling this call.
5563     * </p>
5564     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5565     * information to the event, in case the default implementation has basic information to add.
5566     * </p>
5567     * @param event The event to initialize.
5568     *
5569     * @see #sendAccessibilityEvent(int)
5570     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5571     */
5572    @CallSuper
5573    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5574        if (mAccessibilityDelegate != null) {
5575            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5576        } else {
5577            onInitializeAccessibilityEventInternal(event);
5578        }
5579    }
5580
5581    /**
5582     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5583     *
5584     * Note: Called from the default {@link AccessibilityDelegate}.
5585     *
5586     * @hide
5587     */
5588    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5589        event.setSource(this);
5590        event.setClassName(getAccessibilityClassName());
5591        event.setPackageName(getContext().getPackageName());
5592        event.setEnabled(isEnabled());
5593        event.setContentDescription(mContentDescription);
5594
5595        switch (event.getEventType()) {
5596            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5597                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5598                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5599                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5600                event.setItemCount(focusablesTempList.size());
5601                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5602                if (mAttachInfo != null) {
5603                    focusablesTempList.clear();
5604                }
5605            } break;
5606            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5607                CharSequence text = getIterableTextForAccessibility();
5608                if (text != null && text.length() > 0) {
5609                    event.setFromIndex(getAccessibilitySelectionStart());
5610                    event.setToIndex(getAccessibilitySelectionEnd());
5611                    event.setItemCount(text.length());
5612                }
5613            } break;
5614        }
5615    }
5616
5617    /**
5618     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5619     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5620     * This method is responsible for obtaining an accessibility node info from a
5621     * pool of reusable instances and calling
5622     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5623     * initialize the former.
5624     * <p>
5625     * Note: The client is responsible for recycling the obtained instance by calling
5626     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5627     * </p>
5628     *
5629     * @return A populated {@link AccessibilityNodeInfo}.
5630     *
5631     * @see AccessibilityNodeInfo
5632     */
5633    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5634        if (mAccessibilityDelegate != null) {
5635            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5636        } else {
5637            return createAccessibilityNodeInfoInternal();
5638        }
5639    }
5640
5641    /**
5642     * @see #createAccessibilityNodeInfo()
5643     *
5644     * @hide
5645     */
5646    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5647        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5648        if (provider != null) {
5649            return provider.createAccessibilityNodeInfo(View.NO_ID);
5650        } else {
5651            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5652            onInitializeAccessibilityNodeInfo(info);
5653            return info;
5654        }
5655    }
5656
5657    /**
5658     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5659     * The base implementation sets:
5660     * <ul>
5661     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5662     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5663     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5664     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5665     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5666     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5667     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5668     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5669     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5670     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5671     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5672     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5673     * </ul>
5674     * <p>
5675     * Subclasses should override this method, call the super implementation,
5676     * and set additional attributes.
5677     * </p>
5678     * <p>
5679     * If an {@link AccessibilityDelegate} has been specified via calling
5680     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5681     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5682     * is responsible for handling this call.
5683     * </p>
5684     *
5685     * @param info The instance to initialize.
5686     */
5687    @CallSuper
5688    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5689        if (mAccessibilityDelegate != null) {
5690            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5691        } else {
5692            onInitializeAccessibilityNodeInfoInternal(info);
5693        }
5694    }
5695
5696    /**
5697     * Gets the location of this view in screen coordinates.
5698     *
5699     * @param outRect The output location
5700     * @hide
5701     */
5702    public void getBoundsOnScreen(Rect outRect) {
5703        getBoundsOnScreen(outRect, false);
5704    }
5705
5706    /**
5707     * Gets the location of this view in screen coordinates.
5708     *
5709     * @param outRect The output location
5710     * @param clipToParent Whether to clip child bounds to the parent ones.
5711     * @hide
5712     */
5713    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
5714        if (mAttachInfo == null) {
5715            return;
5716        }
5717
5718        RectF position = mAttachInfo.mTmpTransformRect;
5719        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5720
5721        if (!hasIdentityMatrix()) {
5722            getMatrix().mapRect(position);
5723        }
5724
5725        position.offset(mLeft, mTop);
5726
5727        ViewParent parent = mParent;
5728        while (parent instanceof View) {
5729            View parentView = (View) parent;
5730
5731            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5732
5733            if (clipToParent) {
5734                position.left = Math.max(position.left, 0);
5735                position.top = Math.max(position.top, 0);
5736                position.right = Math.min(position.right, parentView.getWidth());
5737                position.bottom = Math.min(position.bottom, parentView.getHeight());
5738            }
5739
5740            if (!parentView.hasIdentityMatrix()) {
5741                parentView.getMatrix().mapRect(position);
5742            }
5743
5744            position.offset(parentView.mLeft, parentView.mTop);
5745
5746            parent = parentView.mParent;
5747        }
5748
5749        if (parent instanceof ViewRootImpl) {
5750            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5751            position.offset(0, -viewRootImpl.mCurScrollY);
5752        }
5753
5754        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5755
5756        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5757                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5758    }
5759
5760    /**
5761     * Return the class name of this object to be used for accessibility purposes.
5762     * Subclasses should only override this if they are implementing something that
5763     * should be seen as a completely new class of view when used by accessibility,
5764     * unrelated to the class it is deriving from.  This is used to fill in
5765     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
5766     */
5767    public CharSequence getAccessibilityClassName() {
5768        return View.class.getName();
5769    }
5770
5771    /**
5772     * Called when assist structure is being retrieved from a view as part of
5773     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
5774     * @param structure Fill in with structured view data.  The default implementation
5775     * fills in all data that can be inferred from the view itself.
5776     */
5777    public void onProvideAssistStructure(ViewAssistStructure structure) {
5778        final int id = mID;
5779        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
5780                && (id&0x0000ffff) != 0) {
5781            String pkg, type, entry;
5782            try {
5783                final Resources res = getResources();
5784                entry = res.getResourceEntryName(id);
5785                type = res.getResourceTypeName(id);
5786                pkg = res.getResourcePackageName(id);
5787            } catch (Resources.NotFoundException e) {
5788                entry = type = pkg = null;
5789            }
5790            structure.setId(id, pkg, type, entry);
5791        } else {
5792            structure.setId(id, null, null, null);
5793        }
5794        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
5795        structure.setVisibility(getVisibility());
5796        structure.setEnabled(isEnabled());
5797        if (isClickable()) {
5798            structure.setClickable(true);
5799        }
5800        if (isFocusable()) {
5801            structure.setFocusable(true);
5802        }
5803        if (isFocused()) {
5804            structure.setFocused(true);
5805        }
5806        if (isAccessibilityFocused()) {
5807            structure.setAccessibilityFocused(true);
5808        }
5809        if (isSelected()) {
5810            structure.setSelected(true);
5811        }
5812        if (isActivated()) {
5813            structure.setActivated(true);
5814        }
5815        if (isLongClickable()) {
5816            structure.setLongClickable(true);
5817        }
5818        if (this instanceof Checkable) {
5819            structure.setCheckable(true);
5820            if (((Checkable)this).isChecked()) {
5821                structure.setChecked(true);
5822            }
5823        }
5824        structure.setClassName(getAccessibilityClassName().toString());
5825        structure.setContentDescription(getContentDescription());
5826    }
5827
5828    /**
5829     * Called when assist structure is being retrieved from a view as part of
5830     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
5831     * generate additional virtual structure under this view.  The defaullt implementation
5832     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
5833     * view's virtual accessibility nodes, if any.  You can override this for a more
5834     * optimal implementation providing this data.
5835     */
5836    public void onProvideVirtualAssistStructure(ViewAssistStructure structure) {
5837        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5838        if (provider != null) {
5839            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
5840            Log.i("View", "Provider of " + this + ": children=" + info.getChildCount());
5841            structure.setChildCount(1);
5842            ViewAssistStructure root = structure.newChild(0);
5843            populateVirtualAssistStructure(root, provider, info);
5844            info.recycle();
5845        }
5846    }
5847
5848    private void populateVirtualAssistStructure(ViewAssistStructure structure,
5849            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
5850        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
5851                null, null, null);
5852        Rect rect = structure.getTempRect();
5853        info.getBoundsInParent(rect);
5854        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
5855        structure.setVisibility(VISIBLE);
5856        structure.setEnabled(info.isEnabled());
5857        if (info.isClickable()) {
5858            structure.setClickable(true);
5859        }
5860        if (info.isFocusable()) {
5861            structure.setFocusable(true);
5862        }
5863        if (info.isFocused()) {
5864            structure.setFocused(true);
5865        }
5866        if (info.isAccessibilityFocused()) {
5867            structure.setAccessibilityFocused(true);
5868        }
5869        if (info.isSelected()) {
5870            structure.setSelected(true);
5871        }
5872        if (info.isLongClickable()) {
5873            structure.setLongClickable(true);
5874        }
5875        if (info.isCheckable()) {
5876            structure.setCheckable(true);
5877            if (info.isChecked()) {
5878                structure.setChecked(true);
5879            }
5880        }
5881        CharSequence cname = info.getClassName();
5882        structure.setClassName(cname != null ? cname.toString() : null);
5883        structure.setContentDescription(info.getContentDescription());
5884        Log.i("View", "vassist " + cname + " @ " + rect.toShortString()
5885                + " text=" + info.getText() + " cd=" + info.getContentDescription());
5886        if (info.getText() != null || info.getError() != null) {
5887            structure.setText(info.getText(), info.getTextSelectionStart(),
5888                    info.getTextSelectionEnd());
5889        }
5890        final int NCHILDREN = info.getChildCount();
5891        if (NCHILDREN > 0) {
5892            structure.setChildCount(NCHILDREN);
5893            for (int i=0; i<NCHILDREN; i++) {
5894                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
5895                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
5896                ViewAssistStructure child = structure.newChild(i);
5897                populateVirtualAssistStructure(child, provider, cinfo);
5898                cinfo.recycle();
5899            }
5900        }
5901    }
5902
5903    /**
5904     * Dispatch creation of {@link ViewAssistStructure} down the hierarchy.  The default
5905     * implementation calls {@link #onProvideAssistStructure} and
5906     * {@link #onProvideVirtualAssistStructure}.
5907     */
5908    public void dispatchProvideAssistStructure(ViewAssistStructure structure) {
5909        if (!isAssistBlocked()) {
5910            onProvideAssistStructure(structure);
5911            onProvideVirtualAssistStructure(structure);
5912        } else {
5913            structure.setClassName(getAccessibilityClassName().toString());
5914            structure.setAssistBlocked(true);
5915        }
5916    }
5917
5918    /**
5919     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5920     *
5921     * Note: Called from the default {@link AccessibilityDelegate}.
5922     *
5923     * @hide
5924     */
5925    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5926        Rect bounds = mAttachInfo.mTmpInvalRect;
5927
5928        getDrawingRect(bounds);
5929        info.setBoundsInParent(bounds);
5930
5931        getBoundsOnScreen(bounds, true);
5932        info.setBoundsInScreen(bounds);
5933
5934        ViewParent parent = getParentForAccessibility();
5935        if (parent instanceof View) {
5936            info.setParent((View) parent);
5937        }
5938
5939        if (mID != View.NO_ID) {
5940            View rootView = getRootView();
5941            if (rootView == null) {
5942                rootView = this;
5943            }
5944
5945            View label = rootView.findLabelForView(this, mID);
5946            if (label != null) {
5947                info.setLabeledBy(label);
5948            }
5949
5950            if ((mAttachInfo.mAccessibilityFetchFlags
5951                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5952                    && Resources.resourceHasPackage(mID)) {
5953                try {
5954                    String viewId = getResources().getResourceName(mID);
5955                    info.setViewIdResourceName(viewId);
5956                } catch (Resources.NotFoundException nfe) {
5957                    /* ignore */
5958                }
5959            }
5960        }
5961
5962        if (mLabelForId != View.NO_ID) {
5963            View rootView = getRootView();
5964            if (rootView == null) {
5965                rootView = this;
5966            }
5967            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5968            if (labeled != null) {
5969                info.setLabelFor(labeled);
5970            }
5971        }
5972
5973        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
5974            View rootView = getRootView();
5975            if (rootView == null) {
5976                rootView = this;
5977            }
5978            View next = rootView.findViewInsideOutShouldExist(this,
5979                    mAccessibilityTraversalBeforeId);
5980            if (next != null) {
5981                info.setTraversalBefore(next);
5982            }
5983        }
5984
5985        if (mAccessibilityTraversalAfterId != View.NO_ID) {
5986            View rootView = getRootView();
5987            if (rootView == null) {
5988                rootView = this;
5989            }
5990            View next = rootView.findViewInsideOutShouldExist(this,
5991                    mAccessibilityTraversalAfterId);
5992            if (next != null) {
5993                info.setTraversalAfter(next);
5994            }
5995        }
5996
5997        info.setVisibleToUser(isVisibleToUser());
5998
5999        info.setPackageName(mContext.getPackageName());
6000        info.setClassName(getAccessibilityClassName());
6001        info.setContentDescription(getContentDescription());
6002
6003        info.setEnabled(isEnabled());
6004        info.setClickable(isClickable());
6005        info.setFocusable(isFocusable());
6006        info.setFocused(isFocused());
6007        info.setAccessibilityFocused(isAccessibilityFocused());
6008        info.setSelected(isSelected());
6009        info.setLongClickable(isLongClickable());
6010        info.setLiveRegion(getAccessibilityLiveRegion());
6011
6012        // TODO: These make sense only if we are in an AdapterView but all
6013        // views can be selected. Maybe from accessibility perspective
6014        // we should report as selectable view in an AdapterView.
6015        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6016        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6017
6018        if (isFocusable()) {
6019            if (isFocused()) {
6020                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6021            } else {
6022                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6023            }
6024        }
6025
6026        if (!isAccessibilityFocused()) {
6027            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6028        } else {
6029            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6030        }
6031
6032        if (isClickable() && isEnabled()) {
6033            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6034        }
6035
6036        if (isLongClickable() && isEnabled()) {
6037            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6038        }
6039
6040        CharSequence text = getIterableTextForAccessibility();
6041        if (text != null && text.length() > 0) {
6042            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6043
6044            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6045            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6046            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6047            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6048                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6049                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6050        }
6051
6052        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6053    }
6054
6055    private View findLabelForView(View view, int labeledId) {
6056        if (mMatchLabelForPredicate == null) {
6057            mMatchLabelForPredicate = new MatchLabelForPredicate();
6058        }
6059        mMatchLabelForPredicate.mLabeledId = labeledId;
6060        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
6061    }
6062
6063    /**
6064     * Computes whether this view is visible to the user. Such a view is
6065     * attached, visible, all its predecessors are visible, it is not clipped
6066     * entirely by its predecessors, and has an alpha greater than zero.
6067     *
6068     * @return Whether the view is visible on the screen.
6069     *
6070     * @hide
6071     */
6072    protected boolean isVisibleToUser() {
6073        return isVisibleToUser(null);
6074    }
6075
6076    /**
6077     * Computes whether the given portion of this view is visible to the user.
6078     * Such a view is attached, visible, all its predecessors are visible,
6079     * has an alpha greater than zero, and the specified portion is not
6080     * clipped entirely by its predecessors.
6081     *
6082     * @param boundInView the portion of the view to test; coordinates should be relative; may be
6083     *                    <code>null</code>, and the entire view will be tested in this case.
6084     *                    When <code>true</code> is returned by the function, the actual visible
6085     *                    region will be stored in this parameter; that is, if boundInView is fully
6086     *                    contained within the view, no modification will be made, otherwise regions
6087     *                    outside of the visible area of the view will be clipped.
6088     *
6089     * @return Whether the specified portion of the view is visible on the screen.
6090     *
6091     * @hide
6092     */
6093    protected boolean isVisibleToUser(Rect boundInView) {
6094        if (mAttachInfo != null) {
6095            // Attached to invisible window means this view is not visible.
6096            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
6097                return false;
6098            }
6099            // An invisible predecessor or one with alpha zero means
6100            // that this view is not visible to the user.
6101            Object current = this;
6102            while (current instanceof View) {
6103                View view = (View) current;
6104                // We have attach info so this view is attached and there is no
6105                // need to check whether we reach to ViewRootImpl on the way up.
6106                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
6107                        view.getVisibility() != VISIBLE) {
6108                    return false;
6109                }
6110                current = view.mParent;
6111            }
6112            // Check if the view is entirely covered by its predecessors.
6113            Rect visibleRect = mAttachInfo.mTmpInvalRect;
6114            Point offset = mAttachInfo.mPoint;
6115            if (!getGlobalVisibleRect(visibleRect, offset)) {
6116                return false;
6117            }
6118            // Check if the visible portion intersects the rectangle of interest.
6119            if (boundInView != null) {
6120                visibleRect.offset(-offset.x, -offset.y);
6121                return boundInView.intersect(visibleRect);
6122            }
6123            return true;
6124        }
6125        return false;
6126    }
6127
6128    /**
6129     * Returns the delegate for implementing accessibility support via
6130     * composition. For more details see {@link AccessibilityDelegate}.
6131     *
6132     * @return The delegate, or null if none set.
6133     *
6134     * @hide
6135     */
6136    public AccessibilityDelegate getAccessibilityDelegate() {
6137        return mAccessibilityDelegate;
6138    }
6139
6140    /**
6141     * Sets a delegate for implementing accessibility support via composition as
6142     * opposed to inheritance. The delegate's primary use is for implementing
6143     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
6144     *
6145     * @param delegate The delegate instance.
6146     *
6147     * @see AccessibilityDelegate
6148     */
6149    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
6150        mAccessibilityDelegate = delegate;
6151    }
6152
6153    /**
6154     * Gets the provider for managing a virtual view hierarchy rooted at this View
6155     * and reported to {@link android.accessibilityservice.AccessibilityService}s
6156     * that explore the window content.
6157     * <p>
6158     * If this method returns an instance, this instance is responsible for managing
6159     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
6160     * View including the one representing the View itself. Similarly the returned
6161     * instance is responsible for performing accessibility actions on any virtual
6162     * view or the root view itself.
6163     * </p>
6164     * <p>
6165     * If an {@link AccessibilityDelegate} has been specified via calling
6166     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6167     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
6168     * is responsible for handling this call.
6169     * </p>
6170     *
6171     * @return The provider.
6172     *
6173     * @see AccessibilityNodeProvider
6174     */
6175    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
6176        if (mAccessibilityDelegate != null) {
6177            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
6178        } else {
6179            return null;
6180        }
6181    }
6182
6183    /**
6184     * Gets the unique identifier of this view on the screen for accessibility purposes.
6185     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
6186     *
6187     * @return The view accessibility id.
6188     *
6189     * @hide
6190     */
6191    public int getAccessibilityViewId() {
6192        if (mAccessibilityViewId == NO_ID) {
6193            mAccessibilityViewId = sNextAccessibilityViewId++;
6194        }
6195        return mAccessibilityViewId;
6196    }
6197
6198    /**
6199     * Gets the unique identifier of the window in which this View reseides.
6200     *
6201     * @return The window accessibility id.
6202     *
6203     * @hide
6204     */
6205    public int getAccessibilityWindowId() {
6206        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
6207                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6208    }
6209
6210    /**
6211     * Gets the {@link View} description. It briefly describes the view and is
6212     * primarily used for accessibility support. Set this property to enable
6213     * better accessibility support for your application. This is especially
6214     * true for views that do not have textual representation (For example,
6215     * ImageButton).
6216     *
6217     * @return The content description.
6218     *
6219     * @attr ref android.R.styleable#View_contentDescription
6220     */
6221    @ViewDebug.ExportedProperty(category = "accessibility")
6222    public CharSequence getContentDescription() {
6223        return mContentDescription;
6224    }
6225
6226    /**
6227     * Sets the {@link View} description. It briefly describes the view and is
6228     * primarily used for accessibility support. Set this property to enable
6229     * better accessibility support for your application. This is especially
6230     * true for views that do not have textual representation (For example,
6231     * ImageButton).
6232     *
6233     * @param contentDescription The content description.
6234     *
6235     * @attr ref android.R.styleable#View_contentDescription
6236     */
6237    @RemotableViewMethod
6238    public void setContentDescription(CharSequence contentDescription) {
6239        if (mContentDescription == null) {
6240            if (contentDescription == null) {
6241                return;
6242            }
6243        } else if (mContentDescription.equals(contentDescription)) {
6244            return;
6245        }
6246        mContentDescription = contentDescription;
6247        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
6248        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
6249            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
6250            notifySubtreeAccessibilityStateChangedIfNeeded();
6251        } else {
6252            notifyViewAccessibilityStateChangedIfNeeded(
6253                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
6254        }
6255    }
6256
6257    /**
6258     * Sets the id of a view before which this one is visited in accessibility traversal.
6259     * A screen-reader must visit the content of this view before the content of the one
6260     * it precedes. For example, if view B is set to be before view A, then a screen-reader
6261     * will traverse the entire content of B before traversing the entire content of A,
6262     * regardles of what traversal strategy it is using.
6263     * <p>
6264     * Views that do not have specified before/after relationships are traversed in order
6265     * determined by the screen-reader.
6266     * </p>
6267     * <p>
6268     * Setting that this view is before a view that is not important for accessibility
6269     * or if this view is not important for accessibility will have no effect as the
6270     * screen-reader is not aware of unimportant views.
6271     * </p>
6272     *
6273     * @param beforeId The id of a view this one precedes in accessibility traversal.
6274     *
6275     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
6276     *
6277     * @see #setImportantForAccessibility(int)
6278     */
6279    @RemotableViewMethod
6280    public void setAccessibilityTraversalBefore(int beforeId) {
6281        if (mAccessibilityTraversalBeforeId == beforeId) {
6282            return;
6283        }
6284        mAccessibilityTraversalBeforeId = beforeId;
6285        notifyViewAccessibilityStateChangedIfNeeded(
6286                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6287    }
6288
6289    /**
6290     * Gets the id of a view before which this one is visited in accessibility traversal.
6291     *
6292     * @return The id of a view this one precedes in accessibility traversal if
6293     *         specified, otherwise {@link #NO_ID}.
6294     *
6295     * @see #setAccessibilityTraversalBefore(int)
6296     */
6297    public int getAccessibilityTraversalBefore() {
6298        return mAccessibilityTraversalBeforeId;
6299    }
6300
6301    /**
6302     * Sets the id of a view after which this one is visited in accessibility traversal.
6303     * A screen-reader must visit the content of the other view before the content of this
6304     * one. For example, if view B is set to be after view A, then a screen-reader
6305     * will traverse the entire content of A before traversing the entire content of B,
6306     * regardles of what traversal strategy it is using.
6307     * <p>
6308     * Views that do not have specified before/after relationships are traversed in order
6309     * determined by the screen-reader.
6310     * </p>
6311     * <p>
6312     * Setting that this view is after a view that is not important for accessibility
6313     * or if this view is not important for accessibility will have no effect as the
6314     * screen-reader is not aware of unimportant views.
6315     * </p>
6316     *
6317     * @param afterId The id of a view this one succedees in accessibility traversal.
6318     *
6319     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
6320     *
6321     * @see #setImportantForAccessibility(int)
6322     */
6323    @RemotableViewMethod
6324    public void setAccessibilityTraversalAfter(int afterId) {
6325        if (mAccessibilityTraversalAfterId == afterId) {
6326            return;
6327        }
6328        mAccessibilityTraversalAfterId = afterId;
6329        notifyViewAccessibilityStateChangedIfNeeded(
6330                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6331    }
6332
6333    /**
6334     * Gets the id of a view after which this one is visited in accessibility traversal.
6335     *
6336     * @return The id of a view this one succeedes in accessibility traversal if
6337     *         specified, otherwise {@link #NO_ID}.
6338     *
6339     * @see #setAccessibilityTraversalAfter(int)
6340     */
6341    public int getAccessibilityTraversalAfter() {
6342        return mAccessibilityTraversalAfterId;
6343    }
6344
6345    /**
6346     * Gets the id of a view for which this view serves as a label for
6347     * accessibility purposes.
6348     *
6349     * @return The labeled view id.
6350     */
6351    @ViewDebug.ExportedProperty(category = "accessibility")
6352    public int getLabelFor() {
6353        return mLabelForId;
6354    }
6355
6356    /**
6357     * Sets the id of a view for which this view serves as a label for
6358     * accessibility purposes.
6359     *
6360     * @param id The labeled view id.
6361     */
6362    @RemotableViewMethod
6363    public void setLabelFor(@IdRes int id) {
6364        if (mLabelForId == id) {
6365            return;
6366        }
6367        mLabelForId = id;
6368        if (mLabelForId != View.NO_ID
6369                && mID == View.NO_ID) {
6370            mID = generateViewId();
6371        }
6372        notifyViewAccessibilityStateChangedIfNeeded(
6373                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6374    }
6375
6376    /**
6377     * Invoked whenever this view loses focus, either by losing window focus or by losing
6378     * focus within its window. This method can be used to clear any state tied to the
6379     * focus. For instance, if a button is held pressed with the trackball and the window
6380     * loses focus, this method can be used to cancel the press.
6381     *
6382     * Subclasses of View overriding this method should always call super.onFocusLost().
6383     *
6384     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6385     * @see #onWindowFocusChanged(boolean)
6386     *
6387     * @hide pending API council approval
6388     */
6389    @CallSuper
6390    protected void onFocusLost() {
6391        resetPressedState();
6392    }
6393
6394    private void resetPressedState() {
6395        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6396            return;
6397        }
6398
6399        if (isPressed()) {
6400            setPressed(false);
6401
6402            if (!mHasPerformedLongPress) {
6403                removeLongPressCallback();
6404            }
6405        }
6406    }
6407
6408    /**
6409     * Returns true if this view has focus
6410     *
6411     * @return True if this view has focus, false otherwise.
6412     */
6413    @ViewDebug.ExportedProperty(category = "focus")
6414    public boolean isFocused() {
6415        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6416    }
6417
6418    /**
6419     * Find the view in the hierarchy rooted at this view that currently has
6420     * focus.
6421     *
6422     * @return The view that currently has focus, or null if no focused view can
6423     *         be found.
6424     */
6425    public View findFocus() {
6426        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6427    }
6428
6429    /**
6430     * Indicates whether this view is one of the set of scrollable containers in
6431     * its window.
6432     *
6433     * @return whether this view is one of the set of scrollable containers in
6434     * its window
6435     *
6436     * @attr ref android.R.styleable#View_isScrollContainer
6437     */
6438    public boolean isScrollContainer() {
6439        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6440    }
6441
6442    /**
6443     * Change whether this view is one of the set of scrollable containers in
6444     * its window.  This will be used to determine whether the window can
6445     * resize or must pan when a soft input area is open -- scrollable
6446     * containers allow the window to use resize mode since the container
6447     * will appropriately shrink.
6448     *
6449     * @attr ref android.R.styleable#View_isScrollContainer
6450     */
6451    public void setScrollContainer(boolean isScrollContainer) {
6452        if (isScrollContainer) {
6453            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6454                mAttachInfo.mScrollContainers.add(this);
6455                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6456            }
6457            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6458        } else {
6459            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6460                mAttachInfo.mScrollContainers.remove(this);
6461            }
6462            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6463        }
6464    }
6465
6466    /**
6467     * Returns the quality of the drawing cache.
6468     *
6469     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6470     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6471     *
6472     * @see #setDrawingCacheQuality(int)
6473     * @see #setDrawingCacheEnabled(boolean)
6474     * @see #isDrawingCacheEnabled()
6475     *
6476     * @attr ref android.R.styleable#View_drawingCacheQuality
6477     */
6478    @DrawingCacheQuality
6479    public int getDrawingCacheQuality() {
6480        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6481    }
6482
6483    /**
6484     * Set the drawing cache quality of this view. This value is used only when the
6485     * drawing cache is enabled
6486     *
6487     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6488     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6489     *
6490     * @see #getDrawingCacheQuality()
6491     * @see #setDrawingCacheEnabled(boolean)
6492     * @see #isDrawingCacheEnabled()
6493     *
6494     * @attr ref android.R.styleable#View_drawingCacheQuality
6495     */
6496    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6497        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6498    }
6499
6500    /**
6501     * Returns whether the screen should remain on, corresponding to the current
6502     * value of {@link #KEEP_SCREEN_ON}.
6503     *
6504     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6505     *
6506     * @see #setKeepScreenOn(boolean)
6507     *
6508     * @attr ref android.R.styleable#View_keepScreenOn
6509     */
6510    public boolean getKeepScreenOn() {
6511        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6512    }
6513
6514    /**
6515     * Controls whether the screen should remain on, modifying the
6516     * value of {@link #KEEP_SCREEN_ON}.
6517     *
6518     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6519     *
6520     * @see #getKeepScreenOn()
6521     *
6522     * @attr ref android.R.styleable#View_keepScreenOn
6523     */
6524    public void setKeepScreenOn(boolean keepScreenOn) {
6525        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6526    }
6527
6528    /**
6529     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6530     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6531     *
6532     * @attr ref android.R.styleable#View_nextFocusLeft
6533     */
6534    public int getNextFocusLeftId() {
6535        return mNextFocusLeftId;
6536    }
6537
6538    /**
6539     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6540     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6541     * decide automatically.
6542     *
6543     * @attr ref android.R.styleable#View_nextFocusLeft
6544     */
6545    public void setNextFocusLeftId(int nextFocusLeftId) {
6546        mNextFocusLeftId = nextFocusLeftId;
6547    }
6548
6549    /**
6550     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6551     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6552     *
6553     * @attr ref android.R.styleable#View_nextFocusRight
6554     */
6555    public int getNextFocusRightId() {
6556        return mNextFocusRightId;
6557    }
6558
6559    /**
6560     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6561     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6562     * decide automatically.
6563     *
6564     * @attr ref android.R.styleable#View_nextFocusRight
6565     */
6566    public void setNextFocusRightId(int nextFocusRightId) {
6567        mNextFocusRightId = nextFocusRightId;
6568    }
6569
6570    /**
6571     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6572     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6573     *
6574     * @attr ref android.R.styleable#View_nextFocusUp
6575     */
6576    public int getNextFocusUpId() {
6577        return mNextFocusUpId;
6578    }
6579
6580    /**
6581     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6582     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6583     * decide automatically.
6584     *
6585     * @attr ref android.R.styleable#View_nextFocusUp
6586     */
6587    public void setNextFocusUpId(int nextFocusUpId) {
6588        mNextFocusUpId = nextFocusUpId;
6589    }
6590
6591    /**
6592     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6593     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6594     *
6595     * @attr ref android.R.styleable#View_nextFocusDown
6596     */
6597    public int getNextFocusDownId() {
6598        return mNextFocusDownId;
6599    }
6600
6601    /**
6602     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6603     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6604     * decide automatically.
6605     *
6606     * @attr ref android.R.styleable#View_nextFocusDown
6607     */
6608    public void setNextFocusDownId(int nextFocusDownId) {
6609        mNextFocusDownId = nextFocusDownId;
6610    }
6611
6612    /**
6613     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6614     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6615     *
6616     * @attr ref android.R.styleable#View_nextFocusForward
6617     */
6618    public int getNextFocusForwardId() {
6619        return mNextFocusForwardId;
6620    }
6621
6622    /**
6623     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6624     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6625     * decide automatically.
6626     *
6627     * @attr ref android.R.styleable#View_nextFocusForward
6628     */
6629    public void setNextFocusForwardId(int nextFocusForwardId) {
6630        mNextFocusForwardId = nextFocusForwardId;
6631    }
6632
6633    /**
6634     * Returns the visibility of this view and all of its ancestors
6635     *
6636     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6637     */
6638    public boolean isShown() {
6639        View current = this;
6640        //noinspection ConstantConditions
6641        do {
6642            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6643                return false;
6644            }
6645            ViewParent parent = current.mParent;
6646            if (parent == null) {
6647                return false; // We are not attached to the view root
6648            }
6649            if (!(parent instanceof View)) {
6650                return true;
6651            }
6652            current = (View) parent;
6653        } while (current != null);
6654
6655        return false;
6656    }
6657
6658    /**
6659     * Called by the view hierarchy when the content insets for a window have
6660     * changed, to allow it to adjust its content to fit within those windows.
6661     * The content insets tell you the space that the status bar, input method,
6662     * and other system windows infringe on the application's window.
6663     *
6664     * <p>You do not normally need to deal with this function, since the default
6665     * window decoration given to applications takes care of applying it to the
6666     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6667     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6668     * and your content can be placed under those system elements.  You can then
6669     * use this method within your view hierarchy if you have parts of your UI
6670     * which you would like to ensure are not being covered.
6671     *
6672     * <p>The default implementation of this method simply applies the content
6673     * insets to the view's padding, consuming that content (modifying the
6674     * insets to be 0), and returning true.  This behavior is off by default, but can
6675     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6676     *
6677     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6678     * insets object is propagated down the hierarchy, so any changes made to it will
6679     * be seen by all following views (including potentially ones above in
6680     * the hierarchy since this is a depth-first traversal).  The first view
6681     * that returns true will abort the entire traversal.
6682     *
6683     * <p>The default implementation works well for a situation where it is
6684     * used with a container that covers the entire window, allowing it to
6685     * apply the appropriate insets to its content on all edges.  If you need
6686     * a more complicated layout (such as two different views fitting system
6687     * windows, one on the top of the window, and one on the bottom),
6688     * you can override the method and handle the insets however you would like.
6689     * Note that the insets provided by the framework are always relative to the
6690     * far edges of the window, not accounting for the location of the called view
6691     * within that window.  (In fact when this method is called you do not yet know
6692     * where the layout will place the view, as it is done before layout happens.)
6693     *
6694     * <p>Note: unlike many View methods, there is no dispatch phase to this
6695     * call.  If you are overriding it in a ViewGroup and want to allow the
6696     * call to continue to your children, you must be sure to call the super
6697     * implementation.
6698     *
6699     * <p>Here is a sample layout that makes use of fitting system windows
6700     * to have controls for a video view placed inside of the window decorations
6701     * that it hides and shows.  This can be used with code like the second
6702     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6703     *
6704     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6705     *
6706     * @param insets Current content insets of the window.  Prior to
6707     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6708     * the insets or else you and Android will be unhappy.
6709     *
6710     * @return {@code true} if this view applied the insets and it should not
6711     * continue propagating further down the hierarchy, {@code false} otherwise.
6712     * @see #getFitsSystemWindows()
6713     * @see #setFitsSystemWindows(boolean)
6714     * @see #setSystemUiVisibility(int)
6715     *
6716     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6717     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6718     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6719     * to implement handling their own insets.
6720     */
6721    protected boolean fitSystemWindows(Rect insets) {
6722        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6723            if (insets == null) {
6724                // Null insets by definition have already been consumed.
6725                // This call cannot apply insets since there are none to apply,
6726                // so return false.
6727                return false;
6728            }
6729            // If we're not in the process of dispatching the newer apply insets call,
6730            // that means we're not in the compatibility path. Dispatch into the newer
6731            // apply insets path and take things from there.
6732            try {
6733                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6734                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6735            } finally {
6736                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6737            }
6738        } else {
6739            // We're being called from the newer apply insets path.
6740            // Perform the standard fallback behavior.
6741            return fitSystemWindowsInt(insets);
6742        }
6743    }
6744
6745    private boolean fitSystemWindowsInt(Rect insets) {
6746        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6747            mUserPaddingStart = UNDEFINED_PADDING;
6748            mUserPaddingEnd = UNDEFINED_PADDING;
6749            Rect localInsets = sThreadLocal.get();
6750            if (localInsets == null) {
6751                localInsets = new Rect();
6752                sThreadLocal.set(localInsets);
6753            }
6754            boolean res = computeFitSystemWindows(insets, localInsets);
6755            mUserPaddingLeftInitial = localInsets.left;
6756            mUserPaddingRightInitial = localInsets.right;
6757            internalSetPadding(localInsets.left, localInsets.top,
6758                    localInsets.right, localInsets.bottom);
6759            return res;
6760        }
6761        return false;
6762    }
6763
6764    /**
6765     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6766     *
6767     * <p>This method should be overridden by views that wish to apply a policy different from or
6768     * in addition to the default behavior. Clients that wish to force a view subtree
6769     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6770     *
6771     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6772     * it will be called during dispatch instead of this method. The listener may optionally
6773     * call this method from its own implementation if it wishes to apply the view's default
6774     * insets policy in addition to its own.</p>
6775     *
6776     * <p>Implementations of this method should either return the insets parameter unchanged
6777     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6778     * that this view applied itself. This allows new inset types added in future platform
6779     * versions to pass through existing implementations unchanged without being erroneously
6780     * consumed.</p>
6781     *
6782     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6783     * property is set then the view will consume the system window insets and apply them
6784     * as padding for the view.</p>
6785     *
6786     * @param insets Insets to apply
6787     * @return The supplied insets with any applied insets consumed
6788     */
6789    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6790        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6791            // We weren't called from within a direct call to fitSystemWindows,
6792            // call into it as a fallback in case we're in a class that overrides it
6793            // and has logic to perform.
6794            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6795                return insets.consumeSystemWindowInsets();
6796            }
6797        } else {
6798            // We were called from within a direct call to fitSystemWindows.
6799            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6800                return insets.consumeSystemWindowInsets();
6801            }
6802        }
6803        return insets;
6804    }
6805
6806    /**
6807     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6808     * window insets to this view. The listener's
6809     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6810     * method will be called instead of the view's
6811     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6812     *
6813     * @param listener Listener to set
6814     *
6815     * @see #onApplyWindowInsets(WindowInsets)
6816     */
6817    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6818        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6819    }
6820
6821    /**
6822     * Request to apply the given window insets to this view or another view in its subtree.
6823     *
6824     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6825     * obscured by window decorations or overlays. This can include the status and navigation bars,
6826     * action bars, input methods and more. New inset categories may be added in the future.
6827     * The method returns the insets provided minus any that were applied by this view or its
6828     * children.</p>
6829     *
6830     * <p>Clients wishing to provide custom behavior should override the
6831     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6832     * {@link OnApplyWindowInsetsListener} via the
6833     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6834     * method.</p>
6835     *
6836     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6837     * </p>
6838     *
6839     * @param insets Insets to apply
6840     * @return The provided insets minus the insets that were consumed
6841     */
6842    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6843        try {
6844            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6845            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6846                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6847            } else {
6848                return onApplyWindowInsets(insets);
6849            }
6850        } finally {
6851            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6852        }
6853    }
6854
6855    /**
6856     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
6857     * only available if the view is attached.
6858     *
6859     * @return WindowInsets from the top of the view hierarchy or null if View is detached
6860     */
6861    public WindowInsets getRootWindowInsets() {
6862        if (mAttachInfo != null) {
6863            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
6864        }
6865        return null;
6866    }
6867
6868    /**
6869     * @hide Compute the insets that should be consumed by this view and the ones
6870     * that should propagate to those under it.
6871     */
6872    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6873        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6874                || mAttachInfo == null
6875                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6876                        && !mAttachInfo.mOverscanRequested)) {
6877            outLocalInsets.set(inoutInsets);
6878            inoutInsets.set(0, 0, 0, 0);
6879            return true;
6880        } else {
6881            // The application wants to take care of fitting system window for
6882            // the content...  however we still need to take care of any overscan here.
6883            final Rect overscan = mAttachInfo.mOverscanInsets;
6884            outLocalInsets.set(overscan);
6885            inoutInsets.left -= overscan.left;
6886            inoutInsets.top -= overscan.top;
6887            inoutInsets.right -= overscan.right;
6888            inoutInsets.bottom -= overscan.bottom;
6889            return false;
6890        }
6891    }
6892
6893    /**
6894     * Compute insets that should be consumed by this view and the ones that should propagate
6895     * to those under it.
6896     *
6897     * @param in Insets currently being processed by this View, likely received as a parameter
6898     *           to {@link #onApplyWindowInsets(WindowInsets)}.
6899     * @param outLocalInsets A Rect that will receive the insets that should be consumed
6900     *                       by this view
6901     * @return Insets that should be passed along to views under this one
6902     */
6903    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
6904        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6905                || mAttachInfo == null
6906                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
6907            outLocalInsets.set(in.getSystemWindowInsets());
6908            return in.consumeSystemWindowInsets();
6909        } else {
6910            outLocalInsets.set(0, 0, 0, 0);
6911            return in;
6912        }
6913    }
6914
6915    /**
6916     * Sets whether or not this view should account for system screen decorations
6917     * such as the status bar and inset its content; that is, controlling whether
6918     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6919     * executed.  See that method for more details.
6920     *
6921     * <p>Note that if you are providing your own implementation of
6922     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6923     * flag to true -- your implementation will be overriding the default
6924     * implementation that checks this flag.
6925     *
6926     * @param fitSystemWindows If true, then the default implementation of
6927     * {@link #fitSystemWindows(Rect)} will be executed.
6928     *
6929     * @attr ref android.R.styleable#View_fitsSystemWindows
6930     * @see #getFitsSystemWindows()
6931     * @see #fitSystemWindows(Rect)
6932     * @see #setSystemUiVisibility(int)
6933     */
6934    public void setFitsSystemWindows(boolean fitSystemWindows) {
6935        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6936    }
6937
6938    /**
6939     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6940     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6941     * will be executed.
6942     *
6943     * @return {@code true} if the default implementation of
6944     * {@link #fitSystemWindows(Rect)} will be executed.
6945     *
6946     * @attr ref android.R.styleable#View_fitsSystemWindows
6947     * @see #setFitsSystemWindows(boolean)
6948     * @see #fitSystemWindows(Rect)
6949     * @see #setSystemUiVisibility(int)
6950     */
6951    @ViewDebug.ExportedProperty
6952    public boolean getFitsSystemWindows() {
6953        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6954    }
6955
6956    /** @hide */
6957    public boolean fitsSystemWindows() {
6958        return getFitsSystemWindows();
6959    }
6960
6961    /**
6962     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6963     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6964     */
6965    public void requestFitSystemWindows() {
6966        if (mParent != null) {
6967            mParent.requestFitSystemWindows();
6968        }
6969    }
6970
6971    /**
6972     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6973     */
6974    public void requestApplyInsets() {
6975        requestFitSystemWindows();
6976    }
6977
6978    /**
6979     * For use by PhoneWindow to make its own system window fitting optional.
6980     * @hide
6981     */
6982    public void makeOptionalFitsSystemWindows() {
6983        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6984    }
6985
6986    /**
6987     * Returns the visibility status for this view.
6988     *
6989     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6990     * @attr ref android.R.styleable#View_visibility
6991     */
6992    @ViewDebug.ExportedProperty(mapping = {
6993        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6994        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6995        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6996    })
6997    @Visibility
6998    public int getVisibility() {
6999        return mViewFlags & VISIBILITY_MASK;
7000    }
7001
7002    /**
7003     * Set the enabled state of this view.
7004     *
7005     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7006     * @attr ref android.R.styleable#View_visibility
7007     */
7008    @RemotableViewMethod
7009    public void setVisibility(@Visibility int visibility) {
7010        setFlags(visibility, VISIBILITY_MASK);
7011    }
7012
7013    /**
7014     * Returns the enabled status for this view. The interpretation of the
7015     * enabled state varies by subclass.
7016     *
7017     * @return True if this view is enabled, false otherwise.
7018     */
7019    @ViewDebug.ExportedProperty
7020    public boolean isEnabled() {
7021        return (mViewFlags & ENABLED_MASK) == ENABLED;
7022    }
7023
7024    /**
7025     * Set the enabled state of this view. The interpretation of the enabled
7026     * state varies by subclass.
7027     *
7028     * @param enabled True if this view is enabled, false otherwise.
7029     */
7030    @RemotableViewMethod
7031    public void setEnabled(boolean enabled) {
7032        if (enabled == isEnabled()) return;
7033
7034        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
7035
7036        /*
7037         * The View most likely has to change its appearance, so refresh
7038         * the drawable state.
7039         */
7040        refreshDrawableState();
7041
7042        // Invalidate too, since the default behavior for views is to be
7043        // be drawn at 50% alpha rather than to change the drawable.
7044        invalidate(true);
7045
7046        if (!enabled) {
7047            cancelPendingInputEvents();
7048        }
7049    }
7050
7051    /**
7052     * Set whether this view can receive the focus.
7053     *
7054     * Setting this to false will also ensure that this view is not focusable
7055     * in touch mode.
7056     *
7057     * @param focusable If true, this view can receive the focus.
7058     *
7059     * @see #setFocusableInTouchMode(boolean)
7060     * @attr ref android.R.styleable#View_focusable
7061     */
7062    public void setFocusable(boolean focusable) {
7063        if (!focusable) {
7064            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
7065        }
7066        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
7067    }
7068
7069    /**
7070     * Set whether this view can receive focus while in touch mode.
7071     *
7072     * Setting this to true will also ensure that this view is focusable.
7073     *
7074     * @param focusableInTouchMode If true, this view can receive the focus while
7075     *   in touch mode.
7076     *
7077     * @see #setFocusable(boolean)
7078     * @attr ref android.R.styleable#View_focusableInTouchMode
7079     */
7080    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
7081        // Focusable in touch mode should always be set before the focusable flag
7082        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
7083        // which, in touch mode, will not successfully request focus on this view
7084        // because the focusable in touch mode flag is not set
7085        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
7086        if (focusableInTouchMode) {
7087            setFlags(FOCUSABLE, FOCUSABLE_MASK);
7088        }
7089    }
7090
7091    /**
7092     * Set whether this view should have sound effects enabled for events such as
7093     * clicking and touching.
7094     *
7095     * <p>You may wish to disable sound effects for a view if you already play sounds,
7096     * for instance, a dial key that plays dtmf tones.
7097     *
7098     * @param soundEffectsEnabled whether sound effects are enabled for this view.
7099     * @see #isSoundEffectsEnabled()
7100     * @see #playSoundEffect(int)
7101     * @attr ref android.R.styleable#View_soundEffectsEnabled
7102     */
7103    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
7104        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
7105    }
7106
7107    /**
7108     * @return whether this view should have sound effects enabled for events such as
7109     *     clicking and touching.
7110     *
7111     * @see #setSoundEffectsEnabled(boolean)
7112     * @see #playSoundEffect(int)
7113     * @attr ref android.R.styleable#View_soundEffectsEnabled
7114     */
7115    @ViewDebug.ExportedProperty
7116    public boolean isSoundEffectsEnabled() {
7117        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
7118    }
7119
7120    /**
7121     * Set whether this view should have haptic feedback for events such as
7122     * long presses.
7123     *
7124     * <p>You may wish to disable haptic feedback if your view already controls
7125     * its own haptic feedback.
7126     *
7127     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
7128     * @see #isHapticFeedbackEnabled()
7129     * @see #performHapticFeedback(int)
7130     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7131     */
7132    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
7133        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
7134    }
7135
7136    /**
7137     * @return whether this view should have haptic feedback enabled for events
7138     * long presses.
7139     *
7140     * @see #setHapticFeedbackEnabled(boolean)
7141     * @see #performHapticFeedback(int)
7142     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7143     */
7144    @ViewDebug.ExportedProperty
7145    public boolean isHapticFeedbackEnabled() {
7146        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
7147    }
7148
7149    /**
7150     * Returns the layout direction for this view.
7151     *
7152     * @return One of {@link #LAYOUT_DIRECTION_LTR},
7153     *   {@link #LAYOUT_DIRECTION_RTL},
7154     *   {@link #LAYOUT_DIRECTION_INHERIT} or
7155     *   {@link #LAYOUT_DIRECTION_LOCALE}.
7156     *
7157     * @attr ref android.R.styleable#View_layoutDirection
7158     *
7159     * @hide
7160     */
7161    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7162        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
7163        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
7164        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
7165        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
7166    })
7167    @LayoutDir
7168    public int getRawLayoutDirection() {
7169        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
7170    }
7171
7172    /**
7173     * Set the layout direction for this view. This will propagate a reset of layout direction
7174     * resolution to the view's children and resolve layout direction for this view.
7175     *
7176     * @param layoutDirection the layout direction to set. Should be one of:
7177     *
7178     * {@link #LAYOUT_DIRECTION_LTR},
7179     * {@link #LAYOUT_DIRECTION_RTL},
7180     * {@link #LAYOUT_DIRECTION_INHERIT},
7181     * {@link #LAYOUT_DIRECTION_LOCALE}.
7182     *
7183     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
7184     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
7185     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
7186     *
7187     * @attr ref android.R.styleable#View_layoutDirection
7188     */
7189    @RemotableViewMethod
7190    public void setLayoutDirection(@LayoutDir int layoutDirection) {
7191        if (getRawLayoutDirection() != layoutDirection) {
7192            // Reset the current layout direction and the resolved one
7193            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
7194            resetRtlProperties();
7195            // Set the new layout direction (filtered)
7196            mPrivateFlags2 |=
7197                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
7198            // We need to resolve all RTL properties as they all depend on layout direction
7199            resolveRtlPropertiesIfNeeded();
7200            requestLayout();
7201            invalidate(true);
7202        }
7203    }
7204
7205    /**
7206     * Returns the resolved layout direction for this view.
7207     *
7208     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
7209     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
7210     *
7211     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
7212     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
7213     *
7214     * @attr ref android.R.styleable#View_layoutDirection
7215     */
7216    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7217        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
7218        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
7219    })
7220    @ResolvedLayoutDir
7221    public int getLayoutDirection() {
7222        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
7223        if (targetSdkVersion < JELLY_BEAN_MR1) {
7224            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
7225            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
7226        }
7227        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
7228                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
7229    }
7230
7231    /**
7232     * Indicates whether or not this view's layout is right-to-left. This is resolved from
7233     * layout attribute and/or the inherited value from the parent
7234     *
7235     * @return true if the layout is right-to-left.
7236     *
7237     * @hide
7238     */
7239    @ViewDebug.ExportedProperty(category = "layout")
7240    public boolean isLayoutRtl() {
7241        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
7242    }
7243
7244    /**
7245     * Indicates whether the view is currently tracking transient state that the
7246     * app should not need to concern itself with saving and restoring, but that
7247     * the framework should take special note to preserve when possible.
7248     *
7249     * <p>A view with transient state cannot be trivially rebound from an external
7250     * data source, such as an adapter binding item views in a list. This may be
7251     * because the view is performing an animation, tracking user selection
7252     * of content, or similar.</p>
7253     *
7254     * @return true if the view has transient state
7255     */
7256    @ViewDebug.ExportedProperty(category = "layout")
7257    public boolean hasTransientState() {
7258        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
7259    }
7260
7261    /**
7262     * Set whether this view is currently tracking transient state that the
7263     * framework should attempt to preserve when possible. This flag is reference counted,
7264     * so every call to setHasTransientState(true) should be paired with a later call
7265     * to setHasTransientState(false).
7266     *
7267     * <p>A view with transient state cannot be trivially rebound from an external
7268     * data source, such as an adapter binding item views in a list. This may be
7269     * because the view is performing an animation, tracking user selection
7270     * of content, or similar.</p>
7271     *
7272     * @param hasTransientState true if this view has transient state
7273     */
7274    public void setHasTransientState(boolean hasTransientState) {
7275        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
7276                mTransientStateCount - 1;
7277        if (mTransientStateCount < 0) {
7278            mTransientStateCount = 0;
7279            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
7280                    "unmatched pair of setHasTransientState calls");
7281        } else if ((hasTransientState && mTransientStateCount == 1) ||
7282                (!hasTransientState && mTransientStateCount == 0)) {
7283            // update flag if we've just incremented up from 0 or decremented down to 0
7284            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
7285                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
7286            if (mParent != null) {
7287                try {
7288                    mParent.childHasTransientStateChanged(this, hasTransientState);
7289                } catch (AbstractMethodError e) {
7290                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7291                            " does not fully implement ViewParent", e);
7292                }
7293            }
7294        }
7295    }
7296
7297    /**
7298     * Returns true if this view is currently attached to a window.
7299     */
7300    public boolean isAttachedToWindow() {
7301        return mAttachInfo != null;
7302    }
7303
7304    /**
7305     * Returns true if this view has been through at least one layout since it
7306     * was last attached to or detached from a window.
7307     */
7308    public boolean isLaidOut() {
7309        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
7310    }
7311
7312    /**
7313     * If this view doesn't do any drawing on its own, set this flag to
7314     * allow further optimizations. By default, this flag is not set on
7315     * View, but could be set on some View subclasses such as ViewGroup.
7316     *
7317     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
7318     * you should clear this flag.
7319     *
7320     * @param willNotDraw whether or not this View draw on its own
7321     */
7322    public void setWillNotDraw(boolean willNotDraw) {
7323        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
7324    }
7325
7326    /**
7327     * Returns whether or not this View draws on its own.
7328     *
7329     * @return true if this view has nothing to draw, false otherwise
7330     */
7331    @ViewDebug.ExportedProperty(category = "drawing")
7332    public boolean willNotDraw() {
7333        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7334    }
7335
7336    /**
7337     * When a View's drawing cache is enabled, drawing is redirected to an
7338     * offscreen bitmap. Some views, like an ImageView, must be able to
7339     * bypass this mechanism if they already draw a single bitmap, to avoid
7340     * unnecessary usage of the memory.
7341     *
7342     * @param willNotCacheDrawing true if this view does not cache its
7343     *        drawing, false otherwise
7344     */
7345    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7346        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7347    }
7348
7349    /**
7350     * Returns whether or not this View can cache its drawing or not.
7351     *
7352     * @return true if this view does not cache its drawing, false otherwise
7353     */
7354    @ViewDebug.ExportedProperty(category = "drawing")
7355    public boolean willNotCacheDrawing() {
7356        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7357    }
7358
7359    /**
7360     * Indicates whether this view reacts to click events or not.
7361     *
7362     * @return true if the view is clickable, false otherwise
7363     *
7364     * @see #setClickable(boolean)
7365     * @attr ref android.R.styleable#View_clickable
7366     */
7367    @ViewDebug.ExportedProperty
7368    public boolean isClickable() {
7369        return (mViewFlags & CLICKABLE) == CLICKABLE;
7370    }
7371
7372    /**
7373     * Enables or disables click events for this view. When a view
7374     * is clickable it will change its state to "pressed" on every click.
7375     * Subclasses should set the view clickable to visually react to
7376     * user's clicks.
7377     *
7378     * @param clickable true to make the view clickable, false otherwise
7379     *
7380     * @see #isClickable()
7381     * @attr ref android.R.styleable#View_clickable
7382     */
7383    public void setClickable(boolean clickable) {
7384        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7385    }
7386
7387    /**
7388     * Indicates whether this view reacts to long click events or not.
7389     *
7390     * @return true if the view is long clickable, false otherwise
7391     *
7392     * @see #setLongClickable(boolean)
7393     * @attr ref android.R.styleable#View_longClickable
7394     */
7395    public boolean isLongClickable() {
7396        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7397    }
7398
7399    /**
7400     * Enables or disables long click events for this view. When a view is long
7401     * clickable it reacts to the user holding down the button for a longer
7402     * duration than a tap. This event can either launch the listener or a
7403     * context menu.
7404     *
7405     * @param longClickable true to make the view long clickable, false otherwise
7406     * @see #isLongClickable()
7407     * @attr ref android.R.styleable#View_longClickable
7408     */
7409    public void setLongClickable(boolean longClickable) {
7410        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7411    }
7412
7413    /**
7414     * Sets the pressed state for this view and provides a touch coordinate for
7415     * animation hinting.
7416     *
7417     * @param pressed Pass true to set the View's internal state to "pressed",
7418     *            or false to reverts the View's internal state from a
7419     *            previously set "pressed" state.
7420     * @param x The x coordinate of the touch that caused the press
7421     * @param y The y coordinate of the touch that caused the press
7422     */
7423    private void setPressed(boolean pressed, float x, float y) {
7424        if (pressed) {
7425            drawableHotspotChanged(x, y);
7426        }
7427
7428        setPressed(pressed);
7429    }
7430
7431    /**
7432     * Sets the pressed state for this view.
7433     *
7434     * @see #isClickable()
7435     * @see #setClickable(boolean)
7436     *
7437     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7438     *        the View's internal state from a previously set "pressed" state.
7439     */
7440    public void setPressed(boolean pressed) {
7441        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7442
7443        if (pressed) {
7444            mPrivateFlags |= PFLAG_PRESSED;
7445        } else {
7446            mPrivateFlags &= ~PFLAG_PRESSED;
7447        }
7448
7449        if (needsRefresh) {
7450            refreshDrawableState();
7451        }
7452        dispatchSetPressed(pressed);
7453    }
7454
7455    /**
7456     * Dispatch setPressed to all of this View's children.
7457     *
7458     * @see #setPressed(boolean)
7459     *
7460     * @param pressed The new pressed state
7461     */
7462    protected void dispatchSetPressed(boolean pressed) {
7463    }
7464
7465    /**
7466     * Indicates whether the view is currently in pressed state. Unless
7467     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7468     * the pressed state.
7469     *
7470     * @see #setPressed(boolean)
7471     * @see #isClickable()
7472     * @see #setClickable(boolean)
7473     *
7474     * @return true if the view is currently pressed, false otherwise
7475     */
7476    @ViewDebug.ExportedProperty
7477    public boolean isPressed() {
7478        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7479    }
7480
7481    /**
7482     * Indicates whether this view will participate in data collection through
7483     * {@link android.view.ViewAssistStructure}.  If true, it will not provide any data
7484     * for itself or its children.  If false, the normal data collection will be allowed.
7485     *
7486     * @return Returns false if assist data collection is not blocked, else true.
7487     *
7488     * @see #setAssistBlocked(boolean)
7489     * @attr ref android.R.styleable#View_assistBlocked
7490     */
7491    public boolean isAssistBlocked() {
7492        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
7493    }
7494
7495    /**
7496     * Controls whether assist data collection from this view and its children is enabled
7497     * (that is, whether {@link #onProvideAssistStructure} and
7498     * {@link #onProvideVirtualAssistStructure} will be called).  The default value is false,
7499     * allowing normal assist collection.  Setting this to false will disable assist collection.
7500     *
7501     * @param enabled Set to true to <em>disable</em> assist data collection, or false
7502     * (the default) to allow it.
7503     *
7504     * @see #isAssistBlocked()
7505     * @see #onProvideAssistStructure
7506     * @see #onProvideVirtualAssistStructure
7507     * @attr ref android.R.styleable#View_assistBlocked
7508     */
7509    public void setAssistBlocked(boolean enabled) {
7510        if (enabled) {
7511            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
7512        } else {
7513            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
7514        }
7515    }
7516
7517    /**
7518     * Indicates whether this view will save its state (that is,
7519     * whether its {@link #onSaveInstanceState} method will be called).
7520     *
7521     * @return Returns true if the view state saving is enabled, else false.
7522     *
7523     * @see #setSaveEnabled(boolean)
7524     * @attr ref android.R.styleable#View_saveEnabled
7525     */
7526    public boolean isSaveEnabled() {
7527        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7528    }
7529
7530    /**
7531     * Controls whether the saving of this view's state is
7532     * enabled (that is, whether its {@link #onSaveInstanceState} method
7533     * will be called).  Note that even if freezing is enabled, the
7534     * view still must have an id assigned to it (via {@link #setId(int)})
7535     * for its state to be saved.  This flag can only disable the
7536     * saving of this view; any child views may still have their state saved.
7537     *
7538     * @param enabled Set to false to <em>disable</em> state saving, or true
7539     * (the default) to allow it.
7540     *
7541     * @see #isSaveEnabled()
7542     * @see #setId(int)
7543     * @see #onSaveInstanceState()
7544     * @attr ref android.R.styleable#View_saveEnabled
7545     */
7546    public void setSaveEnabled(boolean enabled) {
7547        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7548    }
7549
7550    /**
7551     * Gets whether the framework should discard touches when the view's
7552     * window is obscured by another visible window.
7553     * Refer to the {@link View} security documentation for more details.
7554     *
7555     * @return True if touch filtering is enabled.
7556     *
7557     * @see #setFilterTouchesWhenObscured(boolean)
7558     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7559     */
7560    @ViewDebug.ExportedProperty
7561    public boolean getFilterTouchesWhenObscured() {
7562        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7563    }
7564
7565    /**
7566     * Sets whether the framework should discard touches when the view's
7567     * window is obscured by another visible window.
7568     * Refer to the {@link View} security documentation for more details.
7569     *
7570     * @param enabled True if touch filtering should be enabled.
7571     *
7572     * @see #getFilterTouchesWhenObscured
7573     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7574     */
7575    public void setFilterTouchesWhenObscured(boolean enabled) {
7576        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7577                FILTER_TOUCHES_WHEN_OBSCURED);
7578    }
7579
7580    /**
7581     * Indicates whether the entire hierarchy under this view will save its
7582     * state when a state saving traversal occurs from its parent.  The default
7583     * is true; if false, these views will not be saved unless
7584     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7585     *
7586     * @return Returns true if the view state saving from parent is enabled, else false.
7587     *
7588     * @see #setSaveFromParentEnabled(boolean)
7589     */
7590    public boolean isSaveFromParentEnabled() {
7591        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7592    }
7593
7594    /**
7595     * Controls whether the entire hierarchy under this view will save its
7596     * state when a state saving traversal occurs from its parent.  The default
7597     * is true; if false, these views will not be saved unless
7598     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7599     *
7600     * @param enabled Set to false to <em>disable</em> state saving, or true
7601     * (the default) to allow it.
7602     *
7603     * @see #isSaveFromParentEnabled()
7604     * @see #setId(int)
7605     * @see #onSaveInstanceState()
7606     */
7607    public void setSaveFromParentEnabled(boolean enabled) {
7608        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7609    }
7610
7611
7612    /**
7613     * Returns whether this View is able to take focus.
7614     *
7615     * @return True if this view can take focus, or false otherwise.
7616     * @attr ref android.R.styleable#View_focusable
7617     */
7618    @ViewDebug.ExportedProperty(category = "focus")
7619    public final boolean isFocusable() {
7620        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7621    }
7622
7623    /**
7624     * When a view is focusable, it may not want to take focus when in touch mode.
7625     * For example, a button would like focus when the user is navigating via a D-pad
7626     * so that the user can click on it, but once the user starts touching the screen,
7627     * the button shouldn't take focus
7628     * @return Whether the view is focusable in touch mode.
7629     * @attr ref android.R.styleable#View_focusableInTouchMode
7630     */
7631    @ViewDebug.ExportedProperty
7632    public final boolean isFocusableInTouchMode() {
7633        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7634    }
7635
7636    /**
7637     * Find the nearest view in the specified direction that can take focus.
7638     * This does not actually give focus to that view.
7639     *
7640     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7641     *
7642     * @return The nearest focusable in the specified direction, or null if none
7643     *         can be found.
7644     */
7645    public View focusSearch(@FocusRealDirection int direction) {
7646        if (mParent != null) {
7647            return mParent.focusSearch(this, direction);
7648        } else {
7649            return null;
7650        }
7651    }
7652
7653    /**
7654     * This method is the last chance for the focused view and its ancestors to
7655     * respond to an arrow key. This is called when the focused view did not
7656     * consume the key internally, nor could the view system find a new view in
7657     * the requested direction to give focus to.
7658     *
7659     * @param focused The currently focused view.
7660     * @param direction The direction focus wants to move. One of FOCUS_UP,
7661     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7662     * @return True if the this view consumed this unhandled move.
7663     */
7664    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7665        return false;
7666    }
7667
7668    /**
7669     * If a user manually specified the next view id for a particular direction,
7670     * use the root to look up the view.
7671     * @param root The root view of the hierarchy containing this view.
7672     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7673     * or FOCUS_BACKWARD.
7674     * @return The user specified next view, or null if there is none.
7675     */
7676    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7677        switch (direction) {
7678            case FOCUS_LEFT:
7679                if (mNextFocusLeftId == View.NO_ID) return null;
7680                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7681            case FOCUS_RIGHT:
7682                if (mNextFocusRightId == View.NO_ID) return null;
7683                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7684            case FOCUS_UP:
7685                if (mNextFocusUpId == View.NO_ID) return null;
7686                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7687            case FOCUS_DOWN:
7688                if (mNextFocusDownId == View.NO_ID) return null;
7689                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7690            case FOCUS_FORWARD:
7691                if (mNextFocusForwardId == View.NO_ID) return null;
7692                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7693            case FOCUS_BACKWARD: {
7694                if (mID == View.NO_ID) return null;
7695                final int id = mID;
7696                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7697                    @Override
7698                    public boolean apply(View t) {
7699                        return t.mNextFocusForwardId == id;
7700                    }
7701                });
7702            }
7703        }
7704        return null;
7705    }
7706
7707    private View findViewInsideOutShouldExist(View root, int id) {
7708        if (mMatchIdPredicate == null) {
7709            mMatchIdPredicate = new MatchIdPredicate();
7710        }
7711        mMatchIdPredicate.mId = id;
7712        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7713        if (result == null) {
7714            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7715        }
7716        return result;
7717    }
7718
7719    /**
7720     * Find and return all focusable views that are descendants of this view,
7721     * possibly including this view if it is focusable itself.
7722     *
7723     * @param direction The direction of the focus
7724     * @return A list of focusable views
7725     */
7726    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7727        ArrayList<View> result = new ArrayList<View>(24);
7728        addFocusables(result, direction);
7729        return result;
7730    }
7731
7732    /**
7733     * Add any focusable views that are descendants of this view (possibly
7734     * including this view if it is focusable itself) to views.  If we are in touch mode,
7735     * only add views that are also focusable in touch mode.
7736     *
7737     * @param views Focusable views found so far
7738     * @param direction The direction of the focus
7739     */
7740    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7741        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7742    }
7743
7744    /**
7745     * Adds any focusable views that are descendants of this view (possibly
7746     * including this view if it is focusable itself) to views. This method
7747     * adds all focusable views regardless if we are in touch mode or
7748     * only views focusable in touch mode if we are in touch mode or
7749     * only views that can take accessibility focus if accessibility is enabled
7750     * depending on the focusable mode parameter.
7751     *
7752     * @param views Focusable views found so far or null if all we are interested is
7753     *        the number of focusables.
7754     * @param direction The direction of the focus.
7755     * @param focusableMode The type of focusables to be added.
7756     *
7757     * @see #FOCUSABLES_ALL
7758     * @see #FOCUSABLES_TOUCH_MODE
7759     */
7760    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7761            @FocusableMode int focusableMode) {
7762        if (views == null) {
7763            return;
7764        }
7765        if (!isFocusable()) {
7766            return;
7767        }
7768        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7769                && isInTouchMode() && !isFocusableInTouchMode()) {
7770            return;
7771        }
7772        views.add(this);
7773    }
7774
7775    /**
7776     * Finds the Views that contain given text. The containment is case insensitive.
7777     * The search is performed by either the text that the View renders or the content
7778     * description that describes the view for accessibility purposes and the view does
7779     * not render or both. Clients can specify how the search is to be performed via
7780     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7781     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7782     *
7783     * @param outViews The output list of matching Views.
7784     * @param searched The text to match against.
7785     *
7786     * @see #FIND_VIEWS_WITH_TEXT
7787     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7788     * @see #setContentDescription(CharSequence)
7789     */
7790    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7791            @FindViewFlags int flags) {
7792        if (getAccessibilityNodeProvider() != null) {
7793            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7794                outViews.add(this);
7795            }
7796        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7797                && (searched != null && searched.length() > 0)
7798                && (mContentDescription != null && mContentDescription.length() > 0)) {
7799            String searchedLowerCase = searched.toString().toLowerCase();
7800            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7801            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7802                outViews.add(this);
7803            }
7804        }
7805    }
7806
7807    /**
7808     * Find and return all touchable views that are descendants of this view,
7809     * possibly including this view if it is touchable itself.
7810     *
7811     * @return A list of touchable views
7812     */
7813    public ArrayList<View> getTouchables() {
7814        ArrayList<View> result = new ArrayList<View>();
7815        addTouchables(result);
7816        return result;
7817    }
7818
7819    /**
7820     * Add any touchable views that are descendants of this view (possibly
7821     * including this view if it is touchable itself) to views.
7822     *
7823     * @param views Touchable views found so far
7824     */
7825    public void addTouchables(ArrayList<View> views) {
7826        final int viewFlags = mViewFlags;
7827
7828        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7829                && (viewFlags & ENABLED_MASK) == ENABLED) {
7830            views.add(this);
7831        }
7832    }
7833
7834    /**
7835     * Returns whether this View is accessibility focused.
7836     *
7837     * @return True if this View is accessibility focused.
7838     */
7839    public boolean isAccessibilityFocused() {
7840        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7841    }
7842
7843    /**
7844     * Call this to try to give accessibility focus to this view.
7845     *
7846     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7847     * returns false or the view is no visible or the view already has accessibility
7848     * focus.
7849     *
7850     * See also {@link #focusSearch(int)}, which is what you call to say that you
7851     * have focus, and you want your parent to look for the next one.
7852     *
7853     * @return Whether this view actually took accessibility focus.
7854     *
7855     * @hide
7856     */
7857    public boolean requestAccessibilityFocus() {
7858        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7859        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7860            return false;
7861        }
7862        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7863            return false;
7864        }
7865        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7866            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7867            ViewRootImpl viewRootImpl = getViewRootImpl();
7868            if (viewRootImpl != null) {
7869                viewRootImpl.setAccessibilityFocus(this, null);
7870            }
7871            invalidate();
7872            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7873            return true;
7874        }
7875        return false;
7876    }
7877
7878    /**
7879     * Call this to try to clear accessibility focus of this view.
7880     *
7881     * See also {@link #focusSearch(int)}, which is what you call to say that you
7882     * have focus, and you want your parent to look for the next one.
7883     *
7884     * @hide
7885     */
7886    public void clearAccessibilityFocus() {
7887        clearAccessibilityFocusNoCallbacks();
7888        // Clear the global reference of accessibility focus if this
7889        // view or any of its descendants had accessibility focus.
7890        ViewRootImpl viewRootImpl = getViewRootImpl();
7891        if (viewRootImpl != null) {
7892            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7893            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7894                viewRootImpl.setAccessibilityFocus(null, null);
7895            }
7896        }
7897    }
7898
7899    private void sendAccessibilityHoverEvent(int eventType) {
7900        // Since we are not delivering to a client accessibility events from not
7901        // important views (unless the clinet request that) we need to fire the
7902        // event from the deepest view exposed to the client. As a consequence if
7903        // the user crosses a not exposed view the client will see enter and exit
7904        // of the exposed predecessor followed by and enter and exit of that same
7905        // predecessor when entering and exiting the not exposed descendant. This
7906        // is fine since the client has a clear idea which view is hovered at the
7907        // price of a couple more events being sent. This is a simple and
7908        // working solution.
7909        View source = this;
7910        while (true) {
7911            if (source.includeForAccessibility()) {
7912                source.sendAccessibilityEvent(eventType);
7913                return;
7914            }
7915            ViewParent parent = source.getParent();
7916            if (parent instanceof View) {
7917                source = (View) parent;
7918            } else {
7919                return;
7920            }
7921        }
7922    }
7923
7924    /**
7925     * Clears accessibility focus without calling any callback methods
7926     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7927     * is used for clearing accessibility focus when giving this focus to
7928     * another view.
7929     */
7930    void clearAccessibilityFocusNoCallbacks() {
7931        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7932            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7933            invalidate();
7934            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7935        }
7936    }
7937
7938    /**
7939     * Call this to try to give focus to a specific view or to one of its
7940     * descendants.
7941     *
7942     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7943     * false), or if it is focusable and it is not focusable in touch mode
7944     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7945     *
7946     * See also {@link #focusSearch(int)}, which is what you call to say that you
7947     * have focus, and you want your parent to look for the next one.
7948     *
7949     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7950     * {@link #FOCUS_DOWN} and <code>null</code>.
7951     *
7952     * @return Whether this view or one of its descendants actually took focus.
7953     */
7954    public final boolean requestFocus() {
7955        return requestFocus(View.FOCUS_DOWN);
7956    }
7957
7958    /**
7959     * Call this to try to give focus to a specific view or to one of its
7960     * descendants and give it a hint about what direction focus is heading.
7961     *
7962     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7963     * false), or if it is focusable and it is not focusable in touch mode
7964     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7965     *
7966     * See also {@link #focusSearch(int)}, which is what you call to say that you
7967     * have focus, and you want your parent to look for the next one.
7968     *
7969     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7970     * <code>null</code> set for the previously focused rectangle.
7971     *
7972     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7973     * @return Whether this view or one of its descendants actually took focus.
7974     */
7975    public final boolean requestFocus(int direction) {
7976        return requestFocus(direction, null);
7977    }
7978
7979    /**
7980     * Call this to try to give focus to a specific view or to one of its descendants
7981     * and give it hints about the direction and a specific rectangle that the focus
7982     * is coming from.  The rectangle can help give larger views a finer grained hint
7983     * about where focus is coming from, and therefore, where to show selection, or
7984     * forward focus change internally.
7985     *
7986     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7987     * false), or if it is focusable and it is not focusable in touch mode
7988     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7989     *
7990     * A View will not take focus if it is not visible.
7991     *
7992     * A View will not take focus if one of its parents has
7993     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7994     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7995     *
7996     * See also {@link #focusSearch(int)}, which is what you call to say that you
7997     * have focus, and you want your parent to look for the next one.
7998     *
7999     * You may wish to override this method if your custom {@link View} has an internal
8000     * {@link View} that it wishes to forward the request to.
8001     *
8002     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8003     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
8004     *        to give a finer grained hint about where focus is coming from.  May be null
8005     *        if there is no hint.
8006     * @return Whether this view or one of its descendants actually took focus.
8007     */
8008    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
8009        return requestFocusNoSearch(direction, previouslyFocusedRect);
8010    }
8011
8012    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
8013        // need to be focusable
8014        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
8015                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8016            return false;
8017        }
8018
8019        // need to be focusable in touch mode if in touch mode
8020        if (isInTouchMode() &&
8021            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
8022               return false;
8023        }
8024
8025        // need to not have any parents blocking us
8026        if (hasAncestorThatBlocksDescendantFocus()) {
8027            return false;
8028        }
8029
8030        handleFocusGainInternal(direction, previouslyFocusedRect);
8031        return true;
8032    }
8033
8034    /**
8035     * Call this to try to give focus to a specific view or to one of its descendants. This is a
8036     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
8037     * touch mode to request focus when they are touched.
8038     *
8039     * @return Whether this view or one of its descendants actually took focus.
8040     *
8041     * @see #isInTouchMode()
8042     *
8043     */
8044    public final boolean requestFocusFromTouch() {
8045        // Leave touch mode if we need to
8046        if (isInTouchMode()) {
8047            ViewRootImpl viewRoot = getViewRootImpl();
8048            if (viewRoot != null) {
8049                viewRoot.ensureTouchMode(false);
8050            }
8051        }
8052        return requestFocus(View.FOCUS_DOWN);
8053    }
8054
8055    /**
8056     * @return Whether any ancestor of this view blocks descendant focus.
8057     */
8058    private boolean hasAncestorThatBlocksDescendantFocus() {
8059        final boolean focusableInTouchMode = isFocusableInTouchMode();
8060        ViewParent ancestor = mParent;
8061        while (ancestor instanceof ViewGroup) {
8062            final ViewGroup vgAncestor = (ViewGroup) ancestor;
8063            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
8064                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
8065                return true;
8066            } else {
8067                ancestor = vgAncestor.getParent();
8068            }
8069        }
8070        return false;
8071    }
8072
8073    /**
8074     * Gets the mode for determining whether this View is important for accessibility
8075     * which is if it fires accessibility events and if it is reported to
8076     * accessibility services that query the screen.
8077     *
8078     * @return The mode for determining whether a View is important for accessibility.
8079     *
8080     * @attr ref android.R.styleable#View_importantForAccessibility
8081     *
8082     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8083     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8084     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8085     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8086     */
8087    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
8088            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
8089            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
8090            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
8091            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
8092                    to = "noHideDescendants")
8093        })
8094    public int getImportantForAccessibility() {
8095        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8096                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8097    }
8098
8099    /**
8100     * Sets the live region mode for this view. This indicates to accessibility
8101     * services whether they should automatically notify the user about changes
8102     * to the view's content description or text, or to the content descriptions
8103     * or text of the view's children (where applicable).
8104     * <p>
8105     * For example, in a login screen with a TextView that displays an "incorrect
8106     * password" notification, that view should be marked as a live region with
8107     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8108     * <p>
8109     * To disable change notifications for this view, use
8110     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
8111     * mode for most views.
8112     * <p>
8113     * To indicate that the user should be notified of changes, use
8114     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8115     * <p>
8116     * If the view's changes should interrupt ongoing speech and notify the user
8117     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
8118     *
8119     * @param mode The live region mode for this view, one of:
8120     *        <ul>
8121     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
8122     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
8123     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
8124     *        </ul>
8125     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8126     */
8127    public void setAccessibilityLiveRegion(int mode) {
8128        if (mode != getAccessibilityLiveRegion()) {
8129            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8130            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
8131                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8132            notifyViewAccessibilityStateChangedIfNeeded(
8133                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8134        }
8135    }
8136
8137    /**
8138     * Gets the live region mode for this View.
8139     *
8140     * @return The live region mode for the view.
8141     *
8142     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8143     *
8144     * @see #setAccessibilityLiveRegion(int)
8145     */
8146    public int getAccessibilityLiveRegion() {
8147        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
8148                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
8149    }
8150
8151    /**
8152     * Sets how to determine whether this view is important for accessibility
8153     * which is if it fires accessibility events and if it is reported to
8154     * accessibility services that query the screen.
8155     *
8156     * @param mode How to determine whether this view is important for accessibility.
8157     *
8158     * @attr ref android.R.styleable#View_importantForAccessibility
8159     *
8160     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8161     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8162     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8163     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8164     */
8165    public void setImportantForAccessibility(int mode) {
8166        final int oldMode = getImportantForAccessibility();
8167        if (mode != oldMode) {
8168            // If we're moving between AUTO and another state, we might not need
8169            // to send a subtree changed notification. We'll store the computed
8170            // importance, since we'll need to check it later to make sure.
8171            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
8172                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
8173            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
8174            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8175            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
8176                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8177            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
8178                notifySubtreeAccessibilityStateChangedIfNeeded();
8179            } else {
8180                notifyViewAccessibilityStateChangedIfNeeded(
8181                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8182            }
8183        }
8184    }
8185
8186    /**
8187     * Computes whether this view should be exposed for accessibility. In
8188     * general, views that are interactive or provide information are exposed
8189     * while views that serve only as containers are hidden.
8190     * <p>
8191     * If an ancestor of this view has importance
8192     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
8193     * returns <code>false</code>.
8194     * <p>
8195     * Otherwise, the value is computed according to the view's
8196     * {@link #getImportantForAccessibility()} value:
8197     * <ol>
8198     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
8199     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
8200     * </code>
8201     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
8202     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
8203     * view satisfies any of the following:
8204     * <ul>
8205     * <li>Is actionable, e.g. {@link #isClickable()},
8206     * {@link #isLongClickable()}, or {@link #isFocusable()}
8207     * <li>Has an {@link AccessibilityDelegate}
8208     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
8209     * {@link OnKeyListener}, etc.
8210     * <li>Is an accessibility live region, e.g.
8211     * {@link #getAccessibilityLiveRegion()} is not
8212     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
8213     * </ul>
8214     * </ol>
8215     *
8216     * @return Whether the view is exposed for accessibility.
8217     * @see #setImportantForAccessibility(int)
8218     * @see #getImportantForAccessibility()
8219     */
8220    public boolean isImportantForAccessibility() {
8221        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8222                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8223        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
8224                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8225            return false;
8226        }
8227
8228        // Check parent mode to ensure we're not hidden.
8229        ViewParent parent = mParent;
8230        while (parent instanceof View) {
8231            if (((View) parent).getImportantForAccessibility()
8232                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8233                return false;
8234            }
8235            parent = parent.getParent();
8236        }
8237
8238        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
8239                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
8240                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
8241    }
8242
8243    /**
8244     * Gets the parent for accessibility purposes. Note that the parent for
8245     * accessibility is not necessary the immediate parent. It is the first
8246     * predecessor that is important for accessibility.
8247     *
8248     * @return The parent for accessibility purposes.
8249     */
8250    public ViewParent getParentForAccessibility() {
8251        if (mParent instanceof View) {
8252            View parentView = (View) mParent;
8253            if (parentView.includeForAccessibility()) {
8254                return mParent;
8255            } else {
8256                return mParent.getParentForAccessibility();
8257            }
8258        }
8259        return null;
8260    }
8261
8262    /**
8263     * Adds the children of a given View for accessibility. Since some Views are
8264     * not important for accessibility the children for accessibility are not
8265     * necessarily direct children of the view, rather they are the first level of
8266     * descendants important for accessibility.
8267     *
8268     * @param children The list of children for accessibility.
8269     */
8270    public void addChildrenForAccessibility(ArrayList<View> children) {
8271
8272    }
8273
8274    /**
8275     * Whether to regard this view for accessibility. A view is regarded for
8276     * accessibility if it is important for accessibility or the querying
8277     * accessibility service has explicitly requested that view not
8278     * important for accessibility are regarded.
8279     *
8280     * @return Whether to regard the view for accessibility.
8281     *
8282     * @hide
8283     */
8284    public boolean includeForAccessibility() {
8285        if (mAttachInfo != null) {
8286            return (mAttachInfo.mAccessibilityFetchFlags
8287                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
8288                    || isImportantForAccessibility();
8289        }
8290        return false;
8291    }
8292
8293    /**
8294     * Returns whether the View is considered actionable from
8295     * accessibility perspective. Such view are important for
8296     * accessibility.
8297     *
8298     * @return True if the view is actionable for accessibility.
8299     *
8300     * @hide
8301     */
8302    public boolean isActionableForAccessibility() {
8303        return (isClickable() || isLongClickable() || isFocusable());
8304    }
8305
8306    /**
8307     * Returns whether the View has registered callbacks which makes it
8308     * important for accessibility.
8309     *
8310     * @return True if the view is actionable for accessibility.
8311     */
8312    private boolean hasListenersForAccessibility() {
8313        ListenerInfo info = getListenerInfo();
8314        return mTouchDelegate != null || info.mOnKeyListener != null
8315                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
8316                || info.mOnHoverListener != null || info.mOnDragListener != null;
8317    }
8318
8319    /**
8320     * Notifies that the accessibility state of this view changed. The change
8321     * is local to this view and does not represent structural changes such
8322     * as children and parent. For example, the view became focusable. The
8323     * notification is at at most once every
8324     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8325     * to avoid unnecessary load to the system. Also once a view has a pending
8326     * notification this method is a NOP until the notification has been sent.
8327     *
8328     * @hide
8329     */
8330    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
8331        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8332            return;
8333        }
8334        if (mSendViewStateChangedAccessibilityEvent == null) {
8335            mSendViewStateChangedAccessibilityEvent =
8336                    new SendViewStateChangedAccessibilityEvent();
8337        }
8338        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
8339    }
8340
8341    /**
8342     * Notifies that the accessibility state of this view changed. The change
8343     * is *not* local to this view and does represent structural changes such
8344     * as children and parent. For example, the view size changed. The
8345     * notification is at at most once every
8346     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8347     * to avoid unnecessary load to the system. Also once a view has a pending
8348     * notification this method is a NOP until the notification has been sent.
8349     *
8350     * @hide
8351     */
8352    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
8353        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8354            return;
8355        }
8356        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
8357            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8358            if (mParent != null) {
8359                try {
8360                    mParent.notifySubtreeAccessibilityStateChanged(
8361                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
8362                } catch (AbstractMethodError e) {
8363                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8364                            " does not fully implement ViewParent", e);
8365                }
8366            }
8367        }
8368    }
8369
8370    /**
8371     * Reset the flag indicating the accessibility state of the subtree rooted
8372     * at this view changed.
8373     */
8374    void resetSubtreeAccessibilityStateChanged() {
8375        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8376    }
8377
8378    /**
8379     * Report an accessibility action to this view's parents for delegated processing.
8380     *
8381     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
8382     * call this method to delegate an accessibility action to a supporting parent. If the parent
8383     * returns true from its
8384     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
8385     * method this method will return true to signify that the action was consumed.</p>
8386     *
8387     * <p>This method is useful for implementing nested scrolling child views. If
8388     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
8389     * a custom view implementation may invoke this method to allow a parent to consume the
8390     * scroll first. If this method returns true the custom view should skip its own scrolling
8391     * behavior.</p>
8392     *
8393     * @param action Accessibility action to delegate
8394     * @param arguments Optional action arguments
8395     * @return true if the action was consumed by a parent
8396     */
8397    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
8398        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
8399            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
8400                return true;
8401            }
8402        }
8403        return false;
8404    }
8405
8406    /**
8407     * Performs the specified accessibility action on the view. For
8408     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8409     * <p>
8410     * If an {@link AccessibilityDelegate} has been specified via calling
8411     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8412     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8413     * is responsible for handling this call.
8414     * </p>
8415     *
8416     * <p>The default implementation will delegate
8417     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
8418     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
8419     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
8420     *
8421     * @param action The action to perform.
8422     * @param arguments Optional action arguments.
8423     * @return Whether the action was performed.
8424     */
8425    public boolean performAccessibilityAction(int action, Bundle arguments) {
8426      if (mAccessibilityDelegate != null) {
8427          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8428      } else {
8429          return performAccessibilityActionInternal(action, arguments);
8430      }
8431    }
8432
8433   /**
8434    * @see #performAccessibilityAction(int, Bundle)
8435    *
8436    * Note: Called from the default {@link AccessibilityDelegate}.
8437    *
8438    * @hide
8439    */
8440    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8441        if (isNestedScrollingEnabled()
8442                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
8443                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
8444                || action == R.id.accessibilityActionScrollUp
8445                || action == R.id.accessibilityActionScrollLeft
8446                || action == R.id.accessibilityActionScrollDown
8447                || action == R.id.accessibilityActionScrollRight)) {
8448            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
8449                return true;
8450            }
8451        }
8452
8453        switch (action) {
8454            case AccessibilityNodeInfo.ACTION_CLICK: {
8455                if (isClickable()) {
8456                    performClick();
8457                    return true;
8458                }
8459            } break;
8460            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8461                if (isLongClickable()) {
8462                    performLongClick();
8463                    return true;
8464                }
8465            } break;
8466            case AccessibilityNodeInfo.ACTION_FOCUS: {
8467                if (!hasFocus()) {
8468                    // Get out of touch mode since accessibility
8469                    // wants to move focus around.
8470                    getViewRootImpl().ensureTouchMode(false);
8471                    return requestFocus();
8472                }
8473            } break;
8474            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8475                if (hasFocus()) {
8476                    clearFocus();
8477                    return !isFocused();
8478                }
8479            } break;
8480            case AccessibilityNodeInfo.ACTION_SELECT: {
8481                if (!isSelected()) {
8482                    setSelected(true);
8483                    return isSelected();
8484                }
8485            } break;
8486            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8487                if (isSelected()) {
8488                    setSelected(false);
8489                    return !isSelected();
8490                }
8491            } break;
8492            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8493                if (!isAccessibilityFocused()) {
8494                    return requestAccessibilityFocus();
8495                }
8496            } break;
8497            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8498                if (isAccessibilityFocused()) {
8499                    clearAccessibilityFocus();
8500                    return true;
8501                }
8502            } break;
8503            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8504                if (arguments != null) {
8505                    final int granularity = arguments.getInt(
8506                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8507                    final boolean extendSelection = arguments.getBoolean(
8508                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8509                    return traverseAtGranularity(granularity, true, extendSelection);
8510                }
8511            } break;
8512            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8513                if (arguments != null) {
8514                    final int granularity = arguments.getInt(
8515                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8516                    final boolean extendSelection = arguments.getBoolean(
8517                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8518                    return traverseAtGranularity(granularity, false, extendSelection);
8519                }
8520            } break;
8521            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8522                CharSequence text = getIterableTextForAccessibility();
8523                if (text == null) {
8524                    return false;
8525                }
8526                final int start = (arguments != null) ? arguments.getInt(
8527                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8528                final int end = (arguments != null) ? arguments.getInt(
8529                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8530                // Only cursor position can be specified (selection length == 0)
8531                if ((getAccessibilitySelectionStart() != start
8532                        || getAccessibilitySelectionEnd() != end)
8533                        && (start == end)) {
8534                    setAccessibilitySelection(start, end);
8535                    notifyViewAccessibilityStateChangedIfNeeded(
8536                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8537                    return true;
8538                }
8539            } break;
8540            case R.id.accessibilityActionShowOnScreen: {
8541                if (mAttachInfo != null) {
8542                    final Rect r = mAttachInfo.mTmpInvalRect;
8543                    getDrawingRect(r);
8544                    return requestRectangleOnScreen(r, true);
8545                }
8546            } break;
8547        }
8548        return false;
8549    }
8550
8551    private boolean traverseAtGranularity(int granularity, boolean forward,
8552            boolean extendSelection) {
8553        CharSequence text = getIterableTextForAccessibility();
8554        if (text == null || text.length() == 0) {
8555            return false;
8556        }
8557        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
8558        if (iterator == null) {
8559            return false;
8560        }
8561        int current = getAccessibilitySelectionEnd();
8562        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8563            current = forward ? 0 : text.length();
8564        }
8565        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
8566        if (range == null) {
8567            return false;
8568        }
8569        final int segmentStart = range[0];
8570        final int segmentEnd = range[1];
8571        int selectionStart;
8572        int selectionEnd;
8573        if (extendSelection && isAccessibilitySelectionExtendable()) {
8574            selectionStart = getAccessibilitySelectionStart();
8575            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8576                selectionStart = forward ? segmentStart : segmentEnd;
8577            }
8578            selectionEnd = forward ? segmentEnd : segmentStart;
8579        } else {
8580            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
8581        }
8582        setAccessibilitySelection(selectionStart, selectionEnd);
8583        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
8584                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
8585        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
8586        return true;
8587    }
8588
8589    /**
8590     * Gets the text reported for accessibility purposes.
8591     *
8592     * @return The accessibility text.
8593     *
8594     * @hide
8595     */
8596    public CharSequence getIterableTextForAccessibility() {
8597        return getContentDescription();
8598    }
8599
8600    /**
8601     * Gets whether accessibility selection can be extended.
8602     *
8603     * @return If selection is extensible.
8604     *
8605     * @hide
8606     */
8607    public boolean isAccessibilitySelectionExtendable() {
8608        return false;
8609    }
8610
8611    /**
8612     * @hide
8613     */
8614    public int getAccessibilitySelectionStart() {
8615        return mAccessibilityCursorPosition;
8616    }
8617
8618    /**
8619     * @hide
8620     */
8621    public int getAccessibilitySelectionEnd() {
8622        return getAccessibilitySelectionStart();
8623    }
8624
8625    /**
8626     * @hide
8627     */
8628    public void setAccessibilitySelection(int start, int end) {
8629        if (start ==  end && end == mAccessibilityCursorPosition) {
8630            return;
8631        }
8632        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8633            mAccessibilityCursorPosition = start;
8634        } else {
8635            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8636        }
8637        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8638    }
8639
8640    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8641            int fromIndex, int toIndex) {
8642        if (mParent == null) {
8643            return;
8644        }
8645        AccessibilityEvent event = AccessibilityEvent.obtain(
8646                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8647        onInitializeAccessibilityEvent(event);
8648        onPopulateAccessibilityEvent(event);
8649        event.setFromIndex(fromIndex);
8650        event.setToIndex(toIndex);
8651        event.setAction(action);
8652        event.setMovementGranularity(granularity);
8653        mParent.requestSendAccessibilityEvent(this, event);
8654    }
8655
8656    /**
8657     * @hide
8658     */
8659    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8660        switch (granularity) {
8661            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8662                CharSequence text = getIterableTextForAccessibility();
8663                if (text != null && text.length() > 0) {
8664                    CharacterTextSegmentIterator iterator =
8665                        CharacterTextSegmentIterator.getInstance(
8666                                mContext.getResources().getConfiguration().locale);
8667                    iterator.initialize(text.toString());
8668                    return iterator;
8669                }
8670            } break;
8671            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8672                CharSequence text = getIterableTextForAccessibility();
8673                if (text != null && text.length() > 0) {
8674                    WordTextSegmentIterator iterator =
8675                        WordTextSegmentIterator.getInstance(
8676                                mContext.getResources().getConfiguration().locale);
8677                    iterator.initialize(text.toString());
8678                    return iterator;
8679                }
8680            } break;
8681            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8682                CharSequence text = getIterableTextForAccessibility();
8683                if (text != null && text.length() > 0) {
8684                    ParagraphTextSegmentIterator iterator =
8685                        ParagraphTextSegmentIterator.getInstance();
8686                    iterator.initialize(text.toString());
8687                    return iterator;
8688                }
8689            } break;
8690        }
8691        return null;
8692    }
8693
8694    /**
8695     * @hide
8696     */
8697    public void dispatchStartTemporaryDetach() {
8698        onStartTemporaryDetach();
8699    }
8700
8701    /**
8702     * This is called when a container is going to temporarily detach a child, with
8703     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8704     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8705     * {@link #onDetachedFromWindow()} when the container is done.
8706     */
8707    public void onStartTemporaryDetach() {
8708        removeUnsetPressCallback();
8709        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8710    }
8711
8712    /**
8713     * @hide
8714     */
8715    public void dispatchFinishTemporaryDetach() {
8716        onFinishTemporaryDetach();
8717    }
8718
8719    /**
8720     * Called after {@link #onStartTemporaryDetach} when the container is done
8721     * changing the view.
8722     */
8723    public void onFinishTemporaryDetach() {
8724    }
8725
8726    /**
8727     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8728     * for this view's window.  Returns null if the view is not currently attached
8729     * to the window.  Normally you will not need to use this directly, but
8730     * just use the standard high-level event callbacks like
8731     * {@link #onKeyDown(int, KeyEvent)}.
8732     */
8733    public KeyEvent.DispatcherState getKeyDispatcherState() {
8734        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8735    }
8736
8737    /**
8738     * Dispatch a key event before it is processed by any input method
8739     * associated with the view hierarchy.  This can be used to intercept
8740     * key events in special situations before the IME consumes them; a
8741     * typical example would be handling the BACK key to update the application's
8742     * UI instead of allowing the IME to see it and close itself.
8743     *
8744     * @param event The key event to be dispatched.
8745     * @return True if the event was handled, false otherwise.
8746     */
8747    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8748        return onKeyPreIme(event.getKeyCode(), event);
8749    }
8750
8751    /**
8752     * Dispatch a key event to the next view on the focus path. This path runs
8753     * from the top of the view tree down to the currently focused view. If this
8754     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8755     * the next node down the focus path. This method also fires any key
8756     * listeners.
8757     *
8758     * @param event The key event to be dispatched.
8759     * @return True if the event was handled, false otherwise.
8760     */
8761    public boolean dispatchKeyEvent(KeyEvent event) {
8762        if (mInputEventConsistencyVerifier != null) {
8763            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8764        }
8765
8766        // Give any attached key listener a first crack at the event.
8767        //noinspection SimplifiableIfStatement
8768        ListenerInfo li = mListenerInfo;
8769        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8770                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8771            return true;
8772        }
8773
8774        if (event.dispatch(this, mAttachInfo != null
8775                ? mAttachInfo.mKeyDispatchState : null, this)) {
8776            return true;
8777        }
8778
8779        if (mInputEventConsistencyVerifier != null) {
8780            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8781        }
8782        return false;
8783    }
8784
8785    /**
8786     * Dispatches a key shortcut event.
8787     *
8788     * @param event The key event to be dispatched.
8789     * @return True if the event was handled by the view, false otherwise.
8790     */
8791    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8792        return onKeyShortcut(event.getKeyCode(), event);
8793    }
8794
8795    /**
8796     * Pass the touch screen motion event down to the target view, or this
8797     * view if it is the target.
8798     *
8799     * @param event The motion event to be dispatched.
8800     * @return True if the event was handled by the view, false otherwise.
8801     */
8802    public boolean dispatchTouchEvent(MotionEvent event) {
8803        // If the event should be handled by accessibility focus first.
8804        if (event.isTargetAccessibilityFocus()) {
8805            // We don't have focus or no virtual descendant has it, do not handle the event.
8806            if (!isAccessibilityFocusedViewOrHost()) {
8807                return false;
8808            }
8809            // We have focus and got the event, then use normal event dispatch.
8810            event.setTargetAccessibilityFocus(false);
8811        }
8812
8813        boolean result = false;
8814
8815        if (mInputEventConsistencyVerifier != null) {
8816            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8817        }
8818
8819        final int actionMasked = event.getActionMasked();
8820        if (actionMasked == MotionEvent.ACTION_DOWN) {
8821            // Defensive cleanup for new gesture
8822            stopNestedScroll();
8823        }
8824
8825        if (onFilterTouchEventForSecurity(event)) {
8826            //noinspection SimplifiableIfStatement
8827            ListenerInfo li = mListenerInfo;
8828            if (li != null && li.mOnTouchListener != null
8829                    && (mViewFlags & ENABLED_MASK) == ENABLED
8830                    && li.mOnTouchListener.onTouch(this, event)) {
8831                result = true;
8832            }
8833
8834            if (!result && onTouchEvent(event)) {
8835                result = true;
8836            }
8837        }
8838
8839        if (!result && mInputEventConsistencyVerifier != null) {
8840            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8841        }
8842
8843        // Clean up after nested scrolls if this is the end of a gesture;
8844        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8845        // of the gesture.
8846        if (actionMasked == MotionEvent.ACTION_UP ||
8847                actionMasked == MotionEvent.ACTION_CANCEL ||
8848                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8849            stopNestedScroll();
8850        }
8851
8852        return result;
8853    }
8854
8855    boolean isAccessibilityFocusedViewOrHost() {
8856        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
8857                .getAccessibilityFocusedHost() == this);
8858    }
8859
8860    /**
8861     * Filter the touch event to apply security policies.
8862     *
8863     * @param event The motion event to be filtered.
8864     * @return True if the event should be dispatched, false if the event should be dropped.
8865     *
8866     * @see #getFilterTouchesWhenObscured
8867     */
8868    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8869        //noinspection RedundantIfStatement
8870        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8871                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8872            // Window is obscured, drop this touch.
8873            return false;
8874        }
8875        return true;
8876    }
8877
8878    /**
8879     * Pass a trackball motion event down to the focused view.
8880     *
8881     * @param event The motion event to be dispatched.
8882     * @return True if the event was handled by the view, false otherwise.
8883     */
8884    public boolean dispatchTrackballEvent(MotionEvent event) {
8885        if (mInputEventConsistencyVerifier != null) {
8886            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8887        }
8888
8889        return onTrackballEvent(event);
8890    }
8891
8892    /**
8893     * Dispatch a generic motion event.
8894     * <p>
8895     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8896     * are delivered to the view under the pointer.  All other generic motion events are
8897     * delivered to the focused view.  Hover events are handled specially and are delivered
8898     * to {@link #onHoverEvent(MotionEvent)}.
8899     * </p>
8900     *
8901     * @param event The motion event to be dispatched.
8902     * @return True if the event was handled by the view, false otherwise.
8903     */
8904    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8905        if (mInputEventConsistencyVerifier != null) {
8906            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8907        }
8908
8909        final int source = event.getSource();
8910        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8911            final int action = event.getAction();
8912            if (action == MotionEvent.ACTION_HOVER_ENTER
8913                    || action == MotionEvent.ACTION_HOVER_MOVE
8914                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8915                if (dispatchHoverEvent(event)) {
8916                    return true;
8917                }
8918            } else if (dispatchGenericPointerEvent(event)) {
8919                return true;
8920            }
8921        } else if (dispatchGenericFocusedEvent(event)) {
8922            return true;
8923        }
8924
8925        if (dispatchGenericMotionEventInternal(event)) {
8926            return true;
8927        }
8928
8929        if (mInputEventConsistencyVerifier != null) {
8930            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8931        }
8932        return false;
8933    }
8934
8935    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8936        //noinspection SimplifiableIfStatement
8937        ListenerInfo li = mListenerInfo;
8938        if (li != null && li.mOnGenericMotionListener != null
8939                && (mViewFlags & ENABLED_MASK) == ENABLED
8940                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8941            return true;
8942        }
8943
8944        if (onGenericMotionEvent(event)) {
8945            return true;
8946        }
8947
8948        if (mInputEventConsistencyVerifier != null) {
8949            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8950        }
8951        return false;
8952    }
8953
8954    /**
8955     * Dispatch a hover event.
8956     * <p>
8957     * Do not call this method directly.
8958     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8959     * </p>
8960     *
8961     * @param event The motion event to be dispatched.
8962     * @return True if the event was handled by the view, false otherwise.
8963     */
8964    protected boolean dispatchHoverEvent(MotionEvent event) {
8965        ListenerInfo li = mListenerInfo;
8966        //noinspection SimplifiableIfStatement
8967        if (li != null && li.mOnHoverListener != null
8968                && (mViewFlags & ENABLED_MASK) == ENABLED
8969                && li.mOnHoverListener.onHover(this, event)) {
8970            return true;
8971        }
8972
8973        return onHoverEvent(event);
8974    }
8975
8976    /**
8977     * Returns true if the view has a child to which it has recently sent
8978     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8979     * it does not have a hovered child, then it must be the innermost hovered view.
8980     * @hide
8981     */
8982    protected boolean hasHoveredChild() {
8983        return false;
8984    }
8985
8986    /**
8987     * Dispatch a generic motion event to the view under the first pointer.
8988     * <p>
8989     * Do not call this method directly.
8990     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8991     * </p>
8992     *
8993     * @param event The motion event to be dispatched.
8994     * @return True if the event was handled by the view, false otherwise.
8995     */
8996    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8997        return false;
8998    }
8999
9000    /**
9001     * Dispatch a generic motion event to the currently focused view.
9002     * <p>
9003     * Do not call this method directly.
9004     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9005     * </p>
9006     *
9007     * @param event The motion event to be dispatched.
9008     * @return True if the event was handled by the view, false otherwise.
9009     */
9010    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
9011        return false;
9012    }
9013
9014    /**
9015     * Dispatch a pointer event.
9016     * <p>
9017     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
9018     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
9019     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
9020     * and should not be expected to handle other pointing device features.
9021     * </p>
9022     *
9023     * @param event The motion event to be dispatched.
9024     * @return True if the event was handled by the view, false otherwise.
9025     * @hide
9026     */
9027    public final boolean dispatchPointerEvent(MotionEvent event) {
9028        if (event.isTouchEvent()) {
9029            return dispatchTouchEvent(event);
9030        } else {
9031            return dispatchGenericMotionEvent(event);
9032        }
9033    }
9034
9035    /**
9036     * Called when the window containing this view gains or loses window focus.
9037     * ViewGroups should override to route to their children.
9038     *
9039     * @param hasFocus True if the window containing this view now has focus,
9040     *        false otherwise.
9041     */
9042    public void dispatchWindowFocusChanged(boolean hasFocus) {
9043        onWindowFocusChanged(hasFocus);
9044    }
9045
9046    /**
9047     * Called when the window containing this view gains or loses focus.  Note
9048     * that this is separate from view focus: to receive key events, both
9049     * your view and its window must have focus.  If a window is displayed
9050     * on top of yours that takes input focus, then your own window will lose
9051     * focus but the view focus will remain unchanged.
9052     *
9053     * @param hasWindowFocus True if the window containing this view now has
9054     *        focus, false otherwise.
9055     */
9056    public void onWindowFocusChanged(boolean hasWindowFocus) {
9057        InputMethodManager imm = InputMethodManager.peekInstance();
9058        if (!hasWindowFocus) {
9059            if (isPressed()) {
9060                setPressed(false);
9061            }
9062            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9063                imm.focusOut(this);
9064            }
9065            removeLongPressCallback();
9066            removeTapCallback();
9067            onFocusLost();
9068        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9069            imm.focusIn(this);
9070        }
9071        refreshDrawableState();
9072    }
9073
9074    /**
9075     * Returns true if this view is in a window that currently has window focus.
9076     * Note that this is not the same as the view itself having focus.
9077     *
9078     * @return True if this view is in a window that currently has window focus.
9079     */
9080    public boolean hasWindowFocus() {
9081        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
9082    }
9083
9084    /**
9085     * Dispatch a view visibility change down the view hierarchy.
9086     * ViewGroups should override to route to their children.
9087     * @param changedView The view whose visibility changed. Could be 'this' or
9088     * an ancestor view.
9089     * @param visibility The new visibility of changedView: {@link #VISIBLE},
9090     * {@link #INVISIBLE} or {@link #GONE}.
9091     */
9092    protected void dispatchVisibilityChanged(@NonNull View changedView,
9093            @Visibility int visibility) {
9094        onVisibilityChanged(changedView, visibility);
9095    }
9096
9097    /**
9098     * Called when the visibility of the view or an ancestor of the view has
9099     * changed.
9100     *
9101     * @param changedView The view whose visibility changed. May be
9102     *                    {@code this} or an ancestor view.
9103     * @param visibility The new visibility, one of {@link #VISIBLE},
9104     *                   {@link #INVISIBLE} or {@link #GONE}.
9105     */
9106    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
9107        final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE;
9108        if (visible) {
9109            if (mAttachInfo != null) {
9110                initialAwakenScrollBars();
9111            } else {
9112                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
9113            }
9114        }
9115
9116        final Drawable dr = mBackground;
9117        if (dr != null && visible != dr.isVisible()) {
9118            dr.setVisible(visible, false);
9119        }
9120        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
9121        if (fg != null && visible != fg.isVisible()) {
9122            fg.setVisible(visible, false);
9123        }
9124    }
9125
9126    /**
9127     * Dispatch a hint about whether this view is displayed. For instance, when
9128     * a View moves out of the screen, it might receives a display hint indicating
9129     * the view is not displayed. Applications should not <em>rely</em> on this hint
9130     * as there is no guarantee that they will receive one.
9131     *
9132     * @param hint A hint about whether or not this view is displayed:
9133     * {@link #VISIBLE} or {@link #INVISIBLE}.
9134     */
9135    public void dispatchDisplayHint(@Visibility int hint) {
9136        onDisplayHint(hint);
9137    }
9138
9139    /**
9140     * Gives this view a hint about whether is displayed or not. For instance, when
9141     * a View moves out of the screen, it might receives a display hint indicating
9142     * the view is not displayed. Applications should not <em>rely</em> on this hint
9143     * as there is no guarantee that they will receive one.
9144     *
9145     * @param hint A hint about whether or not this view is displayed:
9146     * {@link #VISIBLE} or {@link #INVISIBLE}.
9147     */
9148    protected void onDisplayHint(@Visibility int hint) {
9149    }
9150
9151    /**
9152     * Dispatch a window visibility change down the view hierarchy.
9153     * ViewGroups should override to route to their children.
9154     *
9155     * @param visibility The new visibility of the window.
9156     *
9157     * @see #onWindowVisibilityChanged(int)
9158     */
9159    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
9160        onWindowVisibilityChanged(visibility);
9161    }
9162
9163    /**
9164     * Called when the window containing has change its visibility
9165     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
9166     * that this tells you whether or not your window is being made visible
9167     * to the window manager; this does <em>not</em> tell you whether or not
9168     * your window is obscured by other windows on the screen, even if it
9169     * is itself visible.
9170     *
9171     * @param visibility The new visibility of the window.
9172     */
9173    protected void onWindowVisibilityChanged(@Visibility int visibility) {
9174        if (visibility == VISIBLE) {
9175            initialAwakenScrollBars();
9176        }
9177    }
9178
9179    /**
9180     * Returns the current visibility of the window this view is attached to
9181     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
9182     *
9183     * @return Returns the current visibility of the view's window.
9184     */
9185    @Visibility
9186    public int getWindowVisibility() {
9187        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
9188    }
9189
9190    /**
9191     * Retrieve the overall visible display size in which the window this view is
9192     * attached to has been positioned in.  This takes into account screen
9193     * decorations above the window, for both cases where the window itself
9194     * is being position inside of them or the window is being placed under
9195     * then and covered insets are used for the window to position its content
9196     * inside.  In effect, this tells you the available area where content can
9197     * be placed and remain visible to users.
9198     *
9199     * <p>This function requires an IPC back to the window manager to retrieve
9200     * the requested information, so should not be used in performance critical
9201     * code like drawing.
9202     *
9203     * @param outRect Filled in with the visible display frame.  If the view
9204     * is not attached to a window, this is simply the raw display size.
9205     */
9206    public void getWindowVisibleDisplayFrame(Rect outRect) {
9207        if (mAttachInfo != null) {
9208            try {
9209                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
9210            } catch (RemoteException e) {
9211                return;
9212            }
9213            // XXX This is really broken, and probably all needs to be done
9214            // in the window manager, and we need to know more about whether
9215            // we want the area behind or in front of the IME.
9216            final Rect insets = mAttachInfo.mVisibleInsets;
9217            outRect.left += insets.left;
9218            outRect.top += insets.top;
9219            outRect.right -= insets.right;
9220            outRect.bottom -= insets.bottom;
9221            return;
9222        }
9223        // The view is not attached to a display so we don't have a context.
9224        // Make a best guess about the display size.
9225        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
9226        d.getRectSize(outRect);
9227    }
9228
9229    /**
9230     * Dispatch a notification about a resource configuration change down
9231     * the view hierarchy.
9232     * ViewGroups should override to route to their children.
9233     *
9234     * @param newConfig The new resource configuration.
9235     *
9236     * @see #onConfigurationChanged(android.content.res.Configuration)
9237     */
9238    public void dispatchConfigurationChanged(Configuration newConfig) {
9239        onConfigurationChanged(newConfig);
9240    }
9241
9242    /**
9243     * Called when the current configuration of the resources being used
9244     * by the application have changed.  You can use this to decide when
9245     * to reload resources that can changed based on orientation and other
9246     * configuration characteristics.  You only need to use this if you are
9247     * not relying on the normal {@link android.app.Activity} mechanism of
9248     * recreating the activity instance upon a configuration change.
9249     *
9250     * @param newConfig The new resource configuration.
9251     */
9252    protected void onConfigurationChanged(Configuration newConfig) {
9253    }
9254
9255    /**
9256     * Private function to aggregate all per-view attributes in to the view
9257     * root.
9258     */
9259    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9260        performCollectViewAttributes(attachInfo, visibility);
9261    }
9262
9263    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9264        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
9265            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
9266                attachInfo.mKeepScreenOn = true;
9267            }
9268            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
9269            ListenerInfo li = mListenerInfo;
9270            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
9271                attachInfo.mHasSystemUiListeners = true;
9272            }
9273        }
9274    }
9275
9276    void needGlobalAttributesUpdate(boolean force) {
9277        final AttachInfo ai = mAttachInfo;
9278        if (ai != null && !ai.mRecomputeGlobalAttributes) {
9279            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
9280                    || ai.mHasSystemUiListeners) {
9281                ai.mRecomputeGlobalAttributes = true;
9282            }
9283        }
9284    }
9285
9286    /**
9287     * Returns whether the device is currently in touch mode.  Touch mode is entered
9288     * once the user begins interacting with the device by touch, and affects various
9289     * things like whether focus is always visible to the user.
9290     *
9291     * @return Whether the device is in touch mode.
9292     */
9293    @ViewDebug.ExportedProperty
9294    public boolean isInTouchMode() {
9295        if (mAttachInfo != null) {
9296            return mAttachInfo.mInTouchMode;
9297        } else {
9298            return ViewRootImpl.isInTouchMode();
9299        }
9300    }
9301
9302    /**
9303     * Returns the context the view is running in, through which it can
9304     * access the current theme, resources, etc.
9305     *
9306     * @return The view's Context.
9307     */
9308    @ViewDebug.CapturedViewProperty
9309    public final Context getContext() {
9310        return mContext;
9311    }
9312
9313    /**
9314     * Handle a key event before it is processed by any input method
9315     * associated with the view hierarchy.  This can be used to intercept
9316     * key events in special situations before the IME consumes them; a
9317     * typical example would be handling the BACK key to update the application's
9318     * UI instead of allowing the IME to see it and close itself.
9319     *
9320     * @param keyCode The value in event.getKeyCode().
9321     * @param event Description of the key event.
9322     * @return If you handled the event, return true. If you want to allow the
9323     *         event to be handled by the next receiver, return false.
9324     */
9325    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
9326        return false;
9327    }
9328
9329    /**
9330     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
9331     * KeyEvent.Callback.onKeyDown()}: perform press of the view
9332     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
9333     * is released, if the view is enabled and clickable.
9334     *
9335     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9336     * although some may elect to do so in some situations. Do not rely on this to
9337     * catch software key presses.
9338     *
9339     * @param keyCode A key code that represents the button pressed, from
9340     *                {@link android.view.KeyEvent}.
9341     * @param event   The KeyEvent object that defines the button action.
9342     */
9343    public boolean onKeyDown(int keyCode, KeyEvent event) {
9344        boolean result = false;
9345
9346        if (KeyEvent.isConfirmKey(keyCode)) {
9347            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9348                return true;
9349            }
9350            // Long clickable items don't necessarily have to be clickable
9351            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
9352                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
9353                    (event.getRepeatCount() == 0)) {
9354                setPressed(true);
9355                checkForLongClick(0);
9356                return true;
9357            }
9358        }
9359        return result;
9360    }
9361
9362    /**
9363     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
9364     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
9365     * the event).
9366     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9367     * although some may elect to do so in some situations. Do not rely on this to
9368     * catch software key presses.
9369     */
9370    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
9371        return false;
9372    }
9373
9374    /**
9375     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
9376     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
9377     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
9378     * {@link KeyEvent#KEYCODE_ENTER} is released.
9379     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9380     * although some may elect to do so in some situations. Do not rely on this to
9381     * catch software key presses.
9382     *
9383     * @param keyCode A key code that represents the button pressed, from
9384     *                {@link android.view.KeyEvent}.
9385     * @param event   The KeyEvent object that defines the button action.
9386     */
9387    public boolean onKeyUp(int keyCode, KeyEvent event) {
9388        if (KeyEvent.isConfirmKey(keyCode)) {
9389            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9390                return true;
9391            }
9392            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
9393                setPressed(false);
9394
9395                if (!mHasPerformedLongPress) {
9396                    // This is a tap, so remove the longpress check
9397                    removeLongPressCallback();
9398                    return performClick();
9399                }
9400            }
9401        }
9402        return false;
9403    }
9404
9405    /**
9406     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
9407     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
9408     * the event).
9409     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9410     * although some may elect to do so in some situations. Do not rely on this to
9411     * catch software key presses.
9412     *
9413     * @param keyCode     A key code that represents the button pressed, from
9414     *                    {@link android.view.KeyEvent}.
9415     * @param repeatCount The number of times the action was made.
9416     * @param event       The KeyEvent object that defines the button action.
9417     */
9418    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
9419        return false;
9420    }
9421
9422    /**
9423     * Called on the focused view when a key shortcut event is not handled.
9424     * Override this method to implement local key shortcuts for the View.
9425     * Key shortcuts can also be implemented by setting the
9426     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
9427     *
9428     * @param keyCode The value in event.getKeyCode().
9429     * @param event Description of the key event.
9430     * @return If you handled the event, return true. If you want to allow the
9431     *         event to be handled by the next receiver, return false.
9432     */
9433    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
9434        return false;
9435    }
9436
9437    /**
9438     * Check whether the called view is a text editor, in which case it
9439     * would make sense to automatically display a soft input window for
9440     * it.  Subclasses should override this if they implement
9441     * {@link #onCreateInputConnection(EditorInfo)} to return true if
9442     * a call on that method would return a non-null InputConnection, and
9443     * they are really a first-class editor that the user would normally
9444     * start typing on when the go into a window containing your view.
9445     *
9446     * <p>The default implementation always returns false.  This does
9447     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9448     * will not be called or the user can not otherwise perform edits on your
9449     * view; it is just a hint to the system that this is not the primary
9450     * purpose of this view.
9451     *
9452     * @return Returns true if this view is a text editor, else false.
9453     */
9454    public boolean onCheckIsTextEditor() {
9455        return false;
9456    }
9457
9458    /**
9459     * Create a new InputConnection for an InputMethod to interact
9460     * with the view.  The default implementation returns null, since it doesn't
9461     * support input methods.  You can override this to implement such support.
9462     * This is only needed for views that take focus and text input.
9463     *
9464     * <p>When implementing this, you probably also want to implement
9465     * {@link #onCheckIsTextEditor()} to indicate you will return a
9466     * non-null InputConnection.</p>
9467     *
9468     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9469     * object correctly and in its entirety, so that the connected IME can rely
9470     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9471     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9472     * must be filled in with the correct cursor position for IMEs to work correctly
9473     * with your application.</p>
9474     *
9475     * @param outAttrs Fill in with attribute information about the connection.
9476     */
9477    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9478        return null;
9479    }
9480
9481    /**
9482     * Called by the {@link android.view.inputmethod.InputMethodManager}
9483     * when a view who is not the current
9484     * input connection target is trying to make a call on the manager.  The
9485     * default implementation returns false; you can override this to return
9486     * true for certain views if you are performing InputConnection proxying
9487     * to them.
9488     * @param view The View that is making the InputMethodManager call.
9489     * @return Return true to allow the call, false to reject.
9490     */
9491    public boolean checkInputConnectionProxy(View view) {
9492        return false;
9493    }
9494
9495    /**
9496     * Show the context menu for this view. It is not safe to hold on to the
9497     * menu after returning from this method.
9498     *
9499     * You should normally not overload this method. Overload
9500     * {@link #onCreateContextMenu(ContextMenu)} or define an
9501     * {@link OnCreateContextMenuListener} to add items to the context menu.
9502     *
9503     * @param menu The context menu to populate
9504     */
9505    public void createContextMenu(ContextMenu menu) {
9506        ContextMenuInfo menuInfo = getContextMenuInfo();
9507
9508        // Sets the current menu info so all items added to menu will have
9509        // my extra info set.
9510        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
9511
9512        onCreateContextMenu(menu);
9513        ListenerInfo li = mListenerInfo;
9514        if (li != null && li.mOnCreateContextMenuListener != null) {
9515            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
9516        }
9517
9518        // Clear the extra information so subsequent items that aren't mine don't
9519        // have my extra info.
9520        ((MenuBuilder)menu).setCurrentMenuInfo(null);
9521
9522        if (mParent != null) {
9523            mParent.createContextMenu(menu);
9524        }
9525    }
9526
9527    /**
9528     * Views should implement this if they have extra information to associate
9529     * with the context menu. The return result is supplied as a parameter to
9530     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
9531     * callback.
9532     *
9533     * @return Extra information about the item for which the context menu
9534     *         should be shown. This information will vary across different
9535     *         subclasses of View.
9536     */
9537    protected ContextMenuInfo getContextMenuInfo() {
9538        return null;
9539    }
9540
9541    /**
9542     * Views should implement this if the view itself is going to add items to
9543     * the context menu.
9544     *
9545     * @param menu the context menu to populate
9546     */
9547    protected void onCreateContextMenu(ContextMenu menu) {
9548    }
9549
9550    /**
9551     * Implement this method to handle trackball motion events.  The
9552     * <em>relative</em> movement of the trackball since the last event
9553     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
9554     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
9555     * that a movement of 1 corresponds to the user pressing one DPAD key (so
9556     * they will often be fractional values, representing the more fine-grained
9557     * movement information available from a trackball).
9558     *
9559     * @param event The motion event.
9560     * @return True if the event was handled, false otherwise.
9561     */
9562    public boolean onTrackballEvent(MotionEvent event) {
9563        return false;
9564    }
9565
9566    /**
9567     * Implement this method to handle generic motion events.
9568     * <p>
9569     * Generic motion events describe joystick movements, mouse hovers, track pad
9570     * touches, scroll wheel movements and other input events.  The
9571     * {@link MotionEvent#getSource() source} of the motion event specifies
9572     * the class of input that was received.  Implementations of this method
9573     * must examine the bits in the source before processing the event.
9574     * The following code example shows how this is done.
9575     * </p><p>
9576     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9577     * are delivered to the view under the pointer.  All other generic motion events are
9578     * delivered to the focused view.
9579     * </p>
9580     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
9581     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
9582     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
9583     *             // process the joystick movement...
9584     *             return true;
9585     *         }
9586     *     }
9587     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
9588     *         switch (event.getAction()) {
9589     *             case MotionEvent.ACTION_HOVER_MOVE:
9590     *                 // process the mouse hover movement...
9591     *                 return true;
9592     *             case MotionEvent.ACTION_SCROLL:
9593     *                 // process the scroll wheel movement...
9594     *                 return true;
9595     *         }
9596     *     }
9597     *     return super.onGenericMotionEvent(event);
9598     * }</pre>
9599     *
9600     * @param event The generic motion event being processed.
9601     * @return True if the event was handled, false otherwise.
9602     */
9603    public boolean onGenericMotionEvent(MotionEvent event) {
9604        return false;
9605    }
9606
9607    /**
9608     * Implement this method to handle hover events.
9609     * <p>
9610     * This method is called whenever a pointer is hovering into, over, or out of the
9611     * bounds of a view and the view is not currently being touched.
9612     * Hover events are represented as pointer events with action
9613     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
9614     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
9615     * </p>
9616     * <ul>
9617     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
9618     * when the pointer enters the bounds of the view.</li>
9619     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
9620     * when the pointer has already entered the bounds of the view and has moved.</li>
9621     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
9622     * when the pointer has exited the bounds of the view or when the pointer is
9623     * about to go down due to a button click, tap, or similar user action that
9624     * causes the view to be touched.</li>
9625     * </ul>
9626     * <p>
9627     * The view should implement this method to return true to indicate that it is
9628     * handling the hover event, such as by changing its drawable state.
9629     * </p><p>
9630     * The default implementation calls {@link #setHovered} to update the hovered state
9631     * of the view when a hover enter or hover exit event is received, if the view
9632     * is enabled and is clickable.  The default implementation also sends hover
9633     * accessibility events.
9634     * </p>
9635     *
9636     * @param event The motion event that describes the hover.
9637     * @return True if the view handled the hover event.
9638     *
9639     * @see #isHovered
9640     * @see #setHovered
9641     * @see #onHoverChanged
9642     */
9643    public boolean onHoverEvent(MotionEvent event) {
9644        // The root view may receive hover (or touch) events that are outside the bounds of
9645        // the window.  This code ensures that we only send accessibility events for
9646        // hovers that are actually within the bounds of the root view.
9647        final int action = event.getActionMasked();
9648        if (!mSendingHoverAccessibilityEvents) {
9649            if ((action == MotionEvent.ACTION_HOVER_ENTER
9650                    || action == MotionEvent.ACTION_HOVER_MOVE)
9651                    && !hasHoveredChild()
9652                    && pointInView(event.getX(), event.getY())) {
9653                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9654                mSendingHoverAccessibilityEvents = true;
9655            }
9656        } else {
9657            if (action == MotionEvent.ACTION_HOVER_EXIT
9658                    || (action == MotionEvent.ACTION_MOVE
9659                            && !pointInView(event.getX(), event.getY()))) {
9660                mSendingHoverAccessibilityEvents = false;
9661                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9662            }
9663        }
9664
9665        if (isHoverable()) {
9666            switch (action) {
9667                case MotionEvent.ACTION_HOVER_ENTER:
9668                    setHovered(true);
9669                    break;
9670                case MotionEvent.ACTION_HOVER_EXIT:
9671                    setHovered(false);
9672                    break;
9673            }
9674
9675            // Dispatch the event to onGenericMotionEvent before returning true.
9676            // This is to provide compatibility with existing applications that
9677            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9678            // break because of the new default handling for hoverable views
9679            // in onHoverEvent.
9680            // Note that onGenericMotionEvent will be called by default when
9681            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9682            dispatchGenericMotionEventInternal(event);
9683            // The event was already handled by calling setHovered(), so always
9684            // return true.
9685            return true;
9686        }
9687
9688        return false;
9689    }
9690
9691    /**
9692     * Returns true if the view should handle {@link #onHoverEvent}
9693     * by calling {@link #setHovered} to change its hovered state.
9694     *
9695     * @return True if the view is hoverable.
9696     */
9697    private boolean isHoverable() {
9698        final int viewFlags = mViewFlags;
9699        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9700            return false;
9701        }
9702
9703        return (viewFlags & CLICKABLE) == CLICKABLE
9704                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9705    }
9706
9707    /**
9708     * Returns true if the view is currently hovered.
9709     *
9710     * @return True if the view is currently hovered.
9711     *
9712     * @see #setHovered
9713     * @see #onHoverChanged
9714     */
9715    @ViewDebug.ExportedProperty
9716    public boolean isHovered() {
9717        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9718    }
9719
9720    /**
9721     * Sets whether the view is currently hovered.
9722     * <p>
9723     * Calling this method also changes the drawable state of the view.  This
9724     * enables the view to react to hover by using different drawable resources
9725     * to change its appearance.
9726     * </p><p>
9727     * The {@link #onHoverChanged} method is called when the hovered state changes.
9728     * </p>
9729     *
9730     * @param hovered True if the view is hovered.
9731     *
9732     * @see #isHovered
9733     * @see #onHoverChanged
9734     */
9735    public void setHovered(boolean hovered) {
9736        if (hovered) {
9737            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9738                mPrivateFlags |= PFLAG_HOVERED;
9739                refreshDrawableState();
9740                onHoverChanged(true);
9741            }
9742        } else {
9743            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9744                mPrivateFlags &= ~PFLAG_HOVERED;
9745                refreshDrawableState();
9746                onHoverChanged(false);
9747            }
9748        }
9749    }
9750
9751    /**
9752     * Implement this method to handle hover state changes.
9753     * <p>
9754     * This method is called whenever the hover state changes as a result of a
9755     * call to {@link #setHovered}.
9756     * </p>
9757     *
9758     * @param hovered The current hover state, as returned by {@link #isHovered}.
9759     *
9760     * @see #isHovered
9761     * @see #setHovered
9762     */
9763    public void onHoverChanged(boolean hovered) {
9764    }
9765
9766    /**
9767     * Implement this method to handle touch screen motion events.
9768     * <p>
9769     * If this method is used to detect click actions, it is recommended that
9770     * the actions be performed by implementing and calling
9771     * {@link #performClick()}. This will ensure consistent system behavior,
9772     * including:
9773     * <ul>
9774     * <li>obeying click sound preferences
9775     * <li>dispatching OnClickListener calls
9776     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9777     * accessibility features are enabled
9778     * </ul>
9779     *
9780     * @param event The motion event.
9781     * @return True if the event was handled, false otherwise.
9782     */
9783    public boolean onTouchEvent(MotionEvent event) {
9784        final float x = event.getX();
9785        final float y = event.getY();
9786        final int viewFlags = mViewFlags;
9787
9788        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9789            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9790                setPressed(false);
9791            }
9792            // A disabled view that is clickable still consumes the touch
9793            // events, it just doesn't respond to them.
9794            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9795                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9796        }
9797
9798        if (mTouchDelegate != null) {
9799            if (mTouchDelegate.onTouchEvent(event)) {
9800                return true;
9801            }
9802        }
9803
9804        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9805                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9806            switch (event.getAction()) {
9807                case MotionEvent.ACTION_UP:
9808                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9809                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9810                        // take focus if we don't have it already and we should in
9811                        // touch mode.
9812                        boolean focusTaken = false;
9813                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9814                            focusTaken = requestFocus();
9815                        }
9816
9817                        if (prepressed) {
9818                            // The button is being released before we actually
9819                            // showed it as pressed.  Make it show the pressed
9820                            // state now (before scheduling the click) to ensure
9821                            // the user sees it.
9822                            setPressed(true, x, y);
9823                       }
9824
9825                        if (!mHasPerformedLongPress) {
9826                            // This is a tap, so remove the longpress check
9827                            removeLongPressCallback();
9828
9829                            // Only perform take click actions if we were in the pressed state
9830                            if (!focusTaken) {
9831                                // Use a Runnable and post this rather than calling
9832                                // performClick directly. This lets other visual state
9833                                // of the view update before click actions start.
9834                                if (mPerformClick == null) {
9835                                    mPerformClick = new PerformClick();
9836                                }
9837                                if (!post(mPerformClick)) {
9838                                    performClick();
9839                                }
9840                            }
9841                        }
9842
9843                        if (mUnsetPressedState == null) {
9844                            mUnsetPressedState = new UnsetPressedState();
9845                        }
9846
9847                        if (prepressed) {
9848                            postDelayed(mUnsetPressedState,
9849                                    ViewConfiguration.getPressedStateDuration());
9850                        } else if (!post(mUnsetPressedState)) {
9851                            // If the post failed, unpress right now
9852                            mUnsetPressedState.run();
9853                        }
9854
9855                        removeTapCallback();
9856                    }
9857                    break;
9858
9859                case MotionEvent.ACTION_DOWN:
9860                    mHasPerformedLongPress = false;
9861
9862                    if (performButtonActionOnTouchDown(event)) {
9863                        break;
9864                    }
9865
9866                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9867                    boolean isInScrollingContainer = isInScrollingContainer();
9868
9869                    // For views inside a scrolling container, delay the pressed feedback for
9870                    // a short period in case this is a scroll.
9871                    if (isInScrollingContainer) {
9872                        mPrivateFlags |= PFLAG_PREPRESSED;
9873                        if (mPendingCheckForTap == null) {
9874                            mPendingCheckForTap = new CheckForTap();
9875                        }
9876                        mPendingCheckForTap.x = event.getX();
9877                        mPendingCheckForTap.y = event.getY();
9878                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9879                    } else {
9880                        // Not inside a scrolling container, so show the feedback right away
9881                        setPressed(true, x, y);
9882                        checkForLongClick(0);
9883                    }
9884                    break;
9885
9886                case MotionEvent.ACTION_CANCEL:
9887                    setPressed(false);
9888                    removeTapCallback();
9889                    removeLongPressCallback();
9890                    break;
9891
9892                case MotionEvent.ACTION_MOVE:
9893                    drawableHotspotChanged(x, y);
9894
9895                    // Be lenient about moving outside of buttons
9896                    if (!pointInView(x, y, mTouchSlop)) {
9897                        // Outside button
9898                        removeTapCallback();
9899                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9900                            // Remove any future long press/tap checks
9901                            removeLongPressCallback();
9902
9903                            setPressed(false);
9904                        }
9905                    }
9906                    break;
9907            }
9908
9909            return true;
9910        }
9911
9912        return false;
9913    }
9914
9915    /**
9916     * @hide
9917     */
9918    public boolean isInScrollingContainer() {
9919        ViewParent p = getParent();
9920        while (p != null && p instanceof ViewGroup) {
9921            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9922                return true;
9923            }
9924            p = p.getParent();
9925        }
9926        return false;
9927    }
9928
9929    /**
9930     * Remove the longpress detection timer.
9931     */
9932    private void removeLongPressCallback() {
9933        if (mPendingCheckForLongPress != null) {
9934          removeCallbacks(mPendingCheckForLongPress);
9935        }
9936    }
9937
9938    /**
9939     * Remove the pending click action
9940     */
9941    private void removePerformClickCallback() {
9942        if (mPerformClick != null) {
9943            removeCallbacks(mPerformClick);
9944        }
9945    }
9946
9947    /**
9948     * Remove the prepress detection timer.
9949     */
9950    private void removeUnsetPressCallback() {
9951        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9952            setPressed(false);
9953            removeCallbacks(mUnsetPressedState);
9954        }
9955    }
9956
9957    /**
9958     * Remove the tap detection timer.
9959     */
9960    private void removeTapCallback() {
9961        if (mPendingCheckForTap != null) {
9962            mPrivateFlags &= ~PFLAG_PREPRESSED;
9963            removeCallbacks(mPendingCheckForTap);
9964        }
9965    }
9966
9967    /**
9968     * Cancels a pending long press.  Your subclass can use this if you
9969     * want the context menu to come up if the user presses and holds
9970     * at the same place, but you don't want it to come up if they press
9971     * and then move around enough to cause scrolling.
9972     */
9973    public void cancelLongPress() {
9974        removeLongPressCallback();
9975
9976        /*
9977         * The prepressed state handled by the tap callback is a display
9978         * construct, but the tap callback will post a long press callback
9979         * less its own timeout. Remove it here.
9980         */
9981        removeTapCallback();
9982    }
9983
9984    /**
9985     * Remove the pending callback for sending a
9986     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9987     */
9988    private void removeSendViewScrolledAccessibilityEventCallback() {
9989        if (mSendViewScrolledAccessibilityEvent != null) {
9990            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9991            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9992        }
9993    }
9994
9995    /**
9996     * Sets the TouchDelegate for this View.
9997     */
9998    public void setTouchDelegate(TouchDelegate delegate) {
9999        mTouchDelegate = delegate;
10000    }
10001
10002    /**
10003     * Gets the TouchDelegate for this View.
10004     */
10005    public TouchDelegate getTouchDelegate() {
10006        return mTouchDelegate;
10007    }
10008
10009    /**
10010     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
10011     *
10012     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
10013     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
10014     * available. This method should only be called for touch events.
10015     *
10016     * <p class="note">This api is not intended for most applications. Buffered dispatch
10017     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
10018     * streams will not improve your input latency. Side effects include: increased latency,
10019     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
10020     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
10021     * you.</p>
10022     */
10023    public final void requestUnbufferedDispatch(MotionEvent event) {
10024        final int action = event.getAction();
10025        if (mAttachInfo == null
10026                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
10027                || !event.isTouchEvent()) {
10028            return;
10029        }
10030        mAttachInfo.mUnbufferedDispatchRequested = true;
10031    }
10032
10033    /**
10034     * Set flags controlling behavior of this view.
10035     *
10036     * @param flags Constant indicating the value which should be set
10037     * @param mask Constant indicating the bit range that should be changed
10038     */
10039    void setFlags(int flags, int mask) {
10040        final boolean accessibilityEnabled =
10041                AccessibilityManager.getInstance(mContext).isEnabled();
10042        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
10043
10044        int old = mViewFlags;
10045        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
10046
10047        int changed = mViewFlags ^ old;
10048        if (changed == 0) {
10049            return;
10050        }
10051        int privateFlags = mPrivateFlags;
10052
10053        /* Check if the FOCUSABLE bit has changed */
10054        if (((changed & FOCUSABLE_MASK) != 0) &&
10055                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
10056            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
10057                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
10058                /* Give up focus if we are no longer focusable */
10059                clearFocus();
10060            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
10061                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
10062                /*
10063                 * Tell the view system that we are now available to take focus
10064                 * if no one else already has it.
10065                 */
10066                if (mParent != null) mParent.focusableViewAvailable(this);
10067            }
10068        }
10069
10070        final int newVisibility = flags & VISIBILITY_MASK;
10071        if (newVisibility == VISIBLE) {
10072            if ((changed & VISIBILITY_MASK) != 0) {
10073                /*
10074                 * If this view is becoming visible, invalidate it in case it changed while
10075                 * it was not visible. Marking it drawn ensures that the invalidation will
10076                 * go through.
10077                 */
10078                mPrivateFlags |= PFLAG_DRAWN;
10079                invalidate(true);
10080
10081                needGlobalAttributesUpdate(true);
10082
10083                // a view becoming visible is worth notifying the parent
10084                // about in case nothing has focus.  even if this specific view
10085                // isn't focusable, it may contain something that is, so let
10086                // the root view try to give this focus if nothing else does.
10087                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
10088                    mParent.focusableViewAvailable(this);
10089                }
10090            }
10091        }
10092
10093        /* Check if the GONE bit has changed */
10094        if ((changed & GONE) != 0) {
10095            needGlobalAttributesUpdate(false);
10096            requestLayout();
10097
10098            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
10099                if (hasFocus()) clearFocus();
10100                clearAccessibilityFocus();
10101                destroyDrawingCache();
10102                if (mParent instanceof View) {
10103                    // GONE views noop invalidation, so invalidate the parent
10104                    ((View) mParent).invalidate(true);
10105                }
10106                // Mark the view drawn to ensure that it gets invalidated properly the next
10107                // time it is visible and gets invalidated
10108                mPrivateFlags |= PFLAG_DRAWN;
10109            }
10110            if (mAttachInfo != null) {
10111                mAttachInfo.mViewVisibilityChanged = true;
10112            }
10113        }
10114
10115        /* Check if the VISIBLE bit has changed */
10116        if ((changed & INVISIBLE) != 0) {
10117            needGlobalAttributesUpdate(false);
10118            /*
10119             * If this view is becoming invisible, set the DRAWN flag so that
10120             * the next invalidate() will not be skipped.
10121             */
10122            mPrivateFlags |= PFLAG_DRAWN;
10123
10124            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
10125                // root view becoming invisible shouldn't clear focus and accessibility focus
10126                if (getRootView() != this) {
10127                    if (hasFocus()) clearFocus();
10128                    clearAccessibilityFocus();
10129                }
10130            }
10131            if (mAttachInfo != null) {
10132                mAttachInfo.mViewVisibilityChanged = true;
10133            }
10134        }
10135
10136        if ((changed & VISIBILITY_MASK) != 0) {
10137            // If the view is invisible, cleanup its display list to free up resources
10138            if (newVisibility != VISIBLE && mAttachInfo != null) {
10139                cleanupDraw();
10140            }
10141
10142            if (mParent instanceof ViewGroup) {
10143                ((ViewGroup) mParent).onChildVisibilityChanged(this,
10144                        (changed & VISIBILITY_MASK), newVisibility);
10145                ((View) mParent).invalidate(true);
10146            } else if (mParent != null) {
10147                mParent.invalidateChild(this, null);
10148            }
10149            dispatchVisibilityChanged(this, newVisibility);
10150
10151            notifySubtreeAccessibilityStateChangedIfNeeded();
10152        }
10153
10154        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
10155            destroyDrawingCache();
10156        }
10157
10158        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
10159            destroyDrawingCache();
10160            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10161            invalidateParentCaches();
10162        }
10163
10164        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
10165            destroyDrawingCache();
10166            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10167        }
10168
10169        if ((changed & DRAW_MASK) != 0) {
10170            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
10171                if (mBackground != null) {
10172                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10173                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
10174                } else {
10175                    mPrivateFlags |= PFLAG_SKIP_DRAW;
10176                }
10177            } else {
10178                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10179            }
10180            requestLayout();
10181            invalidate(true);
10182        }
10183
10184        if ((changed & KEEP_SCREEN_ON) != 0) {
10185            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10186                mParent.recomputeViewAttributes(this);
10187            }
10188        }
10189
10190        if (accessibilityEnabled) {
10191            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
10192                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
10193                if (oldIncludeForAccessibility != includeForAccessibility()) {
10194                    notifySubtreeAccessibilityStateChangedIfNeeded();
10195                } else {
10196                    notifyViewAccessibilityStateChangedIfNeeded(
10197                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10198                }
10199            } else if ((changed & ENABLED_MASK) != 0) {
10200                notifyViewAccessibilityStateChangedIfNeeded(
10201                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10202            }
10203        }
10204    }
10205
10206    /**
10207     * Change the view's z order in the tree, so it's on top of other sibling
10208     * views. This ordering change may affect layout, if the parent container
10209     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
10210     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
10211     * method should be followed by calls to {@link #requestLayout()} and
10212     * {@link View#invalidate()} on the view's parent to force the parent to redraw
10213     * with the new child ordering.
10214     *
10215     * @see ViewGroup#bringChildToFront(View)
10216     */
10217    public void bringToFront() {
10218        if (mParent != null) {
10219            mParent.bringChildToFront(this);
10220        }
10221    }
10222
10223    /**
10224     * This is called in response to an internal scroll in this view (i.e., the
10225     * view scrolled its own contents). This is typically as a result of
10226     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
10227     * called.
10228     *
10229     * @param l Current horizontal scroll origin.
10230     * @param t Current vertical scroll origin.
10231     * @param oldl Previous horizontal scroll origin.
10232     * @param oldt Previous vertical scroll origin.
10233     */
10234    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
10235        notifySubtreeAccessibilityStateChangedIfNeeded();
10236
10237        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10238            postSendViewScrolledAccessibilityEventCallback();
10239        }
10240
10241        mBackgroundSizeChanged = true;
10242        if (mForegroundInfo != null) {
10243            mForegroundInfo.mBoundsChanged = true;
10244        }
10245
10246        final AttachInfo ai = mAttachInfo;
10247        if (ai != null) {
10248            ai.mViewScrollChanged = true;
10249        }
10250
10251        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
10252            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
10253        }
10254    }
10255
10256    /**
10257     * Interface definition for a callback to be invoked when the scroll
10258     * X or Y positions of a view change.
10259     * <p>
10260     * <b>Note:</b> Some views handle scrolling independently from View and may
10261     * have their own separate listeners for scroll-type events. For example,
10262     * {@link android.widget.ListView ListView} allows clients to register an
10263     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
10264     * to listen for changes in list scroll position.
10265     *
10266     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
10267     */
10268    public interface OnScrollChangeListener {
10269        /**
10270         * Called when the scroll position of a view changes.
10271         *
10272         * @param v The view whose scroll position has changed.
10273         * @param scrollX Current horizontal scroll origin.
10274         * @param scrollY Current vertical scroll origin.
10275         * @param oldScrollX Previous horizontal scroll origin.
10276         * @param oldScrollY Previous vertical scroll origin.
10277         */
10278        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
10279    }
10280
10281    /**
10282     * Interface definition for a callback to be invoked when the layout bounds of a view
10283     * changes due to layout processing.
10284     */
10285    public interface OnLayoutChangeListener {
10286        /**
10287         * Called when the layout bounds of a view changes due to layout processing.
10288         *
10289         * @param v The view whose bounds have changed.
10290         * @param left The new value of the view's left property.
10291         * @param top The new value of the view's top property.
10292         * @param right The new value of the view's right property.
10293         * @param bottom The new value of the view's bottom property.
10294         * @param oldLeft The previous value of the view's left property.
10295         * @param oldTop The previous value of the view's top property.
10296         * @param oldRight The previous value of the view's right property.
10297         * @param oldBottom The previous value of the view's bottom property.
10298         */
10299        void onLayoutChange(View v, int left, int top, int right, int bottom,
10300            int oldLeft, int oldTop, int oldRight, int oldBottom);
10301    }
10302
10303    /**
10304     * This is called during layout when the size of this view has changed. If
10305     * you were just added to the view hierarchy, you're called with the old
10306     * values of 0.
10307     *
10308     * @param w Current width of this view.
10309     * @param h Current height of this view.
10310     * @param oldw Old width of this view.
10311     * @param oldh Old height of this view.
10312     */
10313    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
10314    }
10315
10316    /**
10317     * Called by draw to draw the child views. This may be overridden
10318     * by derived classes to gain control just before its children are drawn
10319     * (but after its own view has been drawn).
10320     * @param canvas the canvas on which to draw the view
10321     */
10322    protected void dispatchDraw(Canvas canvas) {
10323
10324    }
10325
10326    /**
10327     * Gets the parent of this view. Note that the parent is a
10328     * ViewParent and not necessarily a View.
10329     *
10330     * @return Parent of this view.
10331     */
10332    public final ViewParent getParent() {
10333        return mParent;
10334    }
10335
10336    /**
10337     * Set the horizontal scrolled position of your view. This will cause a call to
10338     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10339     * invalidated.
10340     * @param value the x position to scroll to
10341     */
10342    public void setScrollX(int value) {
10343        scrollTo(value, mScrollY);
10344    }
10345
10346    /**
10347     * Set the vertical scrolled position of your view. This will cause a call to
10348     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10349     * invalidated.
10350     * @param value the y position to scroll to
10351     */
10352    public void setScrollY(int value) {
10353        scrollTo(mScrollX, value);
10354    }
10355
10356    /**
10357     * Return the scrolled left position of this view. This is the left edge of
10358     * the displayed part of your view. You do not need to draw any pixels
10359     * farther left, since those are outside of the frame of your view on
10360     * screen.
10361     *
10362     * @return The left edge of the displayed part of your view, in pixels.
10363     */
10364    public final int getScrollX() {
10365        return mScrollX;
10366    }
10367
10368    /**
10369     * Return the scrolled top position of this view. This is the top edge of
10370     * the displayed part of your view. You do not need to draw any pixels above
10371     * it, since those are outside of the frame of your view on screen.
10372     *
10373     * @return The top edge of the displayed part of your view, in pixels.
10374     */
10375    public final int getScrollY() {
10376        return mScrollY;
10377    }
10378
10379    /**
10380     * Return the width of the your view.
10381     *
10382     * @return The width of your view, in pixels.
10383     */
10384    @ViewDebug.ExportedProperty(category = "layout")
10385    public final int getWidth() {
10386        return mRight - mLeft;
10387    }
10388
10389    /**
10390     * Return the height of your view.
10391     *
10392     * @return The height of your view, in pixels.
10393     */
10394    @ViewDebug.ExportedProperty(category = "layout")
10395    public final int getHeight() {
10396        return mBottom - mTop;
10397    }
10398
10399    /**
10400     * Return the visible drawing bounds of your view. Fills in the output
10401     * rectangle with the values from getScrollX(), getScrollY(),
10402     * getWidth(), and getHeight(). These bounds do not account for any
10403     * transformation properties currently set on the view, such as
10404     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
10405     *
10406     * @param outRect The (scrolled) drawing bounds of the view.
10407     */
10408    public void getDrawingRect(Rect outRect) {
10409        outRect.left = mScrollX;
10410        outRect.top = mScrollY;
10411        outRect.right = mScrollX + (mRight - mLeft);
10412        outRect.bottom = mScrollY + (mBottom - mTop);
10413    }
10414
10415    /**
10416     * Like {@link #getMeasuredWidthAndState()}, but only returns the
10417     * raw width component (that is the result is masked by
10418     * {@link #MEASURED_SIZE_MASK}).
10419     *
10420     * @return The raw measured width of this view.
10421     */
10422    public final int getMeasuredWidth() {
10423        return mMeasuredWidth & MEASURED_SIZE_MASK;
10424    }
10425
10426    /**
10427     * Return the full width measurement information for this view as computed
10428     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10429     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10430     * This should be used during measurement and layout calculations only. Use
10431     * {@link #getWidth()} to see how wide a view is after layout.
10432     *
10433     * @return The measured width of this view as a bit mask.
10434     */
10435    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10436            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10437                    name = "MEASURED_STATE_TOO_SMALL"),
10438    })
10439    public final int getMeasuredWidthAndState() {
10440        return mMeasuredWidth;
10441    }
10442
10443    /**
10444     * Like {@link #getMeasuredHeightAndState()}, but only returns the
10445     * raw width component (that is the result is masked by
10446     * {@link #MEASURED_SIZE_MASK}).
10447     *
10448     * @return The raw measured height of this view.
10449     */
10450    public final int getMeasuredHeight() {
10451        return mMeasuredHeight & MEASURED_SIZE_MASK;
10452    }
10453
10454    /**
10455     * Return the full height measurement information for this view as computed
10456     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10457     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10458     * This should be used during measurement and layout calculations only. Use
10459     * {@link #getHeight()} to see how wide a view is after layout.
10460     *
10461     * @return The measured width of this view as a bit mask.
10462     */
10463    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10464            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10465                    name = "MEASURED_STATE_TOO_SMALL"),
10466    })
10467    public final int getMeasuredHeightAndState() {
10468        return mMeasuredHeight;
10469    }
10470
10471    /**
10472     * Return only the state bits of {@link #getMeasuredWidthAndState()}
10473     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
10474     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
10475     * and the height component is at the shifted bits
10476     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
10477     */
10478    public final int getMeasuredState() {
10479        return (mMeasuredWidth&MEASURED_STATE_MASK)
10480                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
10481                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
10482    }
10483
10484    /**
10485     * The transform matrix of this view, which is calculated based on the current
10486     * rotation, scale, and pivot properties.
10487     *
10488     * @see #getRotation()
10489     * @see #getScaleX()
10490     * @see #getScaleY()
10491     * @see #getPivotX()
10492     * @see #getPivotY()
10493     * @return The current transform matrix for the view
10494     */
10495    public Matrix getMatrix() {
10496        ensureTransformationInfo();
10497        final Matrix matrix = mTransformationInfo.mMatrix;
10498        mRenderNode.getMatrix(matrix);
10499        return matrix;
10500    }
10501
10502    /**
10503     * Returns true if the transform matrix is the identity matrix.
10504     * Recomputes the matrix if necessary.
10505     *
10506     * @return True if the transform matrix is the identity matrix, false otherwise.
10507     */
10508    final boolean hasIdentityMatrix() {
10509        return mRenderNode.hasIdentityMatrix();
10510    }
10511
10512    void ensureTransformationInfo() {
10513        if (mTransformationInfo == null) {
10514            mTransformationInfo = new TransformationInfo();
10515        }
10516    }
10517
10518   /**
10519     * Utility method to retrieve the inverse of the current mMatrix property.
10520     * We cache the matrix to avoid recalculating it when transform properties
10521     * have not changed.
10522     *
10523     * @return The inverse of the current matrix of this view.
10524     * @hide
10525     */
10526    public final Matrix getInverseMatrix() {
10527        ensureTransformationInfo();
10528        if (mTransformationInfo.mInverseMatrix == null) {
10529            mTransformationInfo.mInverseMatrix = new Matrix();
10530        }
10531        final Matrix matrix = mTransformationInfo.mInverseMatrix;
10532        mRenderNode.getInverseMatrix(matrix);
10533        return matrix;
10534    }
10535
10536    /**
10537     * Gets the distance along the Z axis from the camera to this view.
10538     *
10539     * @see #setCameraDistance(float)
10540     *
10541     * @return The distance along the Z axis.
10542     */
10543    public float getCameraDistance() {
10544        final float dpi = mResources.getDisplayMetrics().densityDpi;
10545        return -(mRenderNode.getCameraDistance() * dpi);
10546    }
10547
10548    /**
10549     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
10550     * views are drawn) from the camera to this view. The camera's distance
10551     * affects 3D transformations, for instance rotations around the X and Y
10552     * axis. If the rotationX or rotationY properties are changed and this view is
10553     * large (more than half the size of the screen), it is recommended to always
10554     * use a camera distance that's greater than the height (X axis rotation) or
10555     * the width (Y axis rotation) of this view.</p>
10556     *
10557     * <p>The distance of the camera from the view plane can have an affect on the
10558     * perspective distortion of the view when it is rotated around the x or y axis.
10559     * For example, a large distance will result in a large viewing angle, and there
10560     * will not be much perspective distortion of the view as it rotates. A short
10561     * distance may cause much more perspective distortion upon rotation, and can
10562     * also result in some drawing artifacts if the rotated view ends up partially
10563     * behind the camera (which is why the recommendation is to use a distance at
10564     * least as far as the size of the view, if the view is to be rotated.)</p>
10565     *
10566     * <p>The distance is expressed in "depth pixels." The default distance depends
10567     * on the screen density. For instance, on a medium density display, the
10568     * default distance is 1280. On a high density display, the default distance
10569     * is 1920.</p>
10570     *
10571     * <p>If you want to specify a distance that leads to visually consistent
10572     * results across various densities, use the following formula:</p>
10573     * <pre>
10574     * float scale = context.getResources().getDisplayMetrics().density;
10575     * view.setCameraDistance(distance * scale);
10576     * </pre>
10577     *
10578     * <p>The density scale factor of a high density display is 1.5,
10579     * and 1920 = 1280 * 1.5.</p>
10580     *
10581     * @param distance The distance in "depth pixels", if negative the opposite
10582     *        value is used
10583     *
10584     * @see #setRotationX(float)
10585     * @see #setRotationY(float)
10586     */
10587    public void setCameraDistance(float distance) {
10588        final float dpi = mResources.getDisplayMetrics().densityDpi;
10589
10590        invalidateViewProperty(true, false);
10591        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
10592        invalidateViewProperty(false, false);
10593
10594        invalidateParentIfNeededAndWasQuickRejected();
10595    }
10596
10597    /**
10598     * The degrees that the view is rotated around the pivot point.
10599     *
10600     * @see #setRotation(float)
10601     * @see #getPivotX()
10602     * @see #getPivotY()
10603     *
10604     * @return The degrees of rotation.
10605     */
10606    @ViewDebug.ExportedProperty(category = "drawing")
10607    public float getRotation() {
10608        return mRenderNode.getRotation();
10609    }
10610
10611    /**
10612     * Sets the degrees that the view is rotated around the pivot point. Increasing values
10613     * result in clockwise rotation.
10614     *
10615     * @param rotation The degrees of rotation.
10616     *
10617     * @see #getRotation()
10618     * @see #getPivotX()
10619     * @see #getPivotY()
10620     * @see #setRotationX(float)
10621     * @see #setRotationY(float)
10622     *
10623     * @attr ref android.R.styleable#View_rotation
10624     */
10625    public void setRotation(float rotation) {
10626        if (rotation != getRotation()) {
10627            // Double-invalidation is necessary to capture view's old and new areas
10628            invalidateViewProperty(true, false);
10629            mRenderNode.setRotation(rotation);
10630            invalidateViewProperty(false, true);
10631
10632            invalidateParentIfNeededAndWasQuickRejected();
10633            notifySubtreeAccessibilityStateChangedIfNeeded();
10634        }
10635    }
10636
10637    /**
10638     * The degrees that the view is rotated around the vertical axis through the pivot point.
10639     *
10640     * @see #getPivotX()
10641     * @see #getPivotY()
10642     * @see #setRotationY(float)
10643     *
10644     * @return The degrees of Y rotation.
10645     */
10646    @ViewDebug.ExportedProperty(category = "drawing")
10647    public float getRotationY() {
10648        return mRenderNode.getRotationY();
10649    }
10650
10651    /**
10652     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
10653     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
10654     * down the y axis.
10655     *
10656     * When rotating large views, it is recommended to adjust the camera distance
10657     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10658     *
10659     * @param rotationY The degrees of Y rotation.
10660     *
10661     * @see #getRotationY()
10662     * @see #getPivotX()
10663     * @see #getPivotY()
10664     * @see #setRotation(float)
10665     * @see #setRotationX(float)
10666     * @see #setCameraDistance(float)
10667     *
10668     * @attr ref android.R.styleable#View_rotationY
10669     */
10670    public void setRotationY(float rotationY) {
10671        if (rotationY != getRotationY()) {
10672            invalidateViewProperty(true, false);
10673            mRenderNode.setRotationY(rotationY);
10674            invalidateViewProperty(false, true);
10675
10676            invalidateParentIfNeededAndWasQuickRejected();
10677            notifySubtreeAccessibilityStateChangedIfNeeded();
10678        }
10679    }
10680
10681    /**
10682     * The degrees that the view is rotated around the horizontal axis through the pivot point.
10683     *
10684     * @see #getPivotX()
10685     * @see #getPivotY()
10686     * @see #setRotationX(float)
10687     *
10688     * @return The degrees of X rotation.
10689     */
10690    @ViewDebug.ExportedProperty(category = "drawing")
10691    public float getRotationX() {
10692        return mRenderNode.getRotationX();
10693    }
10694
10695    /**
10696     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10697     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10698     * x axis.
10699     *
10700     * When rotating large views, it is recommended to adjust the camera distance
10701     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10702     *
10703     * @param rotationX The degrees of X rotation.
10704     *
10705     * @see #getRotationX()
10706     * @see #getPivotX()
10707     * @see #getPivotY()
10708     * @see #setRotation(float)
10709     * @see #setRotationY(float)
10710     * @see #setCameraDistance(float)
10711     *
10712     * @attr ref android.R.styleable#View_rotationX
10713     */
10714    public void setRotationX(float rotationX) {
10715        if (rotationX != getRotationX()) {
10716            invalidateViewProperty(true, false);
10717            mRenderNode.setRotationX(rotationX);
10718            invalidateViewProperty(false, true);
10719
10720            invalidateParentIfNeededAndWasQuickRejected();
10721            notifySubtreeAccessibilityStateChangedIfNeeded();
10722        }
10723    }
10724
10725    /**
10726     * The amount that the view is scaled in x around the pivot point, as a proportion of
10727     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10728     *
10729     * <p>By default, this is 1.0f.
10730     *
10731     * @see #getPivotX()
10732     * @see #getPivotY()
10733     * @return The scaling factor.
10734     */
10735    @ViewDebug.ExportedProperty(category = "drawing")
10736    public float getScaleX() {
10737        return mRenderNode.getScaleX();
10738    }
10739
10740    /**
10741     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10742     * the view's unscaled width. A value of 1 means that no scaling is applied.
10743     *
10744     * @param scaleX The scaling factor.
10745     * @see #getPivotX()
10746     * @see #getPivotY()
10747     *
10748     * @attr ref android.R.styleable#View_scaleX
10749     */
10750    public void setScaleX(float scaleX) {
10751        if (scaleX != getScaleX()) {
10752            invalidateViewProperty(true, false);
10753            mRenderNode.setScaleX(scaleX);
10754            invalidateViewProperty(false, true);
10755
10756            invalidateParentIfNeededAndWasQuickRejected();
10757            notifySubtreeAccessibilityStateChangedIfNeeded();
10758        }
10759    }
10760
10761    /**
10762     * The amount that the view is scaled in y around the pivot point, as a proportion of
10763     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10764     *
10765     * <p>By default, this is 1.0f.
10766     *
10767     * @see #getPivotX()
10768     * @see #getPivotY()
10769     * @return The scaling factor.
10770     */
10771    @ViewDebug.ExportedProperty(category = "drawing")
10772    public float getScaleY() {
10773        return mRenderNode.getScaleY();
10774    }
10775
10776    /**
10777     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10778     * the view's unscaled width. A value of 1 means that no scaling is applied.
10779     *
10780     * @param scaleY The scaling factor.
10781     * @see #getPivotX()
10782     * @see #getPivotY()
10783     *
10784     * @attr ref android.R.styleable#View_scaleY
10785     */
10786    public void setScaleY(float scaleY) {
10787        if (scaleY != getScaleY()) {
10788            invalidateViewProperty(true, false);
10789            mRenderNode.setScaleY(scaleY);
10790            invalidateViewProperty(false, true);
10791
10792            invalidateParentIfNeededAndWasQuickRejected();
10793            notifySubtreeAccessibilityStateChangedIfNeeded();
10794        }
10795    }
10796
10797    /**
10798     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10799     * and {@link #setScaleX(float) scaled}.
10800     *
10801     * @see #getRotation()
10802     * @see #getScaleX()
10803     * @see #getScaleY()
10804     * @see #getPivotY()
10805     * @return The x location of the pivot point.
10806     *
10807     * @attr ref android.R.styleable#View_transformPivotX
10808     */
10809    @ViewDebug.ExportedProperty(category = "drawing")
10810    public float getPivotX() {
10811        return mRenderNode.getPivotX();
10812    }
10813
10814    /**
10815     * Sets the x location of the point around which the view is
10816     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10817     * By default, the pivot point is centered on the object.
10818     * Setting this property disables this behavior and causes the view to use only the
10819     * explicitly set pivotX and pivotY values.
10820     *
10821     * @param pivotX The x location of the pivot point.
10822     * @see #getRotation()
10823     * @see #getScaleX()
10824     * @see #getScaleY()
10825     * @see #getPivotY()
10826     *
10827     * @attr ref android.R.styleable#View_transformPivotX
10828     */
10829    public void setPivotX(float pivotX) {
10830        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10831            invalidateViewProperty(true, false);
10832            mRenderNode.setPivotX(pivotX);
10833            invalidateViewProperty(false, true);
10834
10835            invalidateParentIfNeededAndWasQuickRejected();
10836        }
10837    }
10838
10839    /**
10840     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10841     * and {@link #setScaleY(float) scaled}.
10842     *
10843     * @see #getRotation()
10844     * @see #getScaleX()
10845     * @see #getScaleY()
10846     * @see #getPivotY()
10847     * @return The y location of the pivot point.
10848     *
10849     * @attr ref android.R.styleable#View_transformPivotY
10850     */
10851    @ViewDebug.ExportedProperty(category = "drawing")
10852    public float getPivotY() {
10853        return mRenderNode.getPivotY();
10854    }
10855
10856    /**
10857     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10858     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10859     * Setting this property disables this behavior and causes the view to use only the
10860     * explicitly set pivotX and pivotY values.
10861     *
10862     * @param pivotY The y location of the pivot point.
10863     * @see #getRotation()
10864     * @see #getScaleX()
10865     * @see #getScaleY()
10866     * @see #getPivotY()
10867     *
10868     * @attr ref android.R.styleable#View_transformPivotY
10869     */
10870    public void setPivotY(float pivotY) {
10871        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10872            invalidateViewProperty(true, false);
10873            mRenderNode.setPivotY(pivotY);
10874            invalidateViewProperty(false, true);
10875
10876            invalidateParentIfNeededAndWasQuickRejected();
10877        }
10878    }
10879
10880    /**
10881     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10882     * completely transparent and 1 means the view is completely opaque.
10883     *
10884     * <p>By default this is 1.0f.
10885     * @return The opacity of the view.
10886     */
10887    @ViewDebug.ExportedProperty(category = "drawing")
10888    public float getAlpha() {
10889        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10890    }
10891
10892    /**
10893     * Returns whether this View has content which overlaps.
10894     *
10895     * <p>This function, intended to be overridden by specific View types, is an optimization when
10896     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10897     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10898     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10899     * directly. An example of overlapping rendering is a TextView with a background image, such as
10900     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10901     * ImageView with only the foreground image. The default implementation returns true; subclasses
10902     * should override if they have cases which can be optimized.</p>
10903     *
10904     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10905     * necessitates that a View return true if it uses the methods internally without passing the
10906     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10907     *
10908     * @return true if the content in this view might overlap, false otherwise.
10909     */
10910    @ViewDebug.ExportedProperty(category = "drawing")
10911    public boolean hasOverlappingRendering() {
10912        return true;
10913    }
10914
10915    /**
10916     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10917     * completely transparent and 1 means the view is completely opaque.</p>
10918     *
10919     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10920     * performance implications, especially for large views. It is best to use the alpha property
10921     * sparingly and transiently, as in the case of fading animations.</p>
10922     *
10923     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10924     * strongly recommended for performance reasons to either override
10925     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10926     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10927     *
10928     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10929     * responsible for applying the opacity itself.</p>
10930     *
10931     * <p>Note that if the view is backed by a
10932     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10933     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10934     * 1.0 will supersede the alpha of the layer paint.</p>
10935     *
10936     * @param alpha The opacity of the view.
10937     *
10938     * @see #hasOverlappingRendering()
10939     * @see #setLayerType(int, android.graphics.Paint)
10940     *
10941     * @attr ref android.R.styleable#View_alpha
10942     */
10943    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
10944        ensureTransformationInfo();
10945        if (mTransformationInfo.mAlpha != alpha) {
10946            mTransformationInfo.mAlpha = alpha;
10947            if (onSetAlpha((int) (alpha * 255))) {
10948                mPrivateFlags |= PFLAG_ALPHA_SET;
10949                // subclass is handling alpha - don't optimize rendering cache invalidation
10950                invalidateParentCaches();
10951                invalidate(true);
10952            } else {
10953                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10954                invalidateViewProperty(true, false);
10955                mRenderNode.setAlpha(getFinalAlpha());
10956                notifyViewAccessibilityStateChangedIfNeeded(
10957                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10958            }
10959        }
10960    }
10961
10962    /**
10963     * Faster version of setAlpha() which performs the same steps except there are
10964     * no calls to invalidate(). The caller of this function should perform proper invalidation
10965     * on the parent and this object. The return value indicates whether the subclass handles
10966     * alpha (the return value for onSetAlpha()).
10967     *
10968     * @param alpha The new value for the alpha property
10969     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10970     *         the new value for the alpha property is different from the old value
10971     */
10972    boolean setAlphaNoInvalidation(float alpha) {
10973        ensureTransformationInfo();
10974        if (mTransformationInfo.mAlpha != alpha) {
10975            mTransformationInfo.mAlpha = alpha;
10976            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10977            if (subclassHandlesAlpha) {
10978                mPrivateFlags |= PFLAG_ALPHA_SET;
10979                return true;
10980            } else {
10981                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10982                mRenderNode.setAlpha(getFinalAlpha());
10983            }
10984        }
10985        return false;
10986    }
10987
10988    /**
10989     * This property is hidden and intended only for use by the Fade transition, which
10990     * animates it to produce a visual translucency that does not side-effect (or get
10991     * affected by) the real alpha property. This value is composited with the other
10992     * alpha value (and the AlphaAnimation value, when that is present) to produce
10993     * a final visual translucency result, which is what is passed into the DisplayList.
10994     *
10995     * @hide
10996     */
10997    public void setTransitionAlpha(float alpha) {
10998        ensureTransformationInfo();
10999        if (mTransformationInfo.mTransitionAlpha != alpha) {
11000            mTransformationInfo.mTransitionAlpha = alpha;
11001            mPrivateFlags &= ~PFLAG_ALPHA_SET;
11002            invalidateViewProperty(true, false);
11003            mRenderNode.setAlpha(getFinalAlpha());
11004        }
11005    }
11006
11007    /**
11008     * Calculates the visual alpha of this view, which is a combination of the actual
11009     * alpha value and the transitionAlpha value (if set).
11010     */
11011    private float getFinalAlpha() {
11012        if (mTransformationInfo != null) {
11013            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
11014        }
11015        return 1;
11016    }
11017
11018    /**
11019     * This property is hidden and intended only for use by the Fade transition, which
11020     * animates it to produce a visual translucency that does not side-effect (or get
11021     * affected by) the real alpha property. This value is composited with the other
11022     * alpha value (and the AlphaAnimation value, when that is present) to produce
11023     * a final visual translucency result, which is what is passed into the DisplayList.
11024     *
11025     * @hide
11026     */
11027    @ViewDebug.ExportedProperty(category = "drawing")
11028    public float getTransitionAlpha() {
11029        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
11030    }
11031
11032    /**
11033     * Top position of this view relative to its parent.
11034     *
11035     * @return The top of this view, in pixels.
11036     */
11037    @ViewDebug.CapturedViewProperty
11038    public final int getTop() {
11039        return mTop;
11040    }
11041
11042    /**
11043     * Sets the top position of this view relative to its parent. This method is meant to be called
11044     * by the layout system and should not generally be called otherwise, because the property
11045     * may be changed at any time by the layout.
11046     *
11047     * @param top The top of this view, in pixels.
11048     */
11049    public final void setTop(int top) {
11050        if (top != mTop) {
11051            final boolean matrixIsIdentity = hasIdentityMatrix();
11052            if (matrixIsIdentity) {
11053                if (mAttachInfo != null) {
11054                    int minTop;
11055                    int yLoc;
11056                    if (top < mTop) {
11057                        minTop = top;
11058                        yLoc = top - mTop;
11059                    } else {
11060                        minTop = mTop;
11061                        yLoc = 0;
11062                    }
11063                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
11064                }
11065            } else {
11066                // Double-invalidation is necessary to capture view's old and new areas
11067                invalidate(true);
11068            }
11069
11070            int width = mRight - mLeft;
11071            int oldHeight = mBottom - mTop;
11072
11073            mTop = top;
11074            mRenderNode.setTop(mTop);
11075
11076            sizeChange(width, mBottom - mTop, width, oldHeight);
11077
11078            if (!matrixIsIdentity) {
11079                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11080                invalidate(true);
11081            }
11082            mBackgroundSizeChanged = true;
11083            if (mForegroundInfo != null) {
11084                mForegroundInfo.mBoundsChanged = true;
11085            }
11086            invalidateParentIfNeeded();
11087            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11088                // View was rejected last time it was drawn by its parent; this may have changed
11089                invalidateParentIfNeeded();
11090            }
11091        }
11092    }
11093
11094    /**
11095     * Bottom position of this view relative to its parent.
11096     *
11097     * @return The bottom of this view, in pixels.
11098     */
11099    @ViewDebug.CapturedViewProperty
11100    public final int getBottom() {
11101        return mBottom;
11102    }
11103
11104    /**
11105     * True if this view has changed since the last time being drawn.
11106     *
11107     * @return The dirty state of this view.
11108     */
11109    public boolean isDirty() {
11110        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
11111    }
11112
11113    /**
11114     * Sets the bottom position of this view relative to its parent. This method is meant to be
11115     * called by the layout system and should not generally be called otherwise, because the
11116     * property may be changed at any time by the layout.
11117     *
11118     * @param bottom The bottom of this view, in pixels.
11119     */
11120    public final void setBottom(int bottom) {
11121        if (bottom != mBottom) {
11122            final boolean matrixIsIdentity = hasIdentityMatrix();
11123            if (matrixIsIdentity) {
11124                if (mAttachInfo != null) {
11125                    int maxBottom;
11126                    if (bottom < mBottom) {
11127                        maxBottom = mBottom;
11128                    } else {
11129                        maxBottom = bottom;
11130                    }
11131                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
11132                }
11133            } else {
11134                // Double-invalidation is necessary to capture view's old and new areas
11135                invalidate(true);
11136            }
11137
11138            int width = mRight - mLeft;
11139            int oldHeight = mBottom - mTop;
11140
11141            mBottom = bottom;
11142            mRenderNode.setBottom(mBottom);
11143
11144            sizeChange(width, mBottom - mTop, width, oldHeight);
11145
11146            if (!matrixIsIdentity) {
11147                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11148                invalidate(true);
11149            }
11150            mBackgroundSizeChanged = true;
11151            if (mForegroundInfo != null) {
11152                mForegroundInfo.mBoundsChanged = true;
11153            }
11154            invalidateParentIfNeeded();
11155            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11156                // View was rejected last time it was drawn by its parent; this may have changed
11157                invalidateParentIfNeeded();
11158            }
11159        }
11160    }
11161
11162    /**
11163     * Left position of this view relative to its parent.
11164     *
11165     * @return The left edge of this view, in pixels.
11166     */
11167    @ViewDebug.CapturedViewProperty
11168    public final int getLeft() {
11169        return mLeft;
11170    }
11171
11172    /**
11173     * Sets the left position of this view relative to its parent. This method is meant to be called
11174     * by the layout system and should not generally be called otherwise, because the property
11175     * may be changed at any time by the layout.
11176     *
11177     * @param left The left of this view, in pixels.
11178     */
11179    public final void setLeft(int left) {
11180        if (left != mLeft) {
11181            final boolean matrixIsIdentity = hasIdentityMatrix();
11182            if (matrixIsIdentity) {
11183                if (mAttachInfo != null) {
11184                    int minLeft;
11185                    int xLoc;
11186                    if (left < mLeft) {
11187                        minLeft = left;
11188                        xLoc = left - mLeft;
11189                    } else {
11190                        minLeft = mLeft;
11191                        xLoc = 0;
11192                    }
11193                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
11194                }
11195            } else {
11196                // Double-invalidation is necessary to capture view's old and new areas
11197                invalidate(true);
11198            }
11199
11200            int oldWidth = mRight - mLeft;
11201            int height = mBottom - mTop;
11202
11203            mLeft = left;
11204            mRenderNode.setLeft(left);
11205
11206            sizeChange(mRight - mLeft, height, oldWidth, height);
11207
11208            if (!matrixIsIdentity) {
11209                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11210                invalidate(true);
11211            }
11212            mBackgroundSizeChanged = true;
11213            if (mForegroundInfo != null) {
11214                mForegroundInfo.mBoundsChanged = true;
11215            }
11216            invalidateParentIfNeeded();
11217            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11218                // View was rejected last time it was drawn by its parent; this may have changed
11219                invalidateParentIfNeeded();
11220            }
11221        }
11222    }
11223
11224    /**
11225     * Right position of this view relative to its parent.
11226     *
11227     * @return The right edge of this view, in pixels.
11228     */
11229    @ViewDebug.CapturedViewProperty
11230    public final int getRight() {
11231        return mRight;
11232    }
11233
11234    /**
11235     * Sets the right position of this view relative to its parent. This method is meant to be called
11236     * by the layout system and should not generally be called otherwise, because the property
11237     * may be changed at any time by the layout.
11238     *
11239     * @param right The right of this view, in pixels.
11240     */
11241    public final void setRight(int right) {
11242        if (right != mRight) {
11243            final boolean matrixIsIdentity = hasIdentityMatrix();
11244            if (matrixIsIdentity) {
11245                if (mAttachInfo != null) {
11246                    int maxRight;
11247                    if (right < mRight) {
11248                        maxRight = mRight;
11249                    } else {
11250                        maxRight = right;
11251                    }
11252                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
11253                }
11254            } else {
11255                // Double-invalidation is necessary to capture view's old and new areas
11256                invalidate(true);
11257            }
11258
11259            int oldWidth = mRight - mLeft;
11260            int height = mBottom - mTop;
11261
11262            mRight = right;
11263            mRenderNode.setRight(mRight);
11264
11265            sizeChange(mRight - mLeft, height, oldWidth, height);
11266
11267            if (!matrixIsIdentity) {
11268                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11269                invalidate(true);
11270            }
11271            mBackgroundSizeChanged = true;
11272            if (mForegroundInfo != null) {
11273                mForegroundInfo.mBoundsChanged = true;
11274            }
11275            invalidateParentIfNeeded();
11276            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11277                // View was rejected last time it was drawn by its parent; this may have changed
11278                invalidateParentIfNeeded();
11279            }
11280        }
11281    }
11282
11283    /**
11284     * The visual x position of this view, in pixels. This is equivalent to the
11285     * {@link #setTranslationX(float) translationX} property plus the current
11286     * {@link #getLeft() left} property.
11287     *
11288     * @return The visual x position of this view, in pixels.
11289     */
11290    @ViewDebug.ExportedProperty(category = "drawing")
11291    public float getX() {
11292        return mLeft + getTranslationX();
11293    }
11294
11295    /**
11296     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
11297     * {@link #setTranslationX(float) translationX} property to be the difference between
11298     * the x value passed in and the current {@link #getLeft() left} property.
11299     *
11300     * @param x The visual x position of this view, in pixels.
11301     */
11302    public void setX(float x) {
11303        setTranslationX(x - mLeft);
11304    }
11305
11306    /**
11307     * The visual y position of this view, in pixels. This is equivalent to the
11308     * {@link #setTranslationY(float) translationY} property plus the current
11309     * {@link #getTop() top} property.
11310     *
11311     * @return The visual y position of this view, in pixels.
11312     */
11313    @ViewDebug.ExportedProperty(category = "drawing")
11314    public float getY() {
11315        return mTop + getTranslationY();
11316    }
11317
11318    /**
11319     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
11320     * {@link #setTranslationY(float) translationY} property to be the difference between
11321     * the y value passed in and the current {@link #getTop() top} property.
11322     *
11323     * @param y The visual y position of this view, in pixels.
11324     */
11325    public void setY(float y) {
11326        setTranslationY(y - mTop);
11327    }
11328
11329    /**
11330     * The visual z position of this view, in pixels. This is equivalent to the
11331     * {@link #setTranslationZ(float) translationZ} property plus the current
11332     * {@link #getElevation() elevation} property.
11333     *
11334     * @return The visual z position of this view, in pixels.
11335     */
11336    @ViewDebug.ExportedProperty(category = "drawing")
11337    public float getZ() {
11338        return getElevation() + getTranslationZ();
11339    }
11340
11341    /**
11342     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
11343     * {@link #setTranslationZ(float) translationZ} property to be the difference between
11344     * the x value passed in and the current {@link #getElevation() elevation} property.
11345     *
11346     * @param z The visual z position of this view, in pixels.
11347     */
11348    public void setZ(float z) {
11349        setTranslationZ(z - getElevation());
11350    }
11351
11352    /**
11353     * The base elevation of this view relative to its parent, in pixels.
11354     *
11355     * @return The base depth position of the view, in pixels.
11356     */
11357    @ViewDebug.ExportedProperty(category = "drawing")
11358    public float getElevation() {
11359        return mRenderNode.getElevation();
11360    }
11361
11362    /**
11363     * Sets the base elevation of this view, in pixels.
11364     *
11365     * @attr ref android.R.styleable#View_elevation
11366     */
11367    public void setElevation(float elevation) {
11368        if (elevation != getElevation()) {
11369            invalidateViewProperty(true, false);
11370            mRenderNode.setElevation(elevation);
11371            invalidateViewProperty(false, true);
11372
11373            invalidateParentIfNeededAndWasQuickRejected();
11374        }
11375    }
11376
11377    /**
11378     * The horizontal location of this view relative to its {@link #getLeft() left} position.
11379     * This position is post-layout, in addition to wherever the object's
11380     * layout placed it.
11381     *
11382     * @return The horizontal position of this view relative to its left position, in pixels.
11383     */
11384    @ViewDebug.ExportedProperty(category = "drawing")
11385    public float getTranslationX() {
11386        return mRenderNode.getTranslationX();
11387    }
11388
11389    /**
11390     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11391     * This effectively positions the object post-layout, in addition to wherever the object's
11392     * layout placed it.
11393     *
11394     * @param translationX The horizontal position of this view relative to its left position,
11395     * in pixels.
11396     *
11397     * @attr ref android.R.styleable#View_translationX
11398     */
11399    public void setTranslationX(float translationX) {
11400        if (translationX != getTranslationX()) {
11401            invalidateViewProperty(true, false);
11402            mRenderNode.setTranslationX(translationX);
11403            invalidateViewProperty(false, true);
11404
11405            invalidateParentIfNeededAndWasQuickRejected();
11406            notifySubtreeAccessibilityStateChangedIfNeeded();
11407        }
11408    }
11409
11410    /**
11411     * The vertical location of this view relative to its {@link #getTop() top} position.
11412     * This position is post-layout, in addition to wherever the object's
11413     * layout placed it.
11414     *
11415     * @return The vertical position of this view relative to its top position,
11416     * in pixels.
11417     */
11418    @ViewDebug.ExportedProperty(category = "drawing")
11419    public float getTranslationY() {
11420        return mRenderNode.getTranslationY();
11421    }
11422
11423    /**
11424     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11425     * This effectively positions the object post-layout, in addition to wherever the object's
11426     * layout placed it.
11427     *
11428     * @param translationY The vertical position of this view relative to its top position,
11429     * in pixels.
11430     *
11431     * @attr ref android.R.styleable#View_translationY
11432     */
11433    public void setTranslationY(float translationY) {
11434        if (translationY != getTranslationY()) {
11435            invalidateViewProperty(true, false);
11436            mRenderNode.setTranslationY(translationY);
11437            invalidateViewProperty(false, true);
11438
11439            invalidateParentIfNeededAndWasQuickRejected();
11440            notifySubtreeAccessibilityStateChangedIfNeeded();
11441        }
11442    }
11443
11444    /**
11445     * The depth location of this view relative to its {@link #getElevation() elevation}.
11446     *
11447     * @return The depth of this view relative to its elevation.
11448     */
11449    @ViewDebug.ExportedProperty(category = "drawing")
11450    public float getTranslationZ() {
11451        return mRenderNode.getTranslationZ();
11452    }
11453
11454    /**
11455     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11456     *
11457     * @attr ref android.R.styleable#View_translationZ
11458     */
11459    public void setTranslationZ(float translationZ) {
11460        if (translationZ != getTranslationZ()) {
11461            invalidateViewProperty(true, false);
11462            mRenderNode.setTranslationZ(translationZ);
11463            invalidateViewProperty(false, true);
11464
11465            invalidateParentIfNeededAndWasQuickRejected();
11466        }
11467    }
11468
11469    /** @hide */
11470    public void setAnimationMatrix(Matrix matrix) {
11471        invalidateViewProperty(true, false);
11472        mRenderNode.setAnimationMatrix(matrix);
11473        invalidateViewProperty(false, true);
11474
11475        invalidateParentIfNeededAndWasQuickRejected();
11476    }
11477
11478    /**
11479     * Returns the current StateListAnimator if exists.
11480     *
11481     * @return StateListAnimator or null if it does not exists
11482     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11483     */
11484    public StateListAnimator getStateListAnimator() {
11485        return mStateListAnimator;
11486    }
11487
11488    /**
11489     * Attaches the provided StateListAnimator to this View.
11490     * <p>
11491     * Any previously attached StateListAnimator will be detached.
11492     *
11493     * @param stateListAnimator The StateListAnimator to update the view
11494     * @see {@link android.animation.StateListAnimator}
11495     */
11496    public void setStateListAnimator(StateListAnimator stateListAnimator) {
11497        if (mStateListAnimator == stateListAnimator) {
11498            return;
11499        }
11500        if (mStateListAnimator != null) {
11501            mStateListAnimator.setTarget(null);
11502        }
11503        mStateListAnimator = stateListAnimator;
11504        if (stateListAnimator != null) {
11505            stateListAnimator.setTarget(this);
11506            if (isAttachedToWindow()) {
11507                stateListAnimator.setState(getDrawableState());
11508            }
11509        }
11510    }
11511
11512    /**
11513     * Returns whether the Outline should be used to clip the contents of the View.
11514     * <p>
11515     * Note that this flag will only be respected if the View's Outline returns true from
11516     * {@link Outline#canClip()}.
11517     *
11518     * @see #setOutlineProvider(ViewOutlineProvider)
11519     * @see #setClipToOutline(boolean)
11520     */
11521    public final boolean getClipToOutline() {
11522        return mRenderNode.getClipToOutline();
11523    }
11524
11525    /**
11526     * Sets whether the View's Outline should be used to clip the contents of the View.
11527     * <p>
11528     * Only a single non-rectangular clip can be applied on a View at any time.
11529     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
11530     * circular reveal} animation take priority over Outline clipping, and
11531     * child Outline clipping takes priority over Outline clipping done by a
11532     * parent.
11533     * <p>
11534     * Note that this flag will only be respected if the View's Outline returns true from
11535     * {@link Outline#canClip()}.
11536     *
11537     * @see #setOutlineProvider(ViewOutlineProvider)
11538     * @see #getClipToOutline()
11539     */
11540    public void setClipToOutline(boolean clipToOutline) {
11541        damageInParent();
11542        if (getClipToOutline() != clipToOutline) {
11543            mRenderNode.setClipToOutline(clipToOutline);
11544        }
11545    }
11546
11547    // correspond to the enum values of View_outlineProvider
11548    private static final int PROVIDER_BACKGROUND = 0;
11549    private static final int PROVIDER_NONE = 1;
11550    private static final int PROVIDER_BOUNDS = 2;
11551    private static final int PROVIDER_PADDED_BOUNDS = 3;
11552    private void setOutlineProviderFromAttribute(int providerInt) {
11553        switch (providerInt) {
11554            case PROVIDER_BACKGROUND:
11555                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
11556                break;
11557            case PROVIDER_NONE:
11558                setOutlineProvider(null);
11559                break;
11560            case PROVIDER_BOUNDS:
11561                setOutlineProvider(ViewOutlineProvider.BOUNDS);
11562                break;
11563            case PROVIDER_PADDED_BOUNDS:
11564                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
11565                break;
11566        }
11567    }
11568
11569    /**
11570     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
11571     * the shape of the shadow it casts, and enables outline clipping.
11572     * <p>
11573     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
11574     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
11575     * outline provider with this method allows this behavior to be overridden.
11576     * <p>
11577     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
11578     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
11579     * <p>
11580     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
11581     *
11582     * @see #setClipToOutline(boolean)
11583     * @see #getClipToOutline()
11584     * @see #getOutlineProvider()
11585     */
11586    public void setOutlineProvider(ViewOutlineProvider provider) {
11587        mOutlineProvider = provider;
11588        invalidateOutline();
11589    }
11590
11591    /**
11592     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
11593     * that defines the shape of the shadow it casts, and enables outline clipping.
11594     *
11595     * @see #setOutlineProvider(ViewOutlineProvider)
11596     */
11597    public ViewOutlineProvider getOutlineProvider() {
11598        return mOutlineProvider;
11599    }
11600
11601    /**
11602     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
11603     *
11604     * @see #setOutlineProvider(ViewOutlineProvider)
11605     */
11606    public void invalidateOutline() {
11607        rebuildOutline();
11608
11609        notifySubtreeAccessibilityStateChangedIfNeeded();
11610        invalidateViewProperty(false, false);
11611    }
11612
11613    /**
11614     * Internal version of {@link #invalidateOutline()} which invalidates the
11615     * outline without invalidating the view itself. This is intended to be called from
11616     * within methods in the View class itself which are the result of the view being
11617     * invalidated already. For example, when we are drawing the background of a View,
11618     * we invalidate the outline in case it changed in the meantime, but we do not
11619     * need to invalidate the view because we're already drawing the background as part
11620     * of drawing the view in response to an earlier invalidation of the view.
11621     */
11622    private void rebuildOutline() {
11623        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
11624        if (mAttachInfo == null) return;
11625
11626        if (mOutlineProvider == null) {
11627            // no provider, remove outline
11628            mRenderNode.setOutline(null);
11629        } else {
11630            final Outline outline = mAttachInfo.mTmpOutline;
11631            outline.setEmpty();
11632            outline.setAlpha(1.0f);
11633
11634            mOutlineProvider.getOutline(this, outline);
11635            mRenderNode.setOutline(outline);
11636        }
11637    }
11638
11639    /**
11640     * HierarchyViewer only
11641     *
11642     * @hide
11643     */
11644    @ViewDebug.ExportedProperty(category = "drawing")
11645    public boolean hasShadow() {
11646        return mRenderNode.hasShadow();
11647    }
11648
11649
11650    /** @hide */
11651    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
11652        mRenderNode.setRevealClip(shouldClip, x, y, radius);
11653        invalidateViewProperty(false, false);
11654    }
11655
11656    /**
11657     * Hit rectangle in parent's coordinates
11658     *
11659     * @param outRect The hit rectangle of the view.
11660     */
11661    public void getHitRect(Rect outRect) {
11662        if (hasIdentityMatrix() || mAttachInfo == null) {
11663            outRect.set(mLeft, mTop, mRight, mBottom);
11664        } else {
11665            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11666            tmpRect.set(0, 0, getWidth(), getHeight());
11667            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
11668            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11669                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11670        }
11671    }
11672
11673    /**
11674     * Determines whether the given point, in local coordinates is inside the view.
11675     */
11676    /*package*/ final boolean pointInView(float localX, float localY) {
11677        return localX >= 0 && localX < (mRight - mLeft)
11678                && localY >= 0 && localY < (mBottom - mTop);
11679    }
11680
11681    /**
11682     * Utility method to determine whether the given point, in local coordinates,
11683     * is inside the view, where the area of the view is expanded by the slop factor.
11684     * This method is called while processing touch-move events to determine if the event
11685     * is still within the view.
11686     *
11687     * @hide
11688     */
11689    public boolean pointInView(float localX, float localY, float slop) {
11690        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11691                localY < ((mBottom - mTop) + slop);
11692    }
11693
11694    /**
11695     * When a view has focus and the user navigates away from it, the next view is searched for
11696     * starting from the rectangle filled in by this method.
11697     *
11698     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11699     * of the view.  However, if your view maintains some idea of internal selection,
11700     * such as a cursor, or a selected row or column, you should override this method and
11701     * fill in a more specific rectangle.
11702     *
11703     * @param r The rectangle to fill in, in this view's coordinates.
11704     */
11705    public void getFocusedRect(Rect r) {
11706        getDrawingRect(r);
11707    }
11708
11709    /**
11710     * If some part of this view is not clipped by any of its parents, then
11711     * return that area in r in global (root) coordinates. To convert r to local
11712     * coordinates (without taking possible View rotations into account), offset
11713     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11714     * If the view is completely clipped or translated out, return false.
11715     *
11716     * @param r If true is returned, r holds the global coordinates of the
11717     *        visible portion of this view.
11718     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11719     *        between this view and its root. globalOffet may be null.
11720     * @return true if r is non-empty (i.e. part of the view is visible at the
11721     *         root level.
11722     */
11723    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11724        int width = mRight - mLeft;
11725        int height = mBottom - mTop;
11726        if (width > 0 && height > 0) {
11727            r.set(0, 0, width, height);
11728            if (globalOffset != null) {
11729                globalOffset.set(-mScrollX, -mScrollY);
11730            }
11731            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11732        }
11733        return false;
11734    }
11735
11736    public final boolean getGlobalVisibleRect(Rect r) {
11737        return getGlobalVisibleRect(r, null);
11738    }
11739
11740    public final boolean getLocalVisibleRect(Rect r) {
11741        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11742        if (getGlobalVisibleRect(r, offset)) {
11743            r.offset(-offset.x, -offset.y); // make r local
11744            return true;
11745        }
11746        return false;
11747    }
11748
11749    /**
11750     * Offset this view's vertical location by the specified number of pixels.
11751     *
11752     * @param offset the number of pixels to offset the view by
11753     */
11754    public void offsetTopAndBottom(int offset) {
11755        if (offset != 0) {
11756            final boolean matrixIsIdentity = hasIdentityMatrix();
11757            if (matrixIsIdentity) {
11758                if (isHardwareAccelerated()) {
11759                    invalidateViewProperty(false, false);
11760                } else {
11761                    final ViewParent p = mParent;
11762                    if (p != null && mAttachInfo != null) {
11763                        final Rect r = mAttachInfo.mTmpInvalRect;
11764                        int minTop;
11765                        int maxBottom;
11766                        int yLoc;
11767                        if (offset < 0) {
11768                            minTop = mTop + offset;
11769                            maxBottom = mBottom;
11770                            yLoc = offset;
11771                        } else {
11772                            minTop = mTop;
11773                            maxBottom = mBottom + offset;
11774                            yLoc = 0;
11775                        }
11776                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11777                        p.invalidateChild(this, r);
11778                    }
11779                }
11780            } else {
11781                invalidateViewProperty(false, false);
11782            }
11783
11784            mTop += offset;
11785            mBottom += offset;
11786            mRenderNode.offsetTopAndBottom(offset);
11787            if (isHardwareAccelerated()) {
11788                invalidateViewProperty(false, false);
11789            } else {
11790                if (!matrixIsIdentity) {
11791                    invalidateViewProperty(false, true);
11792                }
11793                invalidateParentIfNeeded();
11794            }
11795            notifySubtreeAccessibilityStateChangedIfNeeded();
11796        }
11797    }
11798
11799    /**
11800     * Offset this view's horizontal location by the specified amount of pixels.
11801     *
11802     * @param offset the number of pixels to offset the view by
11803     */
11804    public void offsetLeftAndRight(int offset) {
11805        if (offset != 0) {
11806            final boolean matrixIsIdentity = hasIdentityMatrix();
11807            if (matrixIsIdentity) {
11808                if (isHardwareAccelerated()) {
11809                    invalidateViewProperty(false, false);
11810                } else {
11811                    final ViewParent p = mParent;
11812                    if (p != null && mAttachInfo != null) {
11813                        final Rect r = mAttachInfo.mTmpInvalRect;
11814                        int minLeft;
11815                        int maxRight;
11816                        if (offset < 0) {
11817                            minLeft = mLeft + offset;
11818                            maxRight = mRight;
11819                        } else {
11820                            minLeft = mLeft;
11821                            maxRight = mRight + offset;
11822                        }
11823                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11824                        p.invalidateChild(this, r);
11825                    }
11826                }
11827            } else {
11828                invalidateViewProperty(false, false);
11829            }
11830
11831            mLeft += offset;
11832            mRight += offset;
11833            mRenderNode.offsetLeftAndRight(offset);
11834            if (isHardwareAccelerated()) {
11835                invalidateViewProperty(false, false);
11836            } else {
11837                if (!matrixIsIdentity) {
11838                    invalidateViewProperty(false, true);
11839                }
11840                invalidateParentIfNeeded();
11841            }
11842            notifySubtreeAccessibilityStateChangedIfNeeded();
11843        }
11844    }
11845
11846    /**
11847     * Get the LayoutParams associated with this view. All views should have
11848     * layout parameters. These supply parameters to the <i>parent</i> of this
11849     * view specifying how it should be arranged. There are many subclasses of
11850     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11851     * of ViewGroup that are responsible for arranging their children.
11852     *
11853     * This method may return null if this View is not attached to a parent
11854     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11855     * was not invoked successfully. When a View is attached to a parent
11856     * ViewGroup, this method must not return null.
11857     *
11858     * @return The LayoutParams associated with this view, or null if no
11859     *         parameters have been set yet
11860     */
11861    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11862    public ViewGroup.LayoutParams getLayoutParams() {
11863        return mLayoutParams;
11864    }
11865
11866    /**
11867     * Set the layout parameters associated with this view. These supply
11868     * parameters to the <i>parent</i> of this view specifying how it should be
11869     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11870     * correspond to the different subclasses of ViewGroup that are responsible
11871     * for arranging their children.
11872     *
11873     * @param params The layout parameters for this view, cannot be null
11874     */
11875    public void setLayoutParams(ViewGroup.LayoutParams params) {
11876        if (params == null) {
11877            throw new NullPointerException("Layout parameters cannot be null");
11878        }
11879        mLayoutParams = params;
11880        resolveLayoutParams();
11881        if (mParent instanceof ViewGroup) {
11882            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11883        }
11884        requestLayout();
11885    }
11886
11887    /**
11888     * Resolve the layout parameters depending on the resolved layout direction
11889     *
11890     * @hide
11891     */
11892    public void resolveLayoutParams() {
11893        if (mLayoutParams != null) {
11894            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11895        }
11896    }
11897
11898    /**
11899     * Set the scrolled position of your view. This will cause a call to
11900     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11901     * invalidated.
11902     * @param x the x position to scroll to
11903     * @param y the y position to scroll to
11904     */
11905    public void scrollTo(int x, int y) {
11906        if (mScrollX != x || mScrollY != y) {
11907            int oldX = mScrollX;
11908            int oldY = mScrollY;
11909            mScrollX = x;
11910            mScrollY = y;
11911            invalidateParentCaches();
11912            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11913            if (!awakenScrollBars()) {
11914                postInvalidateOnAnimation();
11915            }
11916        }
11917    }
11918
11919    /**
11920     * Move the scrolled position of your view. This will cause a call to
11921     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11922     * invalidated.
11923     * @param x the amount of pixels to scroll by horizontally
11924     * @param y the amount of pixels to scroll by vertically
11925     */
11926    public void scrollBy(int x, int y) {
11927        scrollTo(mScrollX + x, mScrollY + y);
11928    }
11929
11930    /**
11931     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11932     * animation to fade the scrollbars out after a default delay. If a subclass
11933     * provides animated scrolling, the start delay should equal the duration
11934     * of the scrolling animation.</p>
11935     *
11936     * <p>The animation starts only if at least one of the scrollbars is
11937     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11938     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11939     * this method returns true, and false otherwise. If the animation is
11940     * started, this method calls {@link #invalidate()}; in that case the
11941     * caller should not call {@link #invalidate()}.</p>
11942     *
11943     * <p>This method should be invoked every time a subclass directly updates
11944     * the scroll parameters.</p>
11945     *
11946     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11947     * and {@link #scrollTo(int, int)}.</p>
11948     *
11949     * @return true if the animation is played, false otherwise
11950     *
11951     * @see #awakenScrollBars(int)
11952     * @see #scrollBy(int, int)
11953     * @see #scrollTo(int, int)
11954     * @see #isHorizontalScrollBarEnabled()
11955     * @see #isVerticalScrollBarEnabled()
11956     * @see #setHorizontalScrollBarEnabled(boolean)
11957     * @see #setVerticalScrollBarEnabled(boolean)
11958     */
11959    protected boolean awakenScrollBars() {
11960        return mScrollCache != null &&
11961                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11962    }
11963
11964    /**
11965     * Trigger the scrollbars to draw.
11966     * This method differs from awakenScrollBars() only in its default duration.
11967     * initialAwakenScrollBars() will show the scroll bars for longer than
11968     * usual to give the user more of a chance to notice them.
11969     *
11970     * @return true if the animation is played, false otherwise.
11971     */
11972    private boolean initialAwakenScrollBars() {
11973        return mScrollCache != null &&
11974                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11975    }
11976
11977    /**
11978     * <p>
11979     * Trigger the scrollbars to draw. When invoked this method starts an
11980     * animation to fade the scrollbars out after a fixed delay. If a subclass
11981     * provides animated scrolling, the start delay should equal the duration of
11982     * the scrolling animation.
11983     * </p>
11984     *
11985     * <p>
11986     * The animation starts only if at least one of the scrollbars is enabled,
11987     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11988     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11989     * this method returns true, and false otherwise. If the animation is
11990     * started, this method calls {@link #invalidate()}; in that case the caller
11991     * should not call {@link #invalidate()}.
11992     * </p>
11993     *
11994     * <p>
11995     * This method should be invoked every time a subclass directly updates the
11996     * scroll parameters.
11997     * </p>
11998     *
11999     * @param startDelay the delay, in milliseconds, after which the animation
12000     *        should start; when the delay is 0, the animation starts
12001     *        immediately
12002     * @return true if the animation is played, false otherwise
12003     *
12004     * @see #scrollBy(int, int)
12005     * @see #scrollTo(int, int)
12006     * @see #isHorizontalScrollBarEnabled()
12007     * @see #isVerticalScrollBarEnabled()
12008     * @see #setHorizontalScrollBarEnabled(boolean)
12009     * @see #setVerticalScrollBarEnabled(boolean)
12010     */
12011    protected boolean awakenScrollBars(int startDelay) {
12012        return awakenScrollBars(startDelay, true);
12013    }
12014
12015    /**
12016     * <p>
12017     * Trigger the scrollbars to draw. When invoked this method starts an
12018     * animation to fade the scrollbars out after a fixed delay. If a subclass
12019     * provides animated scrolling, the start delay should equal the duration of
12020     * the scrolling animation.
12021     * </p>
12022     *
12023     * <p>
12024     * The animation starts only if at least one of the scrollbars is enabled,
12025     * as specified by {@link #isHorizontalScrollBarEnabled()} and
12026     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12027     * this method returns true, and false otherwise. If the animation is
12028     * started, this method calls {@link #invalidate()} if the invalidate parameter
12029     * is set to true; in that case the caller
12030     * should not call {@link #invalidate()}.
12031     * </p>
12032     *
12033     * <p>
12034     * This method should be invoked every time a subclass directly updates the
12035     * scroll parameters.
12036     * </p>
12037     *
12038     * @param startDelay the delay, in milliseconds, after which the animation
12039     *        should start; when the delay is 0, the animation starts
12040     *        immediately
12041     *
12042     * @param invalidate Whether this method should call invalidate
12043     *
12044     * @return true if the animation is played, false otherwise
12045     *
12046     * @see #scrollBy(int, int)
12047     * @see #scrollTo(int, int)
12048     * @see #isHorizontalScrollBarEnabled()
12049     * @see #isVerticalScrollBarEnabled()
12050     * @see #setHorizontalScrollBarEnabled(boolean)
12051     * @see #setVerticalScrollBarEnabled(boolean)
12052     */
12053    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
12054        final ScrollabilityCache scrollCache = mScrollCache;
12055
12056        if (scrollCache == null || !scrollCache.fadeScrollBars) {
12057            return false;
12058        }
12059
12060        if (scrollCache.scrollBar == null) {
12061            scrollCache.scrollBar = new ScrollBarDrawable();
12062            scrollCache.scrollBar.setCallback(this);
12063            scrollCache.scrollBar.setState(getDrawableState());
12064        }
12065
12066        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
12067
12068            if (invalidate) {
12069                // Invalidate to show the scrollbars
12070                postInvalidateOnAnimation();
12071            }
12072
12073            if (scrollCache.state == ScrollabilityCache.OFF) {
12074                // FIXME: this is copied from WindowManagerService.
12075                // We should get this value from the system when it
12076                // is possible to do so.
12077                final int KEY_REPEAT_FIRST_DELAY = 750;
12078                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
12079            }
12080
12081            // Tell mScrollCache when we should start fading. This may
12082            // extend the fade start time if one was already scheduled
12083            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
12084            scrollCache.fadeStartTime = fadeStartTime;
12085            scrollCache.state = ScrollabilityCache.ON;
12086
12087            // Schedule our fader to run, unscheduling any old ones first
12088            if (mAttachInfo != null) {
12089                mAttachInfo.mHandler.removeCallbacks(scrollCache);
12090                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
12091            }
12092
12093            return true;
12094        }
12095
12096        return false;
12097    }
12098
12099    /**
12100     * Do not invalidate views which are not visible and which are not running an animation. They
12101     * will not get drawn and they should not set dirty flags as if they will be drawn
12102     */
12103    private boolean skipInvalidate() {
12104        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
12105                (!(mParent instanceof ViewGroup) ||
12106                        !((ViewGroup) mParent).isViewTransitioning(this));
12107    }
12108
12109    /**
12110     * Mark the area defined by dirty as needing to be drawn. If the view is
12111     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12112     * point in the future.
12113     * <p>
12114     * This must be called from a UI thread. To call from a non-UI thread, call
12115     * {@link #postInvalidate()}.
12116     * <p>
12117     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
12118     * {@code dirty}.
12119     *
12120     * @param dirty the rectangle representing the bounds of the dirty region
12121     */
12122    public void invalidate(Rect dirty) {
12123        final int scrollX = mScrollX;
12124        final int scrollY = mScrollY;
12125        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
12126                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
12127    }
12128
12129    /**
12130     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
12131     * coordinates of the dirty rect are relative to the view. If the view is
12132     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12133     * point in the future.
12134     * <p>
12135     * This must be called from a UI thread. To call from a non-UI thread, call
12136     * {@link #postInvalidate()}.
12137     *
12138     * @param l the left position of the dirty region
12139     * @param t the top position of the dirty region
12140     * @param r the right position of the dirty region
12141     * @param b the bottom position of the dirty region
12142     */
12143    public void invalidate(int l, int t, int r, int b) {
12144        final int scrollX = mScrollX;
12145        final int scrollY = mScrollY;
12146        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
12147    }
12148
12149    /**
12150     * Invalidate the whole view. If the view is visible,
12151     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
12152     * the future.
12153     * <p>
12154     * This must be called from a UI thread. To call from a non-UI thread, call
12155     * {@link #postInvalidate()}.
12156     */
12157    public void invalidate() {
12158        invalidate(true);
12159    }
12160
12161    /**
12162     * This is where the invalidate() work actually happens. A full invalidate()
12163     * causes the drawing cache to be invalidated, but this function can be
12164     * called with invalidateCache set to false to skip that invalidation step
12165     * for cases that do not need it (for example, a component that remains at
12166     * the same dimensions with the same content).
12167     *
12168     * @param invalidateCache Whether the drawing cache for this view should be
12169     *            invalidated as well. This is usually true for a full
12170     *            invalidate, but may be set to false if the View's contents or
12171     *            dimensions have not changed.
12172     */
12173    void invalidate(boolean invalidateCache) {
12174        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
12175    }
12176
12177    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
12178            boolean fullInvalidate) {
12179        if (mGhostView != null) {
12180            mGhostView.invalidate(true);
12181            return;
12182        }
12183
12184        if (skipInvalidate()) {
12185            return;
12186        }
12187
12188        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
12189                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
12190                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
12191                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
12192            if (fullInvalidate) {
12193                mLastIsOpaque = isOpaque();
12194                mPrivateFlags &= ~PFLAG_DRAWN;
12195            }
12196
12197            mPrivateFlags |= PFLAG_DIRTY;
12198
12199            if (invalidateCache) {
12200                mPrivateFlags |= PFLAG_INVALIDATED;
12201                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12202            }
12203
12204            // Propagate the damage rectangle to the parent view.
12205            final AttachInfo ai = mAttachInfo;
12206            final ViewParent p = mParent;
12207            if (p != null && ai != null && l < r && t < b) {
12208                final Rect damage = ai.mTmpInvalRect;
12209                damage.set(l, t, r, b);
12210                p.invalidateChild(this, damage);
12211            }
12212
12213            // Damage the entire projection receiver, if necessary.
12214            if (mBackground != null && mBackground.isProjected()) {
12215                final View receiver = getProjectionReceiver();
12216                if (receiver != null) {
12217                    receiver.damageInParent();
12218                }
12219            }
12220
12221            // Damage the entire IsolatedZVolume receiving this view's shadow.
12222            if (isHardwareAccelerated() && getZ() != 0) {
12223                damageShadowReceiver();
12224            }
12225        }
12226    }
12227
12228    /**
12229     * @return this view's projection receiver, or {@code null} if none exists
12230     */
12231    private View getProjectionReceiver() {
12232        ViewParent p = getParent();
12233        while (p != null && p instanceof View) {
12234            final View v = (View) p;
12235            if (v.isProjectionReceiver()) {
12236                return v;
12237            }
12238            p = p.getParent();
12239        }
12240
12241        return null;
12242    }
12243
12244    /**
12245     * @return whether the view is a projection receiver
12246     */
12247    private boolean isProjectionReceiver() {
12248        return mBackground != null;
12249    }
12250
12251    /**
12252     * Damage area of the screen that can be covered by this View's shadow.
12253     *
12254     * This method will guarantee that any changes to shadows cast by a View
12255     * are damaged on the screen for future redraw.
12256     */
12257    private void damageShadowReceiver() {
12258        final AttachInfo ai = mAttachInfo;
12259        if (ai != null) {
12260            ViewParent p = getParent();
12261            if (p != null && p instanceof ViewGroup) {
12262                final ViewGroup vg = (ViewGroup) p;
12263                vg.damageInParent();
12264            }
12265        }
12266    }
12267
12268    /**
12269     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
12270     * set any flags or handle all of the cases handled by the default invalidation methods.
12271     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
12272     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
12273     * walk up the hierarchy, transforming the dirty rect as necessary.
12274     *
12275     * The method also handles normal invalidation logic if display list properties are not
12276     * being used in this view. The invalidateParent and forceRedraw flags are used by that
12277     * backup approach, to handle these cases used in the various property-setting methods.
12278     *
12279     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
12280     * are not being used in this view
12281     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
12282     * list properties are not being used in this view
12283     */
12284    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
12285        if (!isHardwareAccelerated()
12286                || !mRenderNode.isValid()
12287                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
12288            if (invalidateParent) {
12289                invalidateParentCaches();
12290            }
12291            if (forceRedraw) {
12292                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12293            }
12294            invalidate(false);
12295        } else {
12296            damageInParent();
12297        }
12298        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
12299            damageShadowReceiver();
12300        }
12301    }
12302
12303    /**
12304     * Tells the parent view to damage this view's bounds.
12305     *
12306     * @hide
12307     */
12308    protected void damageInParent() {
12309        final AttachInfo ai = mAttachInfo;
12310        final ViewParent p = mParent;
12311        if (p != null && ai != null) {
12312            final Rect r = ai.mTmpInvalRect;
12313            r.set(0, 0, mRight - mLeft, mBottom - mTop);
12314            if (mParent instanceof ViewGroup) {
12315                ((ViewGroup) mParent).damageChild(this, r);
12316            } else {
12317                mParent.invalidateChild(this, r);
12318            }
12319        }
12320    }
12321
12322    /**
12323     * Utility method to transform a given Rect by the current matrix of this view.
12324     */
12325    void transformRect(final Rect rect) {
12326        if (!getMatrix().isIdentity()) {
12327            RectF boundingRect = mAttachInfo.mTmpTransformRect;
12328            boundingRect.set(rect);
12329            getMatrix().mapRect(boundingRect);
12330            rect.set((int) Math.floor(boundingRect.left),
12331                    (int) Math.floor(boundingRect.top),
12332                    (int) Math.ceil(boundingRect.right),
12333                    (int) Math.ceil(boundingRect.bottom));
12334        }
12335    }
12336
12337    /**
12338     * Used to indicate that the parent of this view should clear its caches. This functionality
12339     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12340     * which is necessary when various parent-managed properties of the view change, such as
12341     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
12342     * clears the parent caches and does not causes an invalidate event.
12343     *
12344     * @hide
12345     */
12346    protected void invalidateParentCaches() {
12347        if (mParent instanceof View) {
12348            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
12349        }
12350    }
12351
12352    /**
12353     * Used to indicate that the parent of this view should be invalidated. This functionality
12354     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12355     * which is necessary when various parent-managed properties of the view change, such as
12356     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
12357     * an invalidation event to the parent.
12358     *
12359     * @hide
12360     */
12361    protected void invalidateParentIfNeeded() {
12362        if (isHardwareAccelerated() && mParent instanceof View) {
12363            ((View) mParent).invalidate(true);
12364        }
12365    }
12366
12367    /**
12368     * @hide
12369     */
12370    protected void invalidateParentIfNeededAndWasQuickRejected() {
12371        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
12372            // View was rejected last time it was drawn by its parent; this may have changed
12373            invalidateParentIfNeeded();
12374        }
12375    }
12376
12377    /**
12378     * Indicates whether this View is opaque. An opaque View guarantees that it will
12379     * draw all the pixels overlapping its bounds using a fully opaque color.
12380     *
12381     * Subclasses of View should override this method whenever possible to indicate
12382     * whether an instance is opaque. Opaque Views are treated in a special way by
12383     * the View hierarchy, possibly allowing it to perform optimizations during
12384     * invalidate/draw passes.
12385     *
12386     * @return True if this View is guaranteed to be fully opaque, false otherwise.
12387     */
12388    @ViewDebug.ExportedProperty(category = "drawing")
12389    public boolean isOpaque() {
12390        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
12391                getFinalAlpha() >= 1.0f;
12392    }
12393
12394    /**
12395     * @hide
12396     */
12397    protected void computeOpaqueFlags() {
12398        // Opaque if:
12399        //   - Has a background
12400        //   - Background is opaque
12401        //   - Doesn't have scrollbars or scrollbars overlay
12402
12403        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
12404            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
12405        } else {
12406            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
12407        }
12408
12409        final int flags = mViewFlags;
12410        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
12411                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
12412                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
12413            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
12414        } else {
12415            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
12416        }
12417    }
12418
12419    /**
12420     * @hide
12421     */
12422    protected boolean hasOpaqueScrollbars() {
12423        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
12424    }
12425
12426    /**
12427     * @return A handler associated with the thread running the View. This
12428     * handler can be used to pump events in the UI events queue.
12429     */
12430    public Handler getHandler() {
12431        final AttachInfo attachInfo = mAttachInfo;
12432        if (attachInfo != null) {
12433            return attachInfo.mHandler;
12434        }
12435        return null;
12436    }
12437
12438    /**
12439     * Gets the view root associated with the View.
12440     * @return The view root, or null if none.
12441     * @hide
12442     */
12443    public ViewRootImpl getViewRootImpl() {
12444        if (mAttachInfo != null) {
12445            return mAttachInfo.mViewRootImpl;
12446        }
12447        return null;
12448    }
12449
12450    /**
12451     * @hide
12452     */
12453    public HardwareRenderer getHardwareRenderer() {
12454        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
12455    }
12456
12457    /**
12458     * <p>Causes the Runnable to be added to the message queue.
12459     * The runnable will be run on the user interface thread.</p>
12460     *
12461     * @param action The Runnable that will be executed.
12462     *
12463     * @return Returns true if the Runnable was successfully placed in to the
12464     *         message queue.  Returns false on failure, usually because the
12465     *         looper processing the message queue is exiting.
12466     *
12467     * @see #postDelayed
12468     * @see #removeCallbacks
12469     */
12470    public boolean post(Runnable action) {
12471        final AttachInfo attachInfo = mAttachInfo;
12472        if (attachInfo != null) {
12473            return attachInfo.mHandler.post(action);
12474        }
12475        // Assume that post will succeed later
12476        ViewRootImpl.getRunQueue().post(action);
12477        return true;
12478    }
12479
12480    /**
12481     * <p>Causes the Runnable to be added to the message queue, to be run
12482     * after the specified amount of time elapses.
12483     * The runnable will be run on the user interface thread.</p>
12484     *
12485     * @param action The Runnable that will be executed.
12486     * @param delayMillis The delay (in milliseconds) until the Runnable
12487     *        will be executed.
12488     *
12489     * @return true if the Runnable was successfully placed in to the
12490     *         message queue.  Returns false on failure, usually because the
12491     *         looper processing the message queue is exiting.  Note that a
12492     *         result of true does not mean the Runnable will be processed --
12493     *         if the looper is quit before the delivery time of the message
12494     *         occurs then the message will be dropped.
12495     *
12496     * @see #post
12497     * @see #removeCallbacks
12498     */
12499    public boolean postDelayed(Runnable action, long delayMillis) {
12500        final AttachInfo attachInfo = mAttachInfo;
12501        if (attachInfo != null) {
12502            return attachInfo.mHandler.postDelayed(action, delayMillis);
12503        }
12504        // Assume that post will succeed later
12505        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12506        return true;
12507    }
12508
12509    /**
12510     * <p>Causes the Runnable to execute on the next animation time step.
12511     * The runnable will be run on the user interface thread.</p>
12512     *
12513     * @param action The Runnable that will be executed.
12514     *
12515     * @see #postOnAnimationDelayed
12516     * @see #removeCallbacks
12517     */
12518    public void postOnAnimation(Runnable action) {
12519        final AttachInfo attachInfo = mAttachInfo;
12520        if (attachInfo != null) {
12521            attachInfo.mViewRootImpl.mChoreographer.postCallback(
12522                    Choreographer.CALLBACK_ANIMATION, action, null);
12523        } else {
12524            // Assume that post will succeed later
12525            ViewRootImpl.getRunQueue().post(action);
12526        }
12527    }
12528
12529    /**
12530     * <p>Causes the Runnable to execute on the next animation time step,
12531     * after the specified amount of time elapses.
12532     * The runnable will be run on the user interface thread.</p>
12533     *
12534     * @param action The Runnable that will be executed.
12535     * @param delayMillis The delay (in milliseconds) until the Runnable
12536     *        will be executed.
12537     *
12538     * @see #postOnAnimation
12539     * @see #removeCallbacks
12540     */
12541    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
12542        final AttachInfo attachInfo = mAttachInfo;
12543        if (attachInfo != null) {
12544            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12545                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
12546        } else {
12547            // Assume that post will succeed later
12548            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12549        }
12550    }
12551
12552    /**
12553     * <p>Removes the specified Runnable from the message queue.</p>
12554     *
12555     * @param action The Runnable to remove from the message handling queue
12556     *
12557     * @return true if this view could ask the Handler to remove the Runnable,
12558     *         false otherwise. When the returned value is true, the Runnable
12559     *         may or may not have been actually removed from the message queue
12560     *         (for instance, if the Runnable was not in the queue already.)
12561     *
12562     * @see #post
12563     * @see #postDelayed
12564     * @see #postOnAnimation
12565     * @see #postOnAnimationDelayed
12566     */
12567    public boolean removeCallbacks(Runnable action) {
12568        if (action != null) {
12569            final AttachInfo attachInfo = mAttachInfo;
12570            if (attachInfo != null) {
12571                attachInfo.mHandler.removeCallbacks(action);
12572                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12573                        Choreographer.CALLBACK_ANIMATION, action, null);
12574            }
12575            // Assume that post will succeed later
12576            ViewRootImpl.getRunQueue().removeCallbacks(action);
12577        }
12578        return true;
12579    }
12580
12581    /**
12582     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
12583     * Use this to invalidate the View from a non-UI thread.</p>
12584     *
12585     * <p>This method can be invoked from outside of the UI thread
12586     * only when this View is attached to a window.</p>
12587     *
12588     * @see #invalidate()
12589     * @see #postInvalidateDelayed(long)
12590     */
12591    public void postInvalidate() {
12592        postInvalidateDelayed(0);
12593    }
12594
12595    /**
12596     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12597     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
12598     *
12599     * <p>This method can be invoked from outside of the UI thread
12600     * only when this View is attached to a window.</p>
12601     *
12602     * @param left The left coordinate of the rectangle to invalidate.
12603     * @param top The top coordinate of the rectangle to invalidate.
12604     * @param right The right coordinate of the rectangle to invalidate.
12605     * @param bottom The bottom coordinate of the rectangle to invalidate.
12606     *
12607     * @see #invalidate(int, int, int, int)
12608     * @see #invalidate(Rect)
12609     * @see #postInvalidateDelayed(long, int, int, int, int)
12610     */
12611    public void postInvalidate(int left, int top, int right, int bottom) {
12612        postInvalidateDelayed(0, left, top, right, bottom);
12613    }
12614
12615    /**
12616     * <p>Cause an invalidate to happen on a subsequent cycle through the event
12617     * loop. Waits for the specified amount of time.</p>
12618     *
12619     * <p>This method can be invoked from outside of the UI thread
12620     * only when this View is attached to a window.</p>
12621     *
12622     * @param delayMilliseconds the duration in milliseconds to delay the
12623     *         invalidation by
12624     *
12625     * @see #invalidate()
12626     * @see #postInvalidate()
12627     */
12628    public void postInvalidateDelayed(long delayMilliseconds) {
12629        // We try only with the AttachInfo because there's no point in invalidating
12630        // if we are not attached to our window
12631        final AttachInfo attachInfo = mAttachInfo;
12632        if (attachInfo != null) {
12633            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
12634        }
12635    }
12636
12637    /**
12638     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12639     * through the event loop. Waits for the specified amount of time.</p>
12640     *
12641     * <p>This method can be invoked from outside of the UI thread
12642     * only when this View is attached to a window.</p>
12643     *
12644     * @param delayMilliseconds the duration in milliseconds to delay the
12645     *         invalidation by
12646     * @param left The left coordinate of the rectangle to invalidate.
12647     * @param top The top coordinate of the rectangle to invalidate.
12648     * @param right The right coordinate of the rectangle to invalidate.
12649     * @param bottom The bottom coordinate of the rectangle to invalidate.
12650     *
12651     * @see #invalidate(int, int, int, int)
12652     * @see #invalidate(Rect)
12653     * @see #postInvalidate(int, int, int, int)
12654     */
12655    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
12656            int right, int bottom) {
12657
12658        // We try only with the AttachInfo because there's no point in invalidating
12659        // if we are not attached to our window
12660        final AttachInfo attachInfo = mAttachInfo;
12661        if (attachInfo != null) {
12662            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12663            info.target = this;
12664            info.left = left;
12665            info.top = top;
12666            info.right = right;
12667            info.bottom = bottom;
12668
12669            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12670        }
12671    }
12672
12673    /**
12674     * <p>Cause an invalidate to happen on the next animation time step, typically the
12675     * next display frame.</p>
12676     *
12677     * <p>This method can be invoked from outside of the UI thread
12678     * only when this View is attached to a window.</p>
12679     *
12680     * @see #invalidate()
12681     */
12682    public void postInvalidateOnAnimation() {
12683        // We try only with the AttachInfo because there's no point in invalidating
12684        // if we are not attached to our window
12685        final AttachInfo attachInfo = mAttachInfo;
12686        if (attachInfo != null) {
12687            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12688        }
12689    }
12690
12691    /**
12692     * <p>Cause an invalidate of the specified area to happen on the next animation
12693     * time step, typically the next display frame.</p>
12694     *
12695     * <p>This method can be invoked from outside of the UI thread
12696     * only when this View is attached to a window.</p>
12697     *
12698     * @param left The left coordinate of the rectangle to invalidate.
12699     * @param top The top coordinate of the rectangle to invalidate.
12700     * @param right The right coordinate of the rectangle to invalidate.
12701     * @param bottom The bottom coordinate of the rectangle to invalidate.
12702     *
12703     * @see #invalidate(int, int, int, int)
12704     * @see #invalidate(Rect)
12705     */
12706    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12707        // We try only with the AttachInfo because there's no point in invalidating
12708        // if we are not attached to our window
12709        final AttachInfo attachInfo = mAttachInfo;
12710        if (attachInfo != null) {
12711            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12712            info.target = this;
12713            info.left = left;
12714            info.top = top;
12715            info.right = right;
12716            info.bottom = bottom;
12717
12718            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12719        }
12720    }
12721
12722    /**
12723     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12724     * This event is sent at most once every
12725     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12726     */
12727    private void postSendViewScrolledAccessibilityEventCallback() {
12728        if (mSendViewScrolledAccessibilityEvent == null) {
12729            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12730        }
12731        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12732            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12733            postDelayed(mSendViewScrolledAccessibilityEvent,
12734                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12735        }
12736    }
12737
12738    /**
12739     * Called by a parent to request that a child update its values for mScrollX
12740     * and mScrollY if necessary. This will typically be done if the child is
12741     * animating a scroll using a {@link android.widget.Scroller Scroller}
12742     * object.
12743     */
12744    public void computeScroll() {
12745    }
12746
12747    /**
12748     * <p>Indicate whether the horizontal edges are faded when the view is
12749     * scrolled horizontally.</p>
12750     *
12751     * @return true if the horizontal edges should are faded on scroll, false
12752     *         otherwise
12753     *
12754     * @see #setHorizontalFadingEdgeEnabled(boolean)
12755     *
12756     * @attr ref android.R.styleable#View_requiresFadingEdge
12757     */
12758    public boolean isHorizontalFadingEdgeEnabled() {
12759        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12760    }
12761
12762    /**
12763     * <p>Define whether the horizontal edges should be faded when this view
12764     * is scrolled horizontally.</p>
12765     *
12766     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12767     *                                    be faded when the view is scrolled
12768     *                                    horizontally
12769     *
12770     * @see #isHorizontalFadingEdgeEnabled()
12771     *
12772     * @attr ref android.R.styleable#View_requiresFadingEdge
12773     */
12774    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12775        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12776            if (horizontalFadingEdgeEnabled) {
12777                initScrollCache();
12778            }
12779
12780            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12781        }
12782    }
12783
12784    /**
12785     * <p>Indicate whether the vertical edges are faded when the view is
12786     * scrolled horizontally.</p>
12787     *
12788     * @return true if the vertical edges should are faded on scroll, false
12789     *         otherwise
12790     *
12791     * @see #setVerticalFadingEdgeEnabled(boolean)
12792     *
12793     * @attr ref android.R.styleable#View_requiresFadingEdge
12794     */
12795    public boolean isVerticalFadingEdgeEnabled() {
12796        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12797    }
12798
12799    /**
12800     * <p>Define whether the vertical edges should be faded when this view
12801     * is scrolled vertically.</p>
12802     *
12803     * @param verticalFadingEdgeEnabled true if the vertical edges should
12804     *                                  be faded when the view is scrolled
12805     *                                  vertically
12806     *
12807     * @see #isVerticalFadingEdgeEnabled()
12808     *
12809     * @attr ref android.R.styleable#View_requiresFadingEdge
12810     */
12811    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12812        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12813            if (verticalFadingEdgeEnabled) {
12814                initScrollCache();
12815            }
12816
12817            mViewFlags ^= FADING_EDGE_VERTICAL;
12818        }
12819    }
12820
12821    /**
12822     * Returns the strength, or intensity, of the top faded edge. The strength is
12823     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12824     * returns 0.0 or 1.0 but no value in between.
12825     *
12826     * Subclasses should override this method to provide a smoother fade transition
12827     * when scrolling occurs.
12828     *
12829     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12830     */
12831    protected float getTopFadingEdgeStrength() {
12832        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12833    }
12834
12835    /**
12836     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12837     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12838     * returns 0.0 or 1.0 but no value in between.
12839     *
12840     * Subclasses should override this method to provide a smoother fade transition
12841     * when scrolling occurs.
12842     *
12843     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12844     */
12845    protected float getBottomFadingEdgeStrength() {
12846        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12847                computeVerticalScrollRange() ? 1.0f : 0.0f;
12848    }
12849
12850    /**
12851     * Returns the strength, or intensity, of the left faded edge. The strength is
12852     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12853     * returns 0.0 or 1.0 but no value in between.
12854     *
12855     * Subclasses should override this method to provide a smoother fade transition
12856     * when scrolling occurs.
12857     *
12858     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12859     */
12860    protected float getLeftFadingEdgeStrength() {
12861        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12862    }
12863
12864    /**
12865     * Returns the strength, or intensity, of the right faded edge. The strength is
12866     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12867     * returns 0.0 or 1.0 but no value in between.
12868     *
12869     * Subclasses should override this method to provide a smoother fade transition
12870     * when scrolling occurs.
12871     *
12872     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12873     */
12874    protected float getRightFadingEdgeStrength() {
12875        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12876                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12877    }
12878
12879    /**
12880     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12881     * scrollbar is not drawn by default.</p>
12882     *
12883     * @return true if the horizontal scrollbar should be painted, false
12884     *         otherwise
12885     *
12886     * @see #setHorizontalScrollBarEnabled(boolean)
12887     */
12888    public boolean isHorizontalScrollBarEnabled() {
12889        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12890    }
12891
12892    /**
12893     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12894     * scrollbar is not drawn by default.</p>
12895     *
12896     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12897     *                                   be painted
12898     *
12899     * @see #isHorizontalScrollBarEnabled()
12900     */
12901    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12902        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12903            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12904            computeOpaqueFlags();
12905            resolvePadding();
12906        }
12907    }
12908
12909    /**
12910     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12911     * scrollbar is not drawn by default.</p>
12912     *
12913     * @return true if the vertical scrollbar should be painted, false
12914     *         otherwise
12915     *
12916     * @see #setVerticalScrollBarEnabled(boolean)
12917     */
12918    public boolean isVerticalScrollBarEnabled() {
12919        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12920    }
12921
12922    /**
12923     * <p>Define whether the vertical scrollbar should be drawn or not. The
12924     * scrollbar is not drawn by default.</p>
12925     *
12926     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12927     *                                 be painted
12928     *
12929     * @see #isVerticalScrollBarEnabled()
12930     */
12931    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12932        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12933            mViewFlags ^= SCROLLBARS_VERTICAL;
12934            computeOpaqueFlags();
12935            resolvePadding();
12936        }
12937    }
12938
12939    /**
12940     * @hide
12941     */
12942    protected void recomputePadding() {
12943        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12944    }
12945
12946    /**
12947     * Define whether scrollbars will fade when the view is not scrolling.
12948     *
12949     * @param fadeScrollbars whether to enable fading
12950     *
12951     * @attr ref android.R.styleable#View_fadeScrollbars
12952     */
12953    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12954        initScrollCache();
12955        final ScrollabilityCache scrollabilityCache = mScrollCache;
12956        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12957        if (fadeScrollbars) {
12958            scrollabilityCache.state = ScrollabilityCache.OFF;
12959        } else {
12960            scrollabilityCache.state = ScrollabilityCache.ON;
12961        }
12962    }
12963
12964    /**
12965     *
12966     * Returns true if scrollbars will fade when this view is not scrolling
12967     *
12968     * @return true if scrollbar fading is enabled
12969     *
12970     * @attr ref android.R.styleable#View_fadeScrollbars
12971     */
12972    public boolean isScrollbarFadingEnabled() {
12973        return mScrollCache != null && mScrollCache.fadeScrollBars;
12974    }
12975
12976    /**
12977     *
12978     * Returns the delay before scrollbars fade.
12979     *
12980     * @return the delay before scrollbars fade
12981     *
12982     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12983     */
12984    public int getScrollBarDefaultDelayBeforeFade() {
12985        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12986                mScrollCache.scrollBarDefaultDelayBeforeFade;
12987    }
12988
12989    /**
12990     * Define the delay before scrollbars fade.
12991     *
12992     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12993     *
12994     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12995     */
12996    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12997        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12998    }
12999
13000    /**
13001     *
13002     * Returns the scrollbar fade duration.
13003     *
13004     * @return the scrollbar fade duration
13005     *
13006     * @attr ref android.R.styleable#View_scrollbarFadeDuration
13007     */
13008    public int getScrollBarFadeDuration() {
13009        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
13010                mScrollCache.scrollBarFadeDuration;
13011    }
13012
13013    /**
13014     * Define the scrollbar fade duration.
13015     *
13016     * @param scrollBarFadeDuration - the scrollbar fade duration
13017     *
13018     * @attr ref android.R.styleable#View_scrollbarFadeDuration
13019     */
13020    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
13021        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
13022    }
13023
13024    /**
13025     *
13026     * Returns the scrollbar size.
13027     *
13028     * @return the scrollbar size
13029     *
13030     * @attr ref android.R.styleable#View_scrollbarSize
13031     */
13032    public int getScrollBarSize() {
13033        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
13034                mScrollCache.scrollBarSize;
13035    }
13036
13037    /**
13038     * Define the scrollbar size.
13039     *
13040     * @param scrollBarSize - the scrollbar size
13041     *
13042     * @attr ref android.R.styleable#View_scrollbarSize
13043     */
13044    public void setScrollBarSize(int scrollBarSize) {
13045        getScrollCache().scrollBarSize = scrollBarSize;
13046    }
13047
13048    /**
13049     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
13050     * inset. When inset, they add to the padding of the view. And the scrollbars
13051     * can be drawn inside the padding area or on the edge of the view. For example,
13052     * if a view has a background drawable and you want to draw the scrollbars
13053     * inside the padding specified by the drawable, you can use
13054     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
13055     * appear at the edge of the view, ignoring the padding, then you can use
13056     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
13057     * @param style the style of the scrollbars. Should be one of
13058     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
13059     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
13060     * @see #SCROLLBARS_INSIDE_OVERLAY
13061     * @see #SCROLLBARS_INSIDE_INSET
13062     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13063     * @see #SCROLLBARS_OUTSIDE_INSET
13064     *
13065     * @attr ref android.R.styleable#View_scrollbarStyle
13066     */
13067    public void setScrollBarStyle(@ScrollBarStyle int style) {
13068        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
13069            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
13070            computeOpaqueFlags();
13071            resolvePadding();
13072        }
13073    }
13074
13075    /**
13076     * <p>Returns the current scrollbar style.</p>
13077     * @return the current scrollbar style
13078     * @see #SCROLLBARS_INSIDE_OVERLAY
13079     * @see #SCROLLBARS_INSIDE_INSET
13080     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13081     * @see #SCROLLBARS_OUTSIDE_INSET
13082     *
13083     * @attr ref android.R.styleable#View_scrollbarStyle
13084     */
13085    @ViewDebug.ExportedProperty(mapping = {
13086            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
13087            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
13088            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
13089            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
13090    })
13091    @ScrollBarStyle
13092    public int getScrollBarStyle() {
13093        return mViewFlags & SCROLLBARS_STYLE_MASK;
13094    }
13095
13096    /**
13097     * <p>Compute the horizontal range that the horizontal scrollbar
13098     * represents.</p>
13099     *
13100     * <p>The range is expressed in arbitrary units that must be the same as the
13101     * units used by {@link #computeHorizontalScrollExtent()} and
13102     * {@link #computeHorizontalScrollOffset()}.</p>
13103     *
13104     * <p>The default range is the drawing width of this view.</p>
13105     *
13106     * @return the total horizontal range represented by the horizontal
13107     *         scrollbar
13108     *
13109     * @see #computeHorizontalScrollExtent()
13110     * @see #computeHorizontalScrollOffset()
13111     * @see android.widget.ScrollBarDrawable
13112     */
13113    protected int computeHorizontalScrollRange() {
13114        return getWidth();
13115    }
13116
13117    /**
13118     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
13119     * within the horizontal range. This value is used to compute the position
13120     * of the thumb within the scrollbar's track.</p>
13121     *
13122     * <p>The range is expressed in arbitrary units that must be the same as the
13123     * units used by {@link #computeHorizontalScrollRange()} and
13124     * {@link #computeHorizontalScrollExtent()}.</p>
13125     *
13126     * <p>The default offset is the scroll offset of this view.</p>
13127     *
13128     * @return the horizontal offset of the scrollbar's thumb
13129     *
13130     * @see #computeHorizontalScrollRange()
13131     * @see #computeHorizontalScrollExtent()
13132     * @see android.widget.ScrollBarDrawable
13133     */
13134    protected int computeHorizontalScrollOffset() {
13135        return mScrollX;
13136    }
13137
13138    /**
13139     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
13140     * within the horizontal range. This value is used to compute the length
13141     * of the thumb within the scrollbar's track.</p>
13142     *
13143     * <p>The range is expressed in arbitrary units that must be the same as the
13144     * units used by {@link #computeHorizontalScrollRange()} and
13145     * {@link #computeHorizontalScrollOffset()}.</p>
13146     *
13147     * <p>The default extent is the drawing width of this view.</p>
13148     *
13149     * @return the horizontal extent of the scrollbar's thumb
13150     *
13151     * @see #computeHorizontalScrollRange()
13152     * @see #computeHorizontalScrollOffset()
13153     * @see android.widget.ScrollBarDrawable
13154     */
13155    protected int computeHorizontalScrollExtent() {
13156        return getWidth();
13157    }
13158
13159    /**
13160     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
13161     *
13162     * <p>The range is expressed in arbitrary units that must be the same as the
13163     * units used by {@link #computeVerticalScrollExtent()} and
13164     * {@link #computeVerticalScrollOffset()}.</p>
13165     *
13166     * @return the total vertical range represented by the vertical scrollbar
13167     *
13168     * <p>The default range is the drawing height of this view.</p>
13169     *
13170     * @see #computeVerticalScrollExtent()
13171     * @see #computeVerticalScrollOffset()
13172     * @see android.widget.ScrollBarDrawable
13173     */
13174    protected int computeVerticalScrollRange() {
13175        return getHeight();
13176    }
13177
13178    /**
13179     * <p>Compute the vertical offset of the vertical scrollbar's thumb
13180     * within the horizontal range. This value is used to compute the position
13181     * of the thumb within the scrollbar's track.</p>
13182     *
13183     * <p>The range is expressed in arbitrary units that must be the same as the
13184     * units used by {@link #computeVerticalScrollRange()} and
13185     * {@link #computeVerticalScrollExtent()}.</p>
13186     *
13187     * <p>The default offset is the scroll offset of this view.</p>
13188     *
13189     * @return the vertical offset of the scrollbar's thumb
13190     *
13191     * @see #computeVerticalScrollRange()
13192     * @see #computeVerticalScrollExtent()
13193     * @see android.widget.ScrollBarDrawable
13194     */
13195    protected int computeVerticalScrollOffset() {
13196        return mScrollY;
13197    }
13198
13199    /**
13200     * <p>Compute the vertical extent of the vertical scrollbar's thumb
13201     * within the vertical range. This value is used to compute the length
13202     * of the thumb within the scrollbar's track.</p>
13203     *
13204     * <p>The range is expressed in arbitrary units that must be the same as the
13205     * units used by {@link #computeVerticalScrollRange()} and
13206     * {@link #computeVerticalScrollOffset()}.</p>
13207     *
13208     * <p>The default extent is the drawing height of this view.</p>
13209     *
13210     * @return the vertical extent of the scrollbar's thumb
13211     *
13212     * @see #computeVerticalScrollRange()
13213     * @see #computeVerticalScrollOffset()
13214     * @see android.widget.ScrollBarDrawable
13215     */
13216    protected int computeVerticalScrollExtent() {
13217        return getHeight();
13218    }
13219
13220    /**
13221     * Check if this view can be scrolled horizontally in a certain direction.
13222     *
13223     * @param direction Negative to check scrolling left, positive to check scrolling right.
13224     * @return true if this view can be scrolled in the specified direction, false otherwise.
13225     */
13226    public boolean canScrollHorizontally(int direction) {
13227        final int offset = computeHorizontalScrollOffset();
13228        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
13229        if (range == 0) return false;
13230        if (direction < 0) {
13231            return offset > 0;
13232        } else {
13233            return offset < range - 1;
13234        }
13235    }
13236
13237    /**
13238     * Check if this view can be scrolled vertically in a certain direction.
13239     *
13240     * @param direction Negative to check scrolling up, positive to check scrolling down.
13241     * @return true if this view can be scrolled in the specified direction, false otherwise.
13242     */
13243    public boolean canScrollVertically(int direction) {
13244        final int offset = computeVerticalScrollOffset();
13245        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
13246        if (range == 0) return false;
13247        if (direction < 0) {
13248            return offset > 0;
13249        } else {
13250            return offset < range - 1;
13251        }
13252    }
13253
13254    /**
13255     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
13256     * scrollbars are painted only if they have been awakened first.</p>
13257     *
13258     * @param canvas the canvas on which to draw the scrollbars
13259     *
13260     * @see #awakenScrollBars(int)
13261     */
13262    protected final void onDrawScrollBars(Canvas canvas) {
13263        // scrollbars are drawn only when the animation is running
13264        final ScrollabilityCache cache = mScrollCache;
13265        if (cache != null) {
13266
13267            int state = cache.state;
13268
13269            if (state == ScrollabilityCache.OFF) {
13270                return;
13271            }
13272
13273            boolean invalidate = false;
13274
13275            if (state == ScrollabilityCache.FADING) {
13276                // We're fading -- get our fade interpolation
13277                if (cache.interpolatorValues == null) {
13278                    cache.interpolatorValues = new float[1];
13279                }
13280
13281                float[] values = cache.interpolatorValues;
13282
13283                // Stops the animation if we're done
13284                if (cache.scrollBarInterpolator.timeToValues(values) ==
13285                        Interpolator.Result.FREEZE_END) {
13286                    cache.state = ScrollabilityCache.OFF;
13287                } else {
13288                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
13289                }
13290
13291                // This will make the scroll bars inval themselves after
13292                // drawing. We only want this when we're fading so that
13293                // we prevent excessive redraws
13294                invalidate = true;
13295            } else {
13296                // We're just on -- but we may have been fading before so
13297                // reset alpha
13298                cache.scrollBar.mutate().setAlpha(255);
13299            }
13300
13301
13302            final int viewFlags = mViewFlags;
13303
13304            final boolean drawHorizontalScrollBar =
13305                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
13306            final boolean drawVerticalScrollBar =
13307                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
13308                && !isVerticalScrollBarHidden();
13309
13310            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
13311                final int width = mRight - mLeft;
13312                final int height = mBottom - mTop;
13313
13314                final ScrollBarDrawable scrollBar = cache.scrollBar;
13315
13316                final int scrollX = mScrollX;
13317                final int scrollY = mScrollY;
13318                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
13319
13320                int left;
13321                int top;
13322                int right;
13323                int bottom;
13324
13325                if (drawHorizontalScrollBar) {
13326                    int size = scrollBar.getSize(false);
13327                    if (size <= 0) {
13328                        size = cache.scrollBarSize;
13329                    }
13330
13331                    scrollBar.setParameters(computeHorizontalScrollRange(),
13332                                            computeHorizontalScrollOffset(),
13333                                            computeHorizontalScrollExtent(), false);
13334                    final int verticalScrollBarGap = drawVerticalScrollBar ?
13335                            getVerticalScrollbarWidth() : 0;
13336                    top = scrollY + height - size - (mUserPaddingBottom & inside);
13337                    left = scrollX + (mPaddingLeft & inside);
13338                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
13339                    bottom = top + size;
13340                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
13341                    if (invalidate) {
13342                        invalidate(left, top, right, bottom);
13343                    }
13344                }
13345
13346                if (drawVerticalScrollBar) {
13347                    int size = scrollBar.getSize(true);
13348                    if (size <= 0) {
13349                        size = cache.scrollBarSize;
13350                    }
13351
13352                    scrollBar.setParameters(computeVerticalScrollRange(),
13353                                            computeVerticalScrollOffset(),
13354                                            computeVerticalScrollExtent(), true);
13355                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
13356                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
13357                        verticalScrollbarPosition = isLayoutRtl() ?
13358                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
13359                    }
13360                    switch (verticalScrollbarPosition) {
13361                        default:
13362                        case SCROLLBAR_POSITION_RIGHT:
13363                            left = scrollX + width - size - (mUserPaddingRight & inside);
13364                            break;
13365                        case SCROLLBAR_POSITION_LEFT:
13366                            left = scrollX + (mUserPaddingLeft & inside);
13367                            break;
13368                    }
13369                    top = scrollY + (mPaddingTop & inside);
13370                    right = left + size;
13371                    bottom = scrollY + height - (mUserPaddingBottom & inside);
13372                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
13373                    if (invalidate) {
13374                        invalidate(left, top, right, bottom);
13375                    }
13376                }
13377            }
13378        }
13379    }
13380
13381    /**
13382     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
13383     * FastScroller is visible.
13384     * @return whether to temporarily hide the vertical scrollbar
13385     * @hide
13386     */
13387    protected boolean isVerticalScrollBarHidden() {
13388        return false;
13389    }
13390
13391    /**
13392     * <p>Draw the horizontal scrollbar if
13393     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
13394     *
13395     * @param canvas the canvas on which to draw the scrollbar
13396     * @param scrollBar the scrollbar's drawable
13397     *
13398     * @see #isHorizontalScrollBarEnabled()
13399     * @see #computeHorizontalScrollRange()
13400     * @see #computeHorizontalScrollExtent()
13401     * @see #computeHorizontalScrollOffset()
13402     * @see android.widget.ScrollBarDrawable
13403     * @hide
13404     */
13405    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
13406            int l, int t, int r, int b) {
13407        scrollBar.setBounds(l, t, r, b);
13408        scrollBar.draw(canvas);
13409    }
13410
13411    /**
13412     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
13413     * returns true.</p>
13414     *
13415     * @param canvas the canvas on which to draw the scrollbar
13416     * @param scrollBar the scrollbar's drawable
13417     *
13418     * @see #isVerticalScrollBarEnabled()
13419     * @see #computeVerticalScrollRange()
13420     * @see #computeVerticalScrollExtent()
13421     * @see #computeVerticalScrollOffset()
13422     * @see android.widget.ScrollBarDrawable
13423     * @hide
13424     */
13425    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
13426            int l, int t, int r, int b) {
13427        scrollBar.setBounds(l, t, r, b);
13428        scrollBar.draw(canvas);
13429    }
13430
13431    /**
13432     * Implement this to do your drawing.
13433     *
13434     * @param canvas the canvas on which the background will be drawn
13435     */
13436    protected void onDraw(Canvas canvas) {
13437    }
13438
13439    /*
13440     * Caller is responsible for calling requestLayout if necessary.
13441     * (This allows addViewInLayout to not request a new layout.)
13442     */
13443    void assignParent(ViewParent parent) {
13444        if (mParent == null) {
13445            mParent = parent;
13446        } else if (parent == null) {
13447            mParent = null;
13448        } else {
13449            throw new RuntimeException("view " + this + " being added, but"
13450                    + " it already has a parent");
13451        }
13452    }
13453
13454    /**
13455     * This is called when the view is attached to a window.  At this point it
13456     * has a Surface and will start drawing.  Note that this function is
13457     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
13458     * however it may be called any time before the first onDraw -- including
13459     * before or after {@link #onMeasure(int, int)}.
13460     *
13461     * @see #onDetachedFromWindow()
13462     */
13463    @CallSuper
13464    protected void onAttachedToWindow() {
13465        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
13466            mParent.requestTransparentRegion(this);
13467        }
13468
13469        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
13470            initialAwakenScrollBars();
13471            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
13472        }
13473
13474        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13475
13476        jumpDrawablesToCurrentState();
13477
13478        resetSubtreeAccessibilityStateChanged();
13479
13480        // rebuild, since Outline not maintained while View is detached
13481        rebuildOutline();
13482
13483        if (isFocused()) {
13484            InputMethodManager imm = InputMethodManager.peekInstance();
13485            if (imm != null) {
13486                imm.focusIn(this);
13487            }
13488        }
13489    }
13490
13491    /**
13492     * Resolve all RTL related properties.
13493     *
13494     * @return true if resolution of RTL properties has been done
13495     *
13496     * @hide
13497     */
13498    public boolean resolveRtlPropertiesIfNeeded() {
13499        if (!needRtlPropertiesResolution()) return false;
13500
13501        // Order is important here: LayoutDirection MUST be resolved first
13502        if (!isLayoutDirectionResolved()) {
13503            resolveLayoutDirection();
13504            resolveLayoutParams();
13505        }
13506        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
13507        if (!isTextDirectionResolved()) {
13508            resolveTextDirection();
13509        }
13510        if (!isTextAlignmentResolved()) {
13511            resolveTextAlignment();
13512        }
13513        // Should resolve Drawables before Padding because we need the layout direction of the
13514        // Drawable to correctly resolve Padding.
13515        if (!areDrawablesResolved()) {
13516            resolveDrawables();
13517        }
13518        if (!isPaddingResolved()) {
13519            resolvePadding();
13520        }
13521        onRtlPropertiesChanged(getLayoutDirection());
13522        return true;
13523    }
13524
13525    /**
13526     * Reset resolution of all RTL related properties.
13527     *
13528     * @hide
13529     */
13530    public void resetRtlProperties() {
13531        resetResolvedLayoutDirection();
13532        resetResolvedTextDirection();
13533        resetResolvedTextAlignment();
13534        resetResolvedPadding();
13535        resetResolvedDrawables();
13536    }
13537
13538    /**
13539     * @see #onScreenStateChanged(int)
13540     */
13541    void dispatchScreenStateChanged(int screenState) {
13542        onScreenStateChanged(screenState);
13543    }
13544
13545    /**
13546     * This method is called whenever the state of the screen this view is
13547     * attached to changes. A state change will usually occurs when the screen
13548     * turns on or off (whether it happens automatically or the user does it
13549     * manually.)
13550     *
13551     * @param screenState The new state of the screen. Can be either
13552     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
13553     */
13554    public void onScreenStateChanged(int screenState) {
13555    }
13556
13557    /**
13558     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
13559     */
13560    private boolean hasRtlSupport() {
13561        return mContext.getApplicationInfo().hasRtlSupport();
13562    }
13563
13564    /**
13565     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
13566     * RTL not supported)
13567     */
13568    private boolean isRtlCompatibilityMode() {
13569        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
13570        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
13571    }
13572
13573    /**
13574     * @return true if RTL properties need resolution.
13575     *
13576     */
13577    private boolean needRtlPropertiesResolution() {
13578        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
13579    }
13580
13581    /**
13582     * Called when any RTL property (layout direction or text direction or text alignment) has
13583     * been changed.
13584     *
13585     * Subclasses need to override this method to take care of cached information that depends on the
13586     * resolved layout direction, or to inform child views that inherit their layout direction.
13587     *
13588     * The default implementation does nothing.
13589     *
13590     * @param layoutDirection the direction of the layout
13591     *
13592     * @see #LAYOUT_DIRECTION_LTR
13593     * @see #LAYOUT_DIRECTION_RTL
13594     */
13595    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
13596    }
13597
13598    /**
13599     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
13600     * that the parent directionality can and will be resolved before its children.
13601     *
13602     * @return true if resolution has been done, false otherwise.
13603     *
13604     * @hide
13605     */
13606    public boolean resolveLayoutDirection() {
13607        // Clear any previous layout direction resolution
13608        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13609
13610        if (hasRtlSupport()) {
13611            // Set resolved depending on layout direction
13612            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
13613                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
13614                case LAYOUT_DIRECTION_INHERIT:
13615                    // We cannot resolve yet. LTR is by default and let the resolution happen again
13616                    // later to get the correct resolved value
13617                    if (!canResolveLayoutDirection()) return false;
13618
13619                    // Parent has not yet resolved, LTR is still the default
13620                    try {
13621                        if (!mParent.isLayoutDirectionResolved()) return false;
13622
13623                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13624                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13625                        }
13626                    } catch (AbstractMethodError e) {
13627                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13628                                " does not fully implement ViewParent", e);
13629                    }
13630                    break;
13631                case LAYOUT_DIRECTION_RTL:
13632                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13633                    break;
13634                case LAYOUT_DIRECTION_LOCALE:
13635                    if((LAYOUT_DIRECTION_RTL ==
13636                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
13637                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13638                    }
13639                    break;
13640                default:
13641                    // Nothing to do, LTR by default
13642            }
13643        }
13644
13645        // Set to resolved
13646        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13647        return true;
13648    }
13649
13650    /**
13651     * Check if layout direction resolution can be done.
13652     *
13653     * @return true if layout direction resolution can be done otherwise return false.
13654     */
13655    public boolean canResolveLayoutDirection() {
13656        switch (getRawLayoutDirection()) {
13657            case LAYOUT_DIRECTION_INHERIT:
13658                if (mParent != null) {
13659                    try {
13660                        return mParent.canResolveLayoutDirection();
13661                    } catch (AbstractMethodError e) {
13662                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13663                                " does not fully implement ViewParent", e);
13664                    }
13665                }
13666                return false;
13667
13668            default:
13669                return true;
13670        }
13671    }
13672
13673    /**
13674     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13675     * {@link #onMeasure(int, int)}.
13676     *
13677     * @hide
13678     */
13679    public void resetResolvedLayoutDirection() {
13680        // Reset the current resolved bits
13681        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13682    }
13683
13684    /**
13685     * @return true if the layout direction is inherited.
13686     *
13687     * @hide
13688     */
13689    public boolean isLayoutDirectionInherited() {
13690        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13691    }
13692
13693    /**
13694     * @return true if layout direction has been resolved.
13695     */
13696    public boolean isLayoutDirectionResolved() {
13697        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13698    }
13699
13700    /**
13701     * Return if padding has been resolved
13702     *
13703     * @hide
13704     */
13705    boolean isPaddingResolved() {
13706        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13707    }
13708
13709    /**
13710     * Resolves padding depending on layout direction, if applicable, and
13711     * recomputes internal padding values to adjust for scroll bars.
13712     *
13713     * @hide
13714     */
13715    public void resolvePadding() {
13716        final int resolvedLayoutDirection = getLayoutDirection();
13717
13718        if (!isRtlCompatibilityMode()) {
13719            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13720            // If start / end padding are defined, they will be resolved (hence overriding) to
13721            // left / right or right / left depending on the resolved layout direction.
13722            // If start / end padding are not defined, use the left / right ones.
13723            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13724                Rect padding = sThreadLocal.get();
13725                if (padding == null) {
13726                    padding = new Rect();
13727                    sThreadLocal.set(padding);
13728                }
13729                mBackground.getPadding(padding);
13730                if (!mLeftPaddingDefined) {
13731                    mUserPaddingLeftInitial = padding.left;
13732                }
13733                if (!mRightPaddingDefined) {
13734                    mUserPaddingRightInitial = padding.right;
13735                }
13736            }
13737            switch (resolvedLayoutDirection) {
13738                case LAYOUT_DIRECTION_RTL:
13739                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13740                        mUserPaddingRight = mUserPaddingStart;
13741                    } else {
13742                        mUserPaddingRight = mUserPaddingRightInitial;
13743                    }
13744                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13745                        mUserPaddingLeft = mUserPaddingEnd;
13746                    } else {
13747                        mUserPaddingLeft = mUserPaddingLeftInitial;
13748                    }
13749                    break;
13750                case LAYOUT_DIRECTION_LTR:
13751                default:
13752                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13753                        mUserPaddingLeft = mUserPaddingStart;
13754                    } else {
13755                        mUserPaddingLeft = mUserPaddingLeftInitial;
13756                    }
13757                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13758                        mUserPaddingRight = mUserPaddingEnd;
13759                    } else {
13760                        mUserPaddingRight = mUserPaddingRightInitial;
13761                    }
13762            }
13763
13764            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13765        }
13766
13767        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13768        onRtlPropertiesChanged(resolvedLayoutDirection);
13769
13770        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13771    }
13772
13773    /**
13774     * Reset the resolved layout direction.
13775     *
13776     * @hide
13777     */
13778    public void resetResolvedPadding() {
13779        resetResolvedPaddingInternal();
13780    }
13781
13782    /**
13783     * Used when we only want to reset *this* view's padding and not trigger overrides
13784     * in ViewGroup that reset children too.
13785     */
13786    void resetResolvedPaddingInternal() {
13787        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13788    }
13789
13790    /**
13791     * This is called when the view is detached from a window.  At this point it
13792     * no longer has a surface for drawing.
13793     *
13794     * @see #onAttachedToWindow()
13795     */
13796    @CallSuper
13797    protected void onDetachedFromWindow() {
13798    }
13799
13800    /**
13801     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13802     * after onDetachedFromWindow().
13803     *
13804     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13805     * The super method should be called at the end of the overridden method to ensure
13806     * subclasses are destroyed first
13807     *
13808     * @hide
13809     */
13810    @CallSuper
13811    protected void onDetachedFromWindowInternal() {
13812        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13813        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13814
13815        removeUnsetPressCallback();
13816        removeLongPressCallback();
13817        removePerformClickCallback();
13818        removeSendViewScrolledAccessibilityEventCallback();
13819        stopNestedScroll();
13820
13821        // Anything that started animating right before detach should already
13822        // be in its final state when re-attached.
13823        jumpDrawablesToCurrentState();
13824
13825        destroyDrawingCache();
13826
13827        cleanupDraw();
13828        mCurrentAnimation = null;
13829    }
13830
13831    private void cleanupDraw() {
13832        resetDisplayList();
13833        if (mAttachInfo != null) {
13834            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13835        }
13836    }
13837
13838    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13839    }
13840
13841    /**
13842     * @return The number of times this view has been attached to a window
13843     */
13844    protected int getWindowAttachCount() {
13845        return mWindowAttachCount;
13846    }
13847
13848    /**
13849     * Retrieve a unique token identifying the window this view is attached to.
13850     * @return Return the window's token for use in
13851     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13852     */
13853    public IBinder getWindowToken() {
13854        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13855    }
13856
13857    /**
13858     * Retrieve the {@link WindowId} for the window this view is
13859     * currently attached to.
13860     */
13861    public WindowId getWindowId() {
13862        if (mAttachInfo == null) {
13863            return null;
13864        }
13865        if (mAttachInfo.mWindowId == null) {
13866            try {
13867                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13868                        mAttachInfo.mWindowToken);
13869                mAttachInfo.mWindowId = new WindowId(
13870                        mAttachInfo.mIWindowId);
13871            } catch (RemoteException e) {
13872            }
13873        }
13874        return mAttachInfo.mWindowId;
13875    }
13876
13877    /**
13878     * Retrieve a unique token identifying the top-level "real" window of
13879     * the window that this view is attached to.  That is, this is like
13880     * {@link #getWindowToken}, except if the window this view in is a panel
13881     * window (attached to another containing window), then the token of
13882     * the containing window is returned instead.
13883     *
13884     * @return Returns the associated window token, either
13885     * {@link #getWindowToken()} or the containing window's token.
13886     */
13887    public IBinder getApplicationWindowToken() {
13888        AttachInfo ai = mAttachInfo;
13889        if (ai != null) {
13890            IBinder appWindowToken = ai.mPanelParentWindowToken;
13891            if (appWindowToken == null) {
13892                appWindowToken = ai.mWindowToken;
13893            }
13894            return appWindowToken;
13895        }
13896        return null;
13897    }
13898
13899    /**
13900     * Gets the logical display to which the view's window has been attached.
13901     *
13902     * @return The logical display, or null if the view is not currently attached to a window.
13903     */
13904    public Display getDisplay() {
13905        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13906    }
13907
13908    /**
13909     * Retrieve private session object this view hierarchy is using to
13910     * communicate with the window manager.
13911     * @return the session object to communicate with the window manager
13912     */
13913    /*package*/ IWindowSession getWindowSession() {
13914        return mAttachInfo != null ? mAttachInfo.mSession : null;
13915    }
13916
13917    /**
13918     * @param info the {@link android.view.View.AttachInfo} to associated with
13919     *        this view
13920     */
13921    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13922        //System.out.println("Attached! " + this);
13923        mAttachInfo = info;
13924        if (mOverlay != null) {
13925            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13926        }
13927        mWindowAttachCount++;
13928        // We will need to evaluate the drawable state at least once.
13929        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13930        if (mFloatingTreeObserver != null) {
13931            info.mTreeObserver.merge(mFloatingTreeObserver);
13932            mFloatingTreeObserver = null;
13933        }
13934        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13935            mAttachInfo.mScrollContainers.add(this);
13936            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13937        }
13938        performCollectViewAttributes(mAttachInfo, visibility);
13939        onAttachedToWindow();
13940
13941        ListenerInfo li = mListenerInfo;
13942        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13943                li != null ? li.mOnAttachStateChangeListeners : null;
13944        if (listeners != null && listeners.size() > 0) {
13945            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13946            // perform the dispatching. The iterator is a safe guard against listeners that
13947            // could mutate the list by calling the various add/remove methods. This prevents
13948            // the array from being modified while we iterate it.
13949            for (OnAttachStateChangeListener listener : listeners) {
13950                listener.onViewAttachedToWindow(this);
13951            }
13952        }
13953
13954        int vis = info.mWindowVisibility;
13955        if (vis != GONE) {
13956            onWindowVisibilityChanged(vis);
13957        }
13958        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13959            // If nobody has evaluated the drawable state yet, then do it now.
13960            refreshDrawableState();
13961        }
13962        needGlobalAttributesUpdate(false);
13963    }
13964
13965    void dispatchDetachedFromWindow() {
13966        AttachInfo info = mAttachInfo;
13967        if (info != null) {
13968            int vis = info.mWindowVisibility;
13969            if (vis != GONE) {
13970                onWindowVisibilityChanged(GONE);
13971            }
13972        }
13973
13974        onDetachedFromWindow();
13975        onDetachedFromWindowInternal();
13976
13977        ListenerInfo li = mListenerInfo;
13978        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13979                li != null ? li.mOnAttachStateChangeListeners : null;
13980        if (listeners != null && listeners.size() > 0) {
13981            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13982            // perform the dispatching. The iterator is a safe guard against listeners that
13983            // could mutate the list by calling the various add/remove methods. This prevents
13984            // the array from being modified while we iterate it.
13985            for (OnAttachStateChangeListener listener : listeners) {
13986                listener.onViewDetachedFromWindow(this);
13987            }
13988        }
13989
13990        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13991            mAttachInfo.mScrollContainers.remove(this);
13992            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13993        }
13994
13995        mAttachInfo = null;
13996        if (mOverlay != null) {
13997            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13998        }
13999    }
14000
14001    /**
14002     * Cancel any deferred high-level input events that were previously posted to the event queue.
14003     *
14004     * <p>Many views post high-level events such as click handlers to the event queue
14005     * to run deferred in order to preserve a desired user experience - clearing visible
14006     * pressed states before executing, etc. This method will abort any events of this nature
14007     * that are currently in flight.</p>
14008     *
14009     * <p>Custom views that generate their own high-level deferred input events should override
14010     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
14011     *
14012     * <p>This will also cancel pending input events for any child views.</p>
14013     *
14014     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
14015     * This will not impact newer events posted after this call that may occur as a result of
14016     * lower-level input events still waiting in the queue. If you are trying to prevent
14017     * double-submitted  events for the duration of some sort of asynchronous transaction
14018     * you should also take other steps to protect against unexpected double inputs e.g. calling
14019     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
14020     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
14021     */
14022    public final void cancelPendingInputEvents() {
14023        dispatchCancelPendingInputEvents();
14024    }
14025
14026    /**
14027     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
14028     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
14029     */
14030    void dispatchCancelPendingInputEvents() {
14031        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
14032        onCancelPendingInputEvents();
14033        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
14034            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
14035                    " did not call through to super.onCancelPendingInputEvents()");
14036        }
14037    }
14038
14039    /**
14040     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
14041     * a parent view.
14042     *
14043     * <p>This method is responsible for removing any pending high-level input events that were
14044     * posted to the event queue to run later. Custom view classes that post their own deferred
14045     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
14046     * {@link android.os.Handler} should override this method, call
14047     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
14048     * </p>
14049     */
14050    public void onCancelPendingInputEvents() {
14051        removePerformClickCallback();
14052        cancelLongPress();
14053        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
14054    }
14055
14056    /**
14057     * Store this view hierarchy's frozen state into the given container.
14058     *
14059     * @param container The SparseArray in which to save the view's state.
14060     *
14061     * @see #restoreHierarchyState(android.util.SparseArray)
14062     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14063     * @see #onSaveInstanceState()
14064     */
14065    public void saveHierarchyState(SparseArray<Parcelable> container) {
14066        dispatchSaveInstanceState(container);
14067    }
14068
14069    /**
14070     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
14071     * this view and its children. May be overridden to modify how freezing happens to a
14072     * view's children; for example, some views may want to not store state for their children.
14073     *
14074     * @param container The SparseArray in which to save the view's state.
14075     *
14076     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14077     * @see #saveHierarchyState(android.util.SparseArray)
14078     * @see #onSaveInstanceState()
14079     */
14080    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
14081        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
14082            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14083            Parcelable state = onSaveInstanceState();
14084            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14085                throw new IllegalStateException(
14086                        "Derived class did not call super.onSaveInstanceState()");
14087            }
14088            if (state != null) {
14089                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
14090                // + ": " + state);
14091                container.put(mID, state);
14092            }
14093        }
14094    }
14095
14096    /**
14097     * Hook allowing a view to generate a representation of its internal state
14098     * that can later be used to create a new instance with that same state.
14099     * This state should only contain information that is not persistent or can
14100     * not be reconstructed later. For example, you will never store your
14101     * current position on screen because that will be computed again when a
14102     * new instance of the view is placed in its view hierarchy.
14103     * <p>
14104     * Some examples of things you may store here: the current cursor position
14105     * in a text view (but usually not the text itself since that is stored in a
14106     * content provider or other persistent storage), the currently selected
14107     * item in a list view.
14108     *
14109     * @return Returns a Parcelable object containing the view's current dynamic
14110     *         state, or null if there is nothing interesting to save. The
14111     *         default implementation returns null.
14112     * @see #onRestoreInstanceState(android.os.Parcelable)
14113     * @see #saveHierarchyState(android.util.SparseArray)
14114     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14115     * @see #setSaveEnabled(boolean)
14116     */
14117    @CallSuper
14118    protected Parcelable onSaveInstanceState() {
14119        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14120        if (mStartActivityRequestWho != null) {
14121            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
14122            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
14123            return state;
14124        }
14125        return BaseSavedState.EMPTY_STATE;
14126    }
14127
14128    /**
14129     * Restore this view hierarchy's frozen state from the given container.
14130     *
14131     * @param container The SparseArray which holds previously frozen states.
14132     *
14133     * @see #saveHierarchyState(android.util.SparseArray)
14134     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14135     * @see #onRestoreInstanceState(android.os.Parcelable)
14136     */
14137    public void restoreHierarchyState(SparseArray<Parcelable> container) {
14138        dispatchRestoreInstanceState(container);
14139    }
14140
14141    /**
14142     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
14143     * state for this view and its children. May be overridden to modify how restoring
14144     * happens to a view's children; for example, some views may want to not store state
14145     * for their children.
14146     *
14147     * @param container The SparseArray which holds previously saved state.
14148     *
14149     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14150     * @see #restoreHierarchyState(android.util.SparseArray)
14151     * @see #onRestoreInstanceState(android.os.Parcelable)
14152     */
14153    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
14154        if (mID != NO_ID) {
14155            Parcelable state = container.get(mID);
14156            if (state != null) {
14157                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
14158                // + ": " + state);
14159                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14160                onRestoreInstanceState(state);
14161                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14162                    throw new IllegalStateException(
14163                            "Derived class did not call super.onRestoreInstanceState()");
14164                }
14165            }
14166        }
14167    }
14168
14169    /**
14170     * Hook allowing a view to re-apply a representation of its internal state that had previously
14171     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
14172     * null state.
14173     *
14174     * @param state The frozen state that had previously been returned by
14175     *        {@link #onSaveInstanceState}.
14176     *
14177     * @see #onSaveInstanceState()
14178     * @see #restoreHierarchyState(android.util.SparseArray)
14179     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14180     */
14181    @CallSuper
14182    protected void onRestoreInstanceState(Parcelable state) {
14183        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14184        if (state != null && !(state instanceof AbsSavedState)) {
14185            throw new IllegalArgumentException("Wrong state class, expecting View State but "
14186                    + "received " + state.getClass().toString() + " instead. This usually happens "
14187                    + "when two views of different type have the same id in the same hierarchy. "
14188                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
14189                    + "other views do not use the same id.");
14190        }
14191        if (state != null && state instanceof BaseSavedState) {
14192            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
14193        }
14194    }
14195
14196    /**
14197     * <p>Return the time at which the drawing of the view hierarchy started.</p>
14198     *
14199     * @return the drawing start time in milliseconds
14200     */
14201    public long getDrawingTime() {
14202        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
14203    }
14204
14205    /**
14206     * <p>Enables or disables the duplication of the parent's state into this view. When
14207     * duplication is enabled, this view gets its drawable state from its parent rather
14208     * than from its own internal properties.</p>
14209     *
14210     * <p>Note: in the current implementation, setting this property to true after the
14211     * view was added to a ViewGroup might have no effect at all. This property should
14212     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
14213     *
14214     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
14215     * property is enabled, an exception will be thrown.</p>
14216     *
14217     * <p>Note: if the child view uses and updates additional states which are unknown to the
14218     * parent, these states should not be affected by this method.</p>
14219     *
14220     * @param enabled True to enable duplication of the parent's drawable state, false
14221     *                to disable it.
14222     *
14223     * @see #getDrawableState()
14224     * @see #isDuplicateParentStateEnabled()
14225     */
14226    public void setDuplicateParentStateEnabled(boolean enabled) {
14227        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
14228    }
14229
14230    /**
14231     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
14232     *
14233     * @return True if this view's drawable state is duplicated from the parent,
14234     *         false otherwise
14235     *
14236     * @see #getDrawableState()
14237     * @see #setDuplicateParentStateEnabled(boolean)
14238     */
14239    public boolean isDuplicateParentStateEnabled() {
14240        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
14241    }
14242
14243    /**
14244     * <p>Specifies the type of layer backing this view. The layer can be
14245     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14246     * {@link #LAYER_TYPE_HARDWARE}.</p>
14247     *
14248     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14249     * instance that controls how the layer is composed on screen. The following
14250     * properties of the paint are taken into account when composing the layer:</p>
14251     * <ul>
14252     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14253     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14254     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14255     * </ul>
14256     *
14257     * <p>If this view has an alpha value set to < 1.0 by calling
14258     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
14259     * by this view's alpha value.</p>
14260     *
14261     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
14262     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
14263     * for more information on when and how to use layers.</p>
14264     *
14265     * @param layerType The type of layer to use with this view, must be one of
14266     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14267     *        {@link #LAYER_TYPE_HARDWARE}
14268     * @param paint The paint used to compose the layer. This argument is optional
14269     *        and can be null. It is ignored when the layer type is
14270     *        {@link #LAYER_TYPE_NONE}
14271     *
14272     * @see #getLayerType()
14273     * @see #LAYER_TYPE_NONE
14274     * @see #LAYER_TYPE_SOFTWARE
14275     * @see #LAYER_TYPE_HARDWARE
14276     * @see #setAlpha(float)
14277     *
14278     * @attr ref android.R.styleable#View_layerType
14279     */
14280    public void setLayerType(int layerType, Paint paint) {
14281        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
14282            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
14283                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
14284        }
14285
14286        boolean typeChanged = mRenderNode.setLayerType(layerType);
14287
14288        if (!typeChanged) {
14289            setLayerPaint(paint);
14290            return;
14291        }
14292
14293        // Destroy any previous software drawing cache if needed
14294        if (mLayerType == LAYER_TYPE_SOFTWARE) {
14295            destroyDrawingCache();
14296        }
14297
14298        mLayerType = layerType;
14299        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
14300        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
14301        mRenderNode.setLayerPaint(mLayerPaint);
14302
14303        // draw() behaves differently if we are on a layer, so we need to
14304        // invalidate() here
14305        invalidateParentCaches();
14306        invalidate(true);
14307    }
14308
14309    /**
14310     * Updates the {@link Paint} object used with the current layer (used only if the current
14311     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
14312     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
14313     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
14314     * ensure that the view gets redrawn immediately.
14315     *
14316     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14317     * instance that controls how the layer is composed on screen. The following
14318     * properties of the paint are taken into account when composing the layer:</p>
14319     * <ul>
14320     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14321     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14322     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14323     * </ul>
14324     *
14325     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
14326     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
14327     *
14328     * @param paint The paint used to compose the layer. This argument is optional
14329     *        and can be null. It is ignored when the layer type is
14330     *        {@link #LAYER_TYPE_NONE}
14331     *
14332     * @see #setLayerType(int, android.graphics.Paint)
14333     */
14334    public void setLayerPaint(Paint paint) {
14335        int layerType = getLayerType();
14336        if (layerType != LAYER_TYPE_NONE) {
14337            mLayerPaint = paint == null ? new Paint() : paint;
14338            if (layerType == LAYER_TYPE_HARDWARE) {
14339                if (mRenderNode.setLayerPaint(mLayerPaint)) {
14340                    invalidateViewProperty(false, false);
14341                }
14342            } else {
14343                invalidate();
14344            }
14345        }
14346    }
14347
14348    /**
14349     * Indicates whether this view has a static layer. A view with layer type
14350     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
14351     * dynamic.
14352     */
14353    boolean hasStaticLayer() {
14354        return true;
14355    }
14356
14357    /**
14358     * Indicates what type of layer is currently associated with this view. By default
14359     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
14360     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
14361     * for more information on the different types of layers.
14362     *
14363     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14364     *         {@link #LAYER_TYPE_HARDWARE}
14365     *
14366     * @see #setLayerType(int, android.graphics.Paint)
14367     * @see #buildLayer()
14368     * @see #LAYER_TYPE_NONE
14369     * @see #LAYER_TYPE_SOFTWARE
14370     * @see #LAYER_TYPE_HARDWARE
14371     */
14372    public int getLayerType() {
14373        return mLayerType;
14374    }
14375
14376    /**
14377     * Forces this view's layer to be created and this view to be rendered
14378     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
14379     * invoking this method will have no effect.
14380     *
14381     * This method can for instance be used to render a view into its layer before
14382     * starting an animation. If this view is complex, rendering into the layer
14383     * before starting the animation will avoid skipping frames.
14384     *
14385     * @throws IllegalStateException If this view is not attached to a window
14386     *
14387     * @see #setLayerType(int, android.graphics.Paint)
14388     */
14389    public void buildLayer() {
14390        if (mLayerType == LAYER_TYPE_NONE) return;
14391
14392        final AttachInfo attachInfo = mAttachInfo;
14393        if (attachInfo == null) {
14394            throw new IllegalStateException("This view must be attached to a window first");
14395        }
14396
14397        if (getWidth() == 0 || getHeight() == 0) {
14398            return;
14399        }
14400
14401        switch (mLayerType) {
14402            case LAYER_TYPE_HARDWARE:
14403                updateDisplayListIfDirty();
14404                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
14405                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
14406                }
14407                break;
14408            case LAYER_TYPE_SOFTWARE:
14409                buildDrawingCache(true);
14410                break;
14411        }
14412    }
14413
14414    /**
14415     * If this View draws with a HardwareLayer, returns it.
14416     * Otherwise returns null
14417     *
14418     * TODO: Only TextureView uses this, can we eliminate it?
14419     */
14420    HardwareLayer getHardwareLayer() {
14421        return null;
14422    }
14423
14424    /**
14425     * Destroys all hardware rendering resources. This method is invoked
14426     * when the system needs to reclaim resources. Upon execution of this
14427     * method, you should free any OpenGL resources created by the view.
14428     *
14429     * Note: you <strong>must</strong> call
14430     * <code>super.destroyHardwareResources()</code> when overriding
14431     * this method.
14432     *
14433     * @hide
14434     */
14435    @CallSuper
14436    protected void destroyHardwareResources() {
14437        // Although the Layer will be destroyed by RenderNode, we want to release
14438        // the staging display list, which is also a signal to RenderNode that it's
14439        // safe to free its copy of the display list as it knows that we will
14440        // push an updated DisplayList if we try to draw again
14441        resetDisplayList();
14442    }
14443
14444    /**
14445     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
14446     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
14447     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
14448     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
14449     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
14450     * null.</p>
14451     *
14452     * <p>Enabling the drawing cache is similar to
14453     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
14454     * acceleration is turned off. When hardware acceleration is turned on, enabling the
14455     * drawing cache has no effect on rendering because the system uses a different mechanism
14456     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
14457     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
14458     * for information on how to enable software and hardware layers.</p>
14459     *
14460     * <p>This API can be used to manually generate
14461     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
14462     * {@link #getDrawingCache()}.</p>
14463     *
14464     * @param enabled true to enable the drawing cache, false otherwise
14465     *
14466     * @see #isDrawingCacheEnabled()
14467     * @see #getDrawingCache()
14468     * @see #buildDrawingCache()
14469     * @see #setLayerType(int, android.graphics.Paint)
14470     */
14471    public void setDrawingCacheEnabled(boolean enabled) {
14472        mCachingFailed = false;
14473        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
14474    }
14475
14476    /**
14477     * <p>Indicates whether the drawing cache is enabled for this view.</p>
14478     *
14479     * @return true if the drawing cache is enabled
14480     *
14481     * @see #setDrawingCacheEnabled(boolean)
14482     * @see #getDrawingCache()
14483     */
14484    @ViewDebug.ExportedProperty(category = "drawing")
14485    public boolean isDrawingCacheEnabled() {
14486        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
14487    }
14488
14489    /**
14490     * Debugging utility which recursively outputs the dirty state of a view and its
14491     * descendants.
14492     *
14493     * @hide
14494     */
14495    @SuppressWarnings({"UnusedDeclaration"})
14496    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
14497        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
14498                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
14499                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
14500                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
14501        if (clear) {
14502            mPrivateFlags &= clearMask;
14503        }
14504        if (this instanceof ViewGroup) {
14505            ViewGroup parent = (ViewGroup) this;
14506            final int count = parent.getChildCount();
14507            for (int i = 0; i < count; i++) {
14508                final View child = parent.getChildAt(i);
14509                child.outputDirtyFlags(indent + "  ", clear, clearMask);
14510            }
14511        }
14512    }
14513
14514    /**
14515     * This method is used by ViewGroup to cause its children to restore or recreate their
14516     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
14517     * to recreate its own display list, which would happen if it went through the normal
14518     * draw/dispatchDraw mechanisms.
14519     *
14520     * @hide
14521     */
14522    protected void dispatchGetDisplayList() {}
14523
14524    /**
14525     * A view that is not attached or hardware accelerated cannot create a display list.
14526     * This method checks these conditions and returns the appropriate result.
14527     *
14528     * @return true if view has the ability to create a display list, false otherwise.
14529     *
14530     * @hide
14531     */
14532    public boolean canHaveDisplayList() {
14533        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
14534    }
14535
14536    private void updateDisplayListIfDirty() {
14537        final RenderNode renderNode = mRenderNode;
14538        if (!canHaveDisplayList()) {
14539            // can't populate RenderNode, don't try
14540            return;
14541        }
14542
14543        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
14544                || !renderNode.isValid()
14545                || (mRecreateDisplayList)) {
14546            // Don't need to recreate the display list, just need to tell our
14547            // children to restore/recreate theirs
14548            if (renderNode.isValid()
14549                    && !mRecreateDisplayList) {
14550                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14551                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14552                dispatchGetDisplayList();
14553
14554                return; // no work needed
14555            }
14556
14557            // If we got here, we're recreating it. Mark it as such to ensure that
14558            // we copy in child display lists into ours in drawChild()
14559            mRecreateDisplayList = true;
14560
14561            int width = mRight - mLeft;
14562            int height = mBottom - mTop;
14563            int layerType = getLayerType();
14564
14565            final DisplayListCanvas canvas = renderNode.start(width, height);
14566            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
14567
14568            try {
14569                final HardwareLayer layer = getHardwareLayer();
14570                if (layer != null && layer.isValid()) {
14571                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
14572                } else if (layerType == LAYER_TYPE_SOFTWARE) {
14573                    buildDrawingCache(true);
14574                    Bitmap cache = getDrawingCache(true);
14575                    if (cache != null) {
14576                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14577                    }
14578                } else {
14579                    computeScroll();
14580
14581                    canvas.translate(-mScrollX, -mScrollY);
14582                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14583                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14584
14585                    // Fast path for layouts with no backgrounds
14586                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14587                        dispatchDraw(canvas);
14588                        if (mOverlay != null && !mOverlay.isEmpty()) {
14589                            mOverlay.getOverlayView().draw(canvas);
14590                        }
14591                    } else {
14592                        draw(canvas);
14593                    }
14594                }
14595            } finally {
14596                renderNode.end(canvas);
14597                setDisplayListProperties(renderNode);
14598            }
14599        } else {
14600            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14601            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14602        }
14603    }
14604
14605    /**
14606     * Returns a RenderNode with View draw content recorded, which can be
14607     * used to draw this view again without executing its draw method.
14608     *
14609     * @return A RenderNode ready to replay, or null if caching is not enabled.
14610     *
14611     * @hide
14612     */
14613    public RenderNode getDisplayList() {
14614        updateDisplayListIfDirty();
14615        return mRenderNode;
14616    }
14617
14618    private void resetDisplayList() {
14619        if (mRenderNode.isValid()) {
14620            mRenderNode.destroyDisplayListData();
14621        }
14622
14623        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
14624            mBackgroundRenderNode.destroyDisplayListData();
14625        }
14626    }
14627
14628    /**
14629     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14630     *
14631     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14632     *
14633     * @see #getDrawingCache(boolean)
14634     */
14635    public Bitmap getDrawingCache() {
14636        return getDrawingCache(false);
14637    }
14638
14639    /**
14640     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14641     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14642     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14643     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14644     * request the drawing cache by calling this method and draw it on screen if the
14645     * returned bitmap is not null.</p>
14646     *
14647     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14648     * this method will create a bitmap of the same size as this view. Because this bitmap
14649     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14650     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14651     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14652     * size than the view. This implies that your application must be able to handle this
14653     * size.</p>
14654     *
14655     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14656     *        the current density of the screen when the application is in compatibility
14657     *        mode.
14658     *
14659     * @return A bitmap representing this view or null if cache is disabled.
14660     *
14661     * @see #setDrawingCacheEnabled(boolean)
14662     * @see #isDrawingCacheEnabled()
14663     * @see #buildDrawingCache(boolean)
14664     * @see #destroyDrawingCache()
14665     */
14666    public Bitmap getDrawingCache(boolean autoScale) {
14667        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14668            return null;
14669        }
14670        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14671            buildDrawingCache(autoScale);
14672        }
14673        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14674    }
14675
14676    /**
14677     * <p>Frees the resources used by the drawing cache. If you call
14678     * {@link #buildDrawingCache()} manually without calling
14679     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14680     * should cleanup the cache with this method afterwards.</p>
14681     *
14682     * @see #setDrawingCacheEnabled(boolean)
14683     * @see #buildDrawingCache()
14684     * @see #getDrawingCache()
14685     */
14686    public void destroyDrawingCache() {
14687        if (mDrawingCache != null) {
14688            mDrawingCache.recycle();
14689            mDrawingCache = null;
14690        }
14691        if (mUnscaledDrawingCache != null) {
14692            mUnscaledDrawingCache.recycle();
14693            mUnscaledDrawingCache = null;
14694        }
14695    }
14696
14697    /**
14698     * Setting a solid background color for the drawing cache's bitmaps will improve
14699     * performance and memory usage. Note, though that this should only be used if this
14700     * view will always be drawn on top of a solid color.
14701     *
14702     * @param color The background color to use for the drawing cache's bitmap
14703     *
14704     * @see #setDrawingCacheEnabled(boolean)
14705     * @see #buildDrawingCache()
14706     * @see #getDrawingCache()
14707     */
14708    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
14709        if (color != mDrawingCacheBackgroundColor) {
14710            mDrawingCacheBackgroundColor = color;
14711            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14712        }
14713    }
14714
14715    /**
14716     * @see #setDrawingCacheBackgroundColor(int)
14717     *
14718     * @return The background color to used for the drawing cache's bitmap
14719     */
14720    @ColorInt
14721    public int getDrawingCacheBackgroundColor() {
14722        return mDrawingCacheBackgroundColor;
14723    }
14724
14725    /**
14726     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14727     *
14728     * @see #buildDrawingCache(boolean)
14729     */
14730    public void buildDrawingCache() {
14731        buildDrawingCache(false);
14732    }
14733
14734    /**
14735     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14736     *
14737     * <p>If you call {@link #buildDrawingCache()} manually without calling
14738     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14739     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14740     *
14741     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14742     * this method will create a bitmap of the same size as this view. Because this bitmap
14743     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14744     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14745     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14746     * size than the view. This implies that your application must be able to handle this
14747     * size.</p>
14748     *
14749     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14750     * you do not need the drawing cache bitmap, calling this method will increase memory
14751     * usage and cause the view to be rendered in software once, thus negatively impacting
14752     * performance.</p>
14753     *
14754     * @see #getDrawingCache()
14755     * @see #destroyDrawingCache()
14756     */
14757    public void buildDrawingCache(boolean autoScale) {
14758        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14759                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14760            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
14761                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
14762                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
14763            }
14764            try {
14765                buildDrawingCacheImpl(autoScale);
14766            } finally {
14767                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
14768            }
14769        }
14770    }
14771
14772    /**
14773     * private, internal implementation of buildDrawingCache, used to enable tracing
14774     */
14775    private void buildDrawingCacheImpl(boolean autoScale) {
14776        mCachingFailed = false;
14777
14778        int width = mRight - mLeft;
14779        int height = mBottom - mTop;
14780
14781        final AttachInfo attachInfo = mAttachInfo;
14782        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14783
14784        if (autoScale && scalingRequired) {
14785            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14786            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14787        }
14788
14789        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14790        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14791        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14792
14793        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14794        final long drawingCacheSize =
14795                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14796        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14797            if (width > 0 && height > 0) {
14798                Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14799                        + projectedBitmapSize + " bytes, only "
14800                        + drawingCacheSize + " available");
14801            }
14802            destroyDrawingCache();
14803            mCachingFailed = true;
14804            return;
14805        }
14806
14807        boolean clear = true;
14808        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14809
14810        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14811            Bitmap.Config quality;
14812            if (!opaque) {
14813                // Never pick ARGB_4444 because it looks awful
14814                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14815                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14816                    case DRAWING_CACHE_QUALITY_AUTO:
14817                    case DRAWING_CACHE_QUALITY_LOW:
14818                    case DRAWING_CACHE_QUALITY_HIGH:
14819                    default:
14820                        quality = Bitmap.Config.ARGB_8888;
14821                        break;
14822                }
14823            } else {
14824                // Optimization for translucent windows
14825                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14826                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14827            }
14828
14829            // Try to cleanup memory
14830            if (bitmap != null) bitmap.recycle();
14831
14832            try {
14833                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14834                        width, height, quality);
14835                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14836                if (autoScale) {
14837                    mDrawingCache = bitmap;
14838                } else {
14839                    mUnscaledDrawingCache = bitmap;
14840                }
14841                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14842            } catch (OutOfMemoryError e) {
14843                // If there is not enough memory to create the bitmap cache, just
14844                // ignore the issue as bitmap caches are not required to draw the
14845                // view hierarchy
14846                if (autoScale) {
14847                    mDrawingCache = null;
14848                } else {
14849                    mUnscaledDrawingCache = null;
14850                }
14851                mCachingFailed = true;
14852                return;
14853            }
14854
14855            clear = drawingCacheBackgroundColor != 0;
14856        }
14857
14858        Canvas canvas;
14859        if (attachInfo != null) {
14860            canvas = attachInfo.mCanvas;
14861            if (canvas == null) {
14862                canvas = new Canvas();
14863            }
14864            canvas.setBitmap(bitmap);
14865            // Temporarily clobber the cached Canvas in case one of our children
14866            // is also using a drawing cache. Without this, the children would
14867            // steal the canvas by attaching their own bitmap to it and bad, bad
14868            // thing would happen (invisible views, corrupted drawings, etc.)
14869            attachInfo.mCanvas = null;
14870        } else {
14871            // This case should hopefully never or seldom happen
14872            canvas = new Canvas(bitmap);
14873        }
14874
14875        if (clear) {
14876            bitmap.eraseColor(drawingCacheBackgroundColor);
14877        }
14878
14879        computeScroll();
14880        final int restoreCount = canvas.save();
14881
14882        if (autoScale && scalingRequired) {
14883            final float scale = attachInfo.mApplicationScale;
14884            canvas.scale(scale, scale);
14885        }
14886
14887        canvas.translate(-mScrollX, -mScrollY);
14888
14889        mPrivateFlags |= PFLAG_DRAWN;
14890        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14891                mLayerType != LAYER_TYPE_NONE) {
14892            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14893        }
14894
14895        // Fast path for layouts with no backgrounds
14896        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14897            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14898            dispatchDraw(canvas);
14899            if (mOverlay != null && !mOverlay.isEmpty()) {
14900                mOverlay.getOverlayView().draw(canvas);
14901            }
14902        } else {
14903            draw(canvas);
14904        }
14905
14906        canvas.restoreToCount(restoreCount);
14907        canvas.setBitmap(null);
14908
14909        if (attachInfo != null) {
14910            // Restore the cached Canvas for our siblings
14911            attachInfo.mCanvas = canvas;
14912        }
14913    }
14914
14915    /**
14916     * Create a snapshot of the view into a bitmap.  We should probably make
14917     * some form of this public, but should think about the API.
14918     */
14919    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14920        int width = mRight - mLeft;
14921        int height = mBottom - mTop;
14922
14923        final AttachInfo attachInfo = mAttachInfo;
14924        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14925        width = (int) ((width * scale) + 0.5f);
14926        height = (int) ((height * scale) + 0.5f);
14927
14928        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14929                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14930        if (bitmap == null) {
14931            throw new OutOfMemoryError();
14932        }
14933
14934        Resources resources = getResources();
14935        if (resources != null) {
14936            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14937        }
14938
14939        Canvas canvas;
14940        if (attachInfo != null) {
14941            canvas = attachInfo.mCanvas;
14942            if (canvas == null) {
14943                canvas = new Canvas();
14944            }
14945            canvas.setBitmap(bitmap);
14946            // Temporarily clobber the cached Canvas in case one of our children
14947            // is also using a drawing cache. Without this, the children would
14948            // steal the canvas by attaching their own bitmap to it and bad, bad
14949            // things would happen (invisible views, corrupted drawings, etc.)
14950            attachInfo.mCanvas = null;
14951        } else {
14952            // This case should hopefully never or seldom happen
14953            canvas = new Canvas(bitmap);
14954        }
14955
14956        if ((backgroundColor & 0xff000000) != 0) {
14957            bitmap.eraseColor(backgroundColor);
14958        }
14959
14960        computeScroll();
14961        final int restoreCount = canvas.save();
14962        canvas.scale(scale, scale);
14963        canvas.translate(-mScrollX, -mScrollY);
14964
14965        // Temporarily remove the dirty mask
14966        int flags = mPrivateFlags;
14967        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14968
14969        // Fast path for layouts with no backgrounds
14970        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14971            dispatchDraw(canvas);
14972            if (mOverlay != null && !mOverlay.isEmpty()) {
14973                mOverlay.getOverlayView().draw(canvas);
14974            }
14975        } else {
14976            draw(canvas);
14977        }
14978
14979        mPrivateFlags = flags;
14980
14981        canvas.restoreToCount(restoreCount);
14982        canvas.setBitmap(null);
14983
14984        if (attachInfo != null) {
14985            // Restore the cached Canvas for our siblings
14986            attachInfo.mCanvas = canvas;
14987        }
14988
14989        return bitmap;
14990    }
14991
14992    /**
14993     * Indicates whether this View is currently in edit mode. A View is usually
14994     * in edit mode when displayed within a developer tool. For instance, if
14995     * this View is being drawn by a visual user interface builder, this method
14996     * should return true.
14997     *
14998     * Subclasses should check the return value of this method to provide
14999     * different behaviors if their normal behavior might interfere with the
15000     * host environment. For instance: the class spawns a thread in its
15001     * constructor, the drawing code relies on device-specific features, etc.
15002     *
15003     * This method is usually checked in the drawing code of custom widgets.
15004     *
15005     * @return True if this View is in edit mode, false otherwise.
15006     */
15007    public boolean isInEditMode() {
15008        return false;
15009    }
15010
15011    /**
15012     * If the View draws content inside its padding and enables fading edges,
15013     * it needs to support padding offsets. Padding offsets are added to the
15014     * fading edges to extend the length of the fade so that it covers pixels
15015     * drawn inside the padding.
15016     *
15017     * Subclasses of this class should override this method if they need
15018     * to draw content inside the padding.
15019     *
15020     * @return True if padding offset must be applied, false otherwise.
15021     *
15022     * @see #getLeftPaddingOffset()
15023     * @see #getRightPaddingOffset()
15024     * @see #getTopPaddingOffset()
15025     * @see #getBottomPaddingOffset()
15026     *
15027     * @since CURRENT
15028     */
15029    protected boolean isPaddingOffsetRequired() {
15030        return false;
15031    }
15032
15033    /**
15034     * Amount by which to extend the left fading region. Called only when
15035     * {@link #isPaddingOffsetRequired()} returns true.
15036     *
15037     * @return The left padding offset in pixels.
15038     *
15039     * @see #isPaddingOffsetRequired()
15040     *
15041     * @since CURRENT
15042     */
15043    protected int getLeftPaddingOffset() {
15044        return 0;
15045    }
15046
15047    /**
15048     * Amount by which to extend the right fading region. Called only when
15049     * {@link #isPaddingOffsetRequired()} returns true.
15050     *
15051     * @return The right padding offset in pixels.
15052     *
15053     * @see #isPaddingOffsetRequired()
15054     *
15055     * @since CURRENT
15056     */
15057    protected int getRightPaddingOffset() {
15058        return 0;
15059    }
15060
15061    /**
15062     * Amount by which to extend the top fading region. Called only when
15063     * {@link #isPaddingOffsetRequired()} returns true.
15064     *
15065     * @return The top padding offset in pixels.
15066     *
15067     * @see #isPaddingOffsetRequired()
15068     *
15069     * @since CURRENT
15070     */
15071    protected int getTopPaddingOffset() {
15072        return 0;
15073    }
15074
15075    /**
15076     * Amount by which to extend the bottom fading region. Called only when
15077     * {@link #isPaddingOffsetRequired()} returns true.
15078     *
15079     * @return The bottom padding offset in pixels.
15080     *
15081     * @see #isPaddingOffsetRequired()
15082     *
15083     * @since CURRENT
15084     */
15085    protected int getBottomPaddingOffset() {
15086        return 0;
15087    }
15088
15089    /**
15090     * @hide
15091     * @param offsetRequired
15092     */
15093    protected int getFadeTop(boolean offsetRequired) {
15094        int top = mPaddingTop;
15095        if (offsetRequired) top += getTopPaddingOffset();
15096        return top;
15097    }
15098
15099    /**
15100     * @hide
15101     * @param offsetRequired
15102     */
15103    protected int getFadeHeight(boolean offsetRequired) {
15104        int padding = mPaddingTop;
15105        if (offsetRequired) padding += getTopPaddingOffset();
15106        return mBottom - mTop - mPaddingBottom - padding;
15107    }
15108
15109    /**
15110     * <p>Indicates whether this view is attached to a hardware accelerated
15111     * window or not.</p>
15112     *
15113     * <p>Even if this method returns true, it does not mean that every call
15114     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
15115     * accelerated {@link android.graphics.Canvas}. For instance, if this view
15116     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
15117     * window is hardware accelerated,
15118     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
15119     * return false, and this method will return true.</p>
15120     *
15121     * @return True if the view is attached to a window and the window is
15122     *         hardware accelerated; false in any other case.
15123     */
15124    @ViewDebug.ExportedProperty(category = "drawing")
15125    public boolean isHardwareAccelerated() {
15126        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
15127    }
15128
15129    /**
15130     * Sets a rectangular area on this view to which the view will be clipped
15131     * when it is drawn. Setting the value to null will remove the clip bounds
15132     * and the view will draw normally, using its full bounds.
15133     *
15134     * @param clipBounds The rectangular area, in the local coordinates of
15135     * this view, to which future drawing operations will be clipped.
15136     */
15137    public void setClipBounds(Rect clipBounds) {
15138        if (clipBounds == mClipBounds
15139                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
15140            return;
15141        }
15142        if (clipBounds != null) {
15143            if (mClipBounds == null) {
15144                mClipBounds = new Rect(clipBounds);
15145            } else {
15146                mClipBounds.set(clipBounds);
15147            }
15148        } else {
15149            mClipBounds = null;
15150        }
15151        mRenderNode.setClipBounds(mClipBounds);
15152        invalidateViewProperty(false, false);
15153    }
15154
15155    /**
15156     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
15157     *
15158     * @return A copy of the current clip bounds if clip bounds are set,
15159     * otherwise null.
15160     */
15161    public Rect getClipBounds() {
15162        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
15163    }
15164
15165
15166    /**
15167     * Populates an output rectangle with the clip bounds of the view,
15168     * returning {@code true} if successful or {@code false} if the view's
15169     * clip bounds are {@code null}.
15170     *
15171     * @param outRect rectangle in which to place the clip bounds of the view
15172     * @return {@code true} if successful or {@code false} if the view's
15173     *         clip bounds are {@code null}
15174     */
15175    public boolean getClipBounds(Rect outRect) {
15176        if (mClipBounds != null) {
15177            outRect.set(mClipBounds);
15178            return true;
15179        }
15180        return false;
15181    }
15182
15183    /**
15184     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
15185     * case of an active Animation being run on the view.
15186     */
15187    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
15188            Animation a, boolean scalingRequired) {
15189        Transformation invalidationTransform;
15190        final int flags = parent.mGroupFlags;
15191        final boolean initialized = a.isInitialized();
15192        if (!initialized) {
15193            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
15194            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
15195            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
15196            onAnimationStart();
15197        }
15198
15199        final Transformation t = parent.getChildTransformation();
15200        boolean more = a.getTransformation(drawingTime, t, 1f);
15201        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
15202            if (parent.mInvalidationTransformation == null) {
15203                parent.mInvalidationTransformation = new Transformation();
15204            }
15205            invalidationTransform = parent.mInvalidationTransformation;
15206            a.getTransformation(drawingTime, invalidationTransform, 1f);
15207        } else {
15208            invalidationTransform = t;
15209        }
15210
15211        if (more) {
15212            if (!a.willChangeBounds()) {
15213                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
15214                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
15215                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
15216                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
15217                    // The child need to draw an animation, potentially offscreen, so
15218                    // make sure we do not cancel invalidate requests
15219                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15220                    parent.invalidate(mLeft, mTop, mRight, mBottom);
15221                }
15222            } else {
15223                if (parent.mInvalidateRegion == null) {
15224                    parent.mInvalidateRegion = new RectF();
15225                }
15226                final RectF region = parent.mInvalidateRegion;
15227                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
15228                        invalidationTransform);
15229
15230                // The child need to draw an animation, potentially offscreen, so
15231                // make sure we do not cancel invalidate requests
15232                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15233
15234                final int left = mLeft + (int) region.left;
15235                final int top = mTop + (int) region.top;
15236                parent.invalidate(left, top, left + (int) (region.width() + .5f),
15237                        top + (int) (region.height() + .5f));
15238            }
15239        }
15240        return more;
15241    }
15242
15243    /**
15244     * This method is called by getDisplayList() when a display list is recorded for a View.
15245     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
15246     */
15247    void setDisplayListProperties(RenderNode renderNode) {
15248        if (renderNode != null) {
15249            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
15250            renderNode.setClipToBounds(mParent instanceof ViewGroup
15251                    && ((ViewGroup) mParent).getClipChildren());
15252
15253            float alpha = 1;
15254            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
15255                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15256                ViewGroup parentVG = (ViewGroup) mParent;
15257                final Transformation t = parentVG.getChildTransformation();
15258                if (parentVG.getChildStaticTransformation(this, t)) {
15259                    final int transformType = t.getTransformationType();
15260                    if (transformType != Transformation.TYPE_IDENTITY) {
15261                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
15262                            alpha = t.getAlpha();
15263                        }
15264                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
15265                            renderNode.setStaticMatrix(t.getMatrix());
15266                        }
15267                    }
15268                }
15269            }
15270            if (mTransformationInfo != null) {
15271                alpha *= getFinalAlpha();
15272                if (alpha < 1) {
15273                    final int multipliedAlpha = (int) (255 * alpha);
15274                    if (onSetAlpha(multipliedAlpha)) {
15275                        alpha = 1;
15276                    }
15277                }
15278                renderNode.setAlpha(alpha);
15279            } else if (alpha < 1) {
15280                renderNode.setAlpha(alpha);
15281            }
15282        }
15283    }
15284
15285    /**
15286     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
15287     *
15288     * This is where the View specializes rendering behavior based on layer type,
15289     * and hardware acceleration.
15290     */
15291    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
15292        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
15293        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
15294         *
15295         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
15296         * HW accelerated, it can't handle drawing RenderNodes.
15297         */
15298        boolean drawingWithRenderNode = mAttachInfo != null
15299                && mAttachInfo.mHardwareAccelerated
15300                && hardwareAcceleratedCanvas;
15301
15302        boolean more = false;
15303        final boolean childHasIdentityMatrix = hasIdentityMatrix();
15304        final int parentFlags = parent.mGroupFlags;
15305
15306        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
15307            parent.getChildTransformation().clear();
15308            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15309        }
15310
15311        Transformation transformToApply = null;
15312        boolean concatMatrix = false;
15313        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
15314        final Animation a = getAnimation();
15315        if (a != null) {
15316            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
15317            concatMatrix = a.willChangeTransformationMatrix();
15318            if (concatMatrix) {
15319                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15320            }
15321            transformToApply = parent.getChildTransformation();
15322        } else {
15323            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
15324                // No longer animating: clear out old animation matrix
15325                mRenderNode.setAnimationMatrix(null);
15326                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15327            }
15328            if (!drawingWithRenderNode
15329                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15330                final Transformation t = parent.getChildTransformation();
15331                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
15332                if (hasTransform) {
15333                    final int transformType = t.getTransformationType();
15334                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
15335                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
15336                }
15337            }
15338        }
15339
15340        concatMatrix |= !childHasIdentityMatrix;
15341
15342        // Sets the flag as early as possible to allow draw() implementations
15343        // to call invalidate() successfully when doing animations
15344        mPrivateFlags |= PFLAG_DRAWN;
15345
15346        if (!concatMatrix &&
15347                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
15348                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
15349                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
15350                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
15351            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
15352            return more;
15353        }
15354        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
15355
15356        if (hardwareAcceleratedCanvas) {
15357            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
15358            // retain the flag's value temporarily in the mRecreateDisplayList flag
15359            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
15360            mPrivateFlags &= ~PFLAG_INVALIDATED;
15361        }
15362
15363        RenderNode renderNode = null;
15364        Bitmap cache = null;
15365        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
15366        if (layerType == LAYER_TYPE_SOFTWARE
15367                || (!drawingWithRenderNode && layerType != LAYER_TYPE_NONE)) {
15368            // If not drawing with RenderNode, treat HW layers as SW
15369            layerType = LAYER_TYPE_SOFTWARE;
15370            buildDrawingCache(true);
15371            cache = getDrawingCache(true);
15372        }
15373
15374        if (drawingWithRenderNode) {
15375            // Delay getting the display list until animation-driven alpha values are
15376            // set up and possibly passed on to the view
15377            renderNode = getDisplayList();
15378            if (!renderNode.isValid()) {
15379                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15380                // to getDisplayList(), the display list will be marked invalid and we should not
15381                // try to use it again.
15382                renderNode = null;
15383                drawingWithRenderNode = false;
15384            }
15385        }
15386
15387        int sx = 0;
15388        int sy = 0;
15389        if (!drawingWithRenderNode) {
15390            computeScroll();
15391            sx = mScrollX;
15392            sy = mScrollY;
15393        }
15394
15395        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
15396        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
15397
15398        int restoreTo = -1;
15399        if (!drawingWithRenderNode || transformToApply != null) {
15400            restoreTo = canvas.save();
15401        }
15402        if (offsetForScroll) {
15403            canvas.translate(mLeft - sx, mTop - sy);
15404        } else {
15405            if (!drawingWithRenderNode) {
15406                canvas.translate(mLeft, mTop);
15407            }
15408            if (scalingRequired) {
15409                if (drawingWithRenderNode) {
15410                    // TODO: Might not need this if we put everything inside the DL
15411                    restoreTo = canvas.save();
15412                }
15413                // mAttachInfo cannot be null, otherwise scalingRequired == false
15414                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15415                canvas.scale(scale, scale);
15416            }
15417        }
15418
15419        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
15420        if (transformToApply != null
15421                || alpha < 1
15422                || !hasIdentityMatrix()
15423                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
15424            if (transformToApply != null || !childHasIdentityMatrix) {
15425                int transX = 0;
15426                int transY = 0;
15427
15428                if (offsetForScroll) {
15429                    transX = -sx;
15430                    transY = -sy;
15431                }
15432
15433                if (transformToApply != null) {
15434                    if (concatMatrix) {
15435                        if (drawingWithRenderNode) {
15436                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
15437                        } else {
15438                            // Undo the scroll translation, apply the transformation matrix,
15439                            // then redo the scroll translate to get the correct result.
15440                            canvas.translate(-transX, -transY);
15441                            canvas.concat(transformToApply.getMatrix());
15442                            canvas.translate(transX, transY);
15443                        }
15444                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15445                    }
15446
15447                    float transformAlpha = transformToApply.getAlpha();
15448                    if (transformAlpha < 1) {
15449                        alpha *= transformAlpha;
15450                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15451                    }
15452                }
15453
15454                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
15455                    canvas.translate(-transX, -transY);
15456                    canvas.concat(getMatrix());
15457                    canvas.translate(transX, transY);
15458                }
15459            }
15460
15461            // Deal with alpha if it is or used to be <1
15462            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
15463                if (alpha < 1) {
15464                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15465                } else {
15466                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15467                }
15468                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15469                if (!drawingWithDrawingCache) {
15470                    final int multipliedAlpha = (int) (255 * alpha);
15471                    if (!onSetAlpha(multipliedAlpha)) {
15472                        if (drawingWithRenderNode) {
15473                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
15474                        } else if (layerType == LAYER_TYPE_NONE) {
15475                            int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15476                            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0) {
15477                                layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
15478                            }
15479                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
15480                                    multipliedAlpha, layerFlags);
15481                        }
15482                    } else {
15483                        // Alpha is handled by the child directly, clobber the layer's alpha
15484                        mPrivateFlags |= PFLAG_ALPHA_SET;
15485                    }
15486                }
15487            }
15488        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15489            onSetAlpha(255);
15490            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15491        }
15492
15493        if (!drawingWithRenderNode) {
15494            // apply clips directly, since RenderNode won't do it for this draw
15495            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
15496                if (offsetForScroll) {
15497                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
15498                } else {
15499                    if (!scalingRequired || cache == null) {
15500                        canvas.clipRect(0, 0, getWidth(), getHeight());
15501                    } else {
15502                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
15503                    }
15504                }
15505            }
15506
15507            if (mClipBounds != null) {
15508                // clip bounds ignore scroll
15509                canvas.clipRect(mClipBounds);
15510            }
15511        }
15512
15513        if (!drawingWithDrawingCache) {
15514            if (drawingWithRenderNode) {
15515                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15516                ((DisplayListCanvas) canvas).drawRenderNode(renderNode, parentFlags);
15517            } else {
15518                // Fast path for layouts with no backgrounds
15519                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15520                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15521                    dispatchDraw(canvas);
15522                } else {
15523                    draw(canvas);
15524                }
15525            }
15526        } else if (cache != null) {
15527            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15528            Paint cachePaint;
15529            int restoreAlpha = 0;
15530
15531            if (layerType == LAYER_TYPE_NONE) {
15532                cachePaint = parent.mCachePaint;
15533                if (cachePaint == null) {
15534                    cachePaint = new Paint();
15535                    cachePaint.setDither(false);
15536                    parent.mCachePaint = cachePaint;
15537                }
15538            } else {
15539                cachePaint = mLayerPaint;
15540                restoreAlpha = mLayerPaint.getAlpha();
15541            }
15542            cachePaint.setAlpha((int) (alpha * 255));
15543            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15544            cachePaint.setAlpha(restoreAlpha);
15545        }
15546
15547        if (restoreTo >= 0) {
15548            canvas.restoreToCount(restoreTo);
15549        }
15550
15551        if (a != null && !more) {
15552            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
15553                onSetAlpha(255);
15554            }
15555            parent.finishAnimatingView(this, a);
15556        }
15557
15558        if (more && hardwareAcceleratedCanvas) {
15559            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15560                // alpha animations should cause the child to recreate its display list
15561                invalidate(true);
15562            }
15563        }
15564
15565        mRecreateDisplayList = false;
15566
15567        return more;
15568    }
15569
15570    /**
15571     * Manually render this view (and all of its children) to the given Canvas.
15572     * The view must have already done a full layout before this function is
15573     * called.  When implementing a view, implement
15574     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15575     * If you do need to override this method, call the superclass version.
15576     *
15577     * @param canvas The Canvas to which the View is rendered.
15578     */
15579    @CallSuper
15580    public void draw(Canvas canvas) {
15581        final int privateFlags = mPrivateFlags;
15582        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15583                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15584        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15585
15586        /*
15587         * Draw traversal performs several drawing steps which must be executed
15588         * in the appropriate order:
15589         *
15590         *      1. Draw the background
15591         *      2. If necessary, save the canvas' layers to prepare for fading
15592         *      3. Draw view's content
15593         *      4. Draw children
15594         *      5. If necessary, draw the fading edges and restore layers
15595         *      6. Draw decorations (scrollbars for instance)
15596         */
15597
15598        // Step 1, draw the background, if needed
15599        int saveCount;
15600
15601        if (!dirtyOpaque) {
15602            drawBackground(canvas);
15603        }
15604
15605        // skip step 2 & 5 if possible (common case)
15606        final int viewFlags = mViewFlags;
15607        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15608        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15609        if (!verticalEdges && !horizontalEdges) {
15610            // Step 3, draw the content
15611            if (!dirtyOpaque) onDraw(canvas);
15612
15613            // Step 4, draw the children
15614            dispatchDraw(canvas);
15615
15616            // Overlay is part of the content and draws beneath Foreground
15617            if (mOverlay != null && !mOverlay.isEmpty()) {
15618                mOverlay.getOverlayView().dispatchDraw(canvas);
15619            }
15620
15621            // Step 6, draw decorations (foreground, scrollbars)
15622            onDrawForeground(canvas);
15623
15624            // we're done...
15625            return;
15626        }
15627
15628        /*
15629         * Here we do the full fledged routine...
15630         * (this is an uncommon case where speed matters less,
15631         * this is why we repeat some of the tests that have been
15632         * done above)
15633         */
15634
15635        boolean drawTop = false;
15636        boolean drawBottom = false;
15637        boolean drawLeft = false;
15638        boolean drawRight = false;
15639
15640        float topFadeStrength = 0.0f;
15641        float bottomFadeStrength = 0.0f;
15642        float leftFadeStrength = 0.0f;
15643        float rightFadeStrength = 0.0f;
15644
15645        // Step 2, save the canvas' layers
15646        int paddingLeft = mPaddingLeft;
15647
15648        final boolean offsetRequired = isPaddingOffsetRequired();
15649        if (offsetRequired) {
15650            paddingLeft += getLeftPaddingOffset();
15651        }
15652
15653        int left = mScrollX + paddingLeft;
15654        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15655        int top = mScrollY + getFadeTop(offsetRequired);
15656        int bottom = top + getFadeHeight(offsetRequired);
15657
15658        if (offsetRequired) {
15659            right += getRightPaddingOffset();
15660            bottom += getBottomPaddingOffset();
15661        }
15662
15663        final ScrollabilityCache scrollabilityCache = mScrollCache;
15664        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15665        int length = (int) fadeHeight;
15666
15667        // clip the fade length if top and bottom fades overlap
15668        // overlapping fades produce odd-looking artifacts
15669        if (verticalEdges && (top + length > bottom - length)) {
15670            length = (bottom - top) / 2;
15671        }
15672
15673        // also clip horizontal fades if necessary
15674        if (horizontalEdges && (left + length > right - length)) {
15675            length = (right - left) / 2;
15676        }
15677
15678        if (verticalEdges) {
15679            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15680            drawTop = topFadeStrength * fadeHeight > 1.0f;
15681            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15682            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15683        }
15684
15685        if (horizontalEdges) {
15686            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15687            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15688            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15689            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15690        }
15691
15692        saveCount = canvas.getSaveCount();
15693
15694        int solidColor = getSolidColor();
15695        if (solidColor == 0) {
15696            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15697
15698            if (drawTop) {
15699                canvas.saveLayer(left, top, right, top + length, null, flags);
15700            }
15701
15702            if (drawBottom) {
15703                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15704            }
15705
15706            if (drawLeft) {
15707                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15708            }
15709
15710            if (drawRight) {
15711                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15712            }
15713        } else {
15714            scrollabilityCache.setFadeColor(solidColor);
15715        }
15716
15717        // Step 3, draw the content
15718        if (!dirtyOpaque) onDraw(canvas);
15719
15720        // Step 4, draw the children
15721        dispatchDraw(canvas);
15722
15723        // Step 5, draw the fade effect and restore layers
15724        final Paint p = scrollabilityCache.paint;
15725        final Matrix matrix = scrollabilityCache.matrix;
15726        final Shader fade = scrollabilityCache.shader;
15727
15728        if (drawTop) {
15729            matrix.setScale(1, fadeHeight * topFadeStrength);
15730            matrix.postTranslate(left, top);
15731            fade.setLocalMatrix(matrix);
15732            p.setShader(fade);
15733            canvas.drawRect(left, top, right, top + length, p);
15734        }
15735
15736        if (drawBottom) {
15737            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15738            matrix.postRotate(180);
15739            matrix.postTranslate(left, bottom);
15740            fade.setLocalMatrix(matrix);
15741            p.setShader(fade);
15742            canvas.drawRect(left, bottom - length, right, bottom, p);
15743        }
15744
15745        if (drawLeft) {
15746            matrix.setScale(1, fadeHeight * leftFadeStrength);
15747            matrix.postRotate(-90);
15748            matrix.postTranslate(left, top);
15749            fade.setLocalMatrix(matrix);
15750            p.setShader(fade);
15751            canvas.drawRect(left, top, left + length, bottom, p);
15752        }
15753
15754        if (drawRight) {
15755            matrix.setScale(1, fadeHeight * rightFadeStrength);
15756            matrix.postRotate(90);
15757            matrix.postTranslate(right, top);
15758            fade.setLocalMatrix(matrix);
15759            p.setShader(fade);
15760            canvas.drawRect(right - length, top, right, bottom, p);
15761        }
15762
15763        canvas.restoreToCount(saveCount);
15764
15765        // Overlay is part of the content and draws beneath Foreground
15766        if (mOverlay != null && !mOverlay.isEmpty()) {
15767            mOverlay.getOverlayView().dispatchDraw(canvas);
15768        }
15769
15770        // Step 6, draw decorations (foreground, scrollbars)
15771        onDrawForeground(canvas);
15772    }
15773
15774    /**
15775     * Draws the background onto the specified canvas.
15776     *
15777     * @param canvas Canvas on which to draw the background
15778     */
15779    private void drawBackground(Canvas canvas) {
15780        final Drawable background = mBackground;
15781        if (background == null) {
15782            return;
15783        }
15784
15785        if (mBackgroundSizeChanged) {
15786            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15787            mBackgroundSizeChanged = false;
15788            rebuildOutline();
15789        }
15790
15791        // Attempt to use a display list if requested.
15792        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15793                && mAttachInfo.mHardwareRenderer != null) {
15794            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15795
15796            final RenderNode renderNode = mBackgroundRenderNode;
15797            if (renderNode != null && renderNode.isValid()) {
15798                setBackgroundRenderNodeProperties(renderNode);
15799                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
15800                return;
15801            }
15802        }
15803
15804        final int scrollX = mScrollX;
15805        final int scrollY = mScrollY;
15806        if ((scrollX | scrollY) == 0) {
15807            background.draw(canvas);
15808        } else {
15809            canvas.translate(scrollX, scrollY);
15810            background.draw(canvas);
15811            canvas.translate(-scrollX, -scrollY);
15812        }
15813    }
15814
15815    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
15816        renderNode.setTranslationX(mScrollX);
15817        renderNode.setTranslationY(mScrollY);
15818    }
15819
15820    /**
15821     * Creates a new display list or updates the existing display list for the
15822     * specified Drawable.
15823     *
15824     * @param drawable Drawable for which to create a display list
15825     * @param renderNode Existing RenderNode, or {@code null}
15826     * @return A valid display list for the specified drawable
15827     */
15828    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15829        if (renderNode == null) {
15830            renderNode = RenderNode.create(drawable.getClass().getName(), this);
15831        }
15832
15833        final Rect bounds = drawable.getBounds();
15834        final int width = bounds.width();
15835        final int height = bounds.height();
15836        final DisplayListCanvas canvas = renderNode.start(width, height);
15837
15838        // Reverse left/top translation done by drawable canvas, which will
15839        // instead be applied by rendernode's LTRB bounds below. This way, the
15840        // drawable's bounds match with its rendernode bounds and its content
15841        // will lie within those bounds in the rendernode tree.
15842        canvas.translate(-bounds.left, -bounds.top);
15843
15844        try {
15845            drawable.draw(canvas);
15846        } finally {
15847            renderNode.end(canvas);
15848        }
15849
15850        // Set up drawable properties that are view-independent.
15851        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15852        renderNode.setProjectBackwards(drawable.isProjected());
15853        renderNode.setProjectionReceiver(true);
15854        renderNode.setClipToBounds(false);
15855        return renderNode;
15856    }
15857
15858    /**
15859     * Returns the overlay for this view, creating it if it does not yet exist.
15860     * Adding drawables to the overlay will cause them to be displayed whenever
15861     * the view itself is redrawn. Objects in the overlay should be actively
15862     * managed: remove them when they should not be displayed anymore. The
15863     * overlay will always have the same size as its host view.
15864     *
15865     * <p>Note: Overlays do not currently work correctly with {@link
15866     * SurfaceView} or {@link TextureView}; contents in overlays for these
15867     * types of views may not display correctly.</p>
15868     *
15869     * @return The ViewOverlay object for this view.
15870     * @see ViewOverlay
15871     */
15872    public ViewOverlay getOverlay() {
15873        if (mOverlay == null) {
15874            mOverlay = new ViewOverlay(mContext, this);
15875        }
15876        return mOverlay;
15877    }
15878
15879    /**
15880     * Override this if your view is known to always be drawn on top of a solid color background,
15881     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15882     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15883     * should be set to 0xFF.
15884     *
15885     * @see #setVerticalFadingEdgeEnabled(boolean)
15886     * @see #setHorizontalFadingEdgeEnabled(boolean)
15887     *
15888     * @return The known solid color background for this view, or 0 if the color may vary
15889     */
15890    @ViewDebug.ExportedProperty(category = "drawing")
15891    @ColorInt
15892    public int getSolidColor() {
15893        return 0;
15894    }
15895
15896    /**
15897     * Build a human readable string representation of the specified view flags.
15898     *
15899     * @param flags the view flags to convert to a string
15900     * @return a String representing the supplied flags
15901     */
15902    private static String printFlags(int flags) {
15903        String output = "";
15904        int numFlags = 0;
15905        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15906            output += "TAKES_FOCUS";
15907            numFlags++;
15908        }
15909
15910        switch (flags & VISIBILITY_MASK) {
15911        case INVISIBLE:
15912            if (numFlags > 0) {
15913                output += " ";
15914            }
15915            output += "INVISIBLE";
15916            // USELESS HERE numFlags++;
15917            break;
15918        case GONE:
15919            if (numFlags > 0) {
15920                output += " ";
15921            }
15922            output += "GONE";
15923            // USELESS HERE numFlags++;
15924            break;
15925        default:
15926            break;
15927        }
15928        return output;
15929    }
15930
15931    /**
15932     * Build a human readable string representation of the specified private
15933     * view flags.
15934     *
15935     * @param privateFlags the private view flags to convert to a string
15936     * @return a String representing the supplied flags
15937     */
15938    private static String printPrivateFlags(int privateFlags) {
15939        String output = "";
15940        int numFlags = 0;
15941
15942        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15943            output += "WANTS_FOCUS";
15944            numFlags++;
15945        }
15946
15947        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15948            if (numFlags > 0) {
15949                output += " ";
15950            }
15951            output += "FOCUSED";
15952            numFlags++;
15953        }
15954
15955        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15956            if (numFlags > 0) {
15957                output += " ";
15958            }
15959            output += "SELECTED";
15960            numFlags++;
15961        }
15962
15963        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15964            if (numFlags > 0) {
15965                output += " ";
15966            }
15967            output += "IS_ROOT_NAMESPACE";
15968            numFlags++;
15969        }
15970
15971        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15972            if (numFlags > 0) {
15973                output += " ";
15974            }
15975            output += "HAS_BOUNDS";
15976            numFlags++;
15977        }
15978
15979        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15980            if (numFlags > 0) {
15981                output += " ";
15982            }
15983            output += "DRAWN";
15984            // USELESS HERE numFlags++;
15985        }
15986        return output;
15987    }
15988
15989    /**
15990     * <p>Indicates whether or not this view's layout will be requested during
15991     * the next hierarchy layout pass.</p>
15992     *
15993     * @return true if the layout will be forced during next layout pass
15994     */
15995    public boolean isLayoutRequested() {
15996        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15997    }
15998
15999    /**
16000     * Return true if o is a ViewGroup that is laying out using optical bounds.
16001     * @hide
16002     */
16003    public static boolean isLayoutModeOptical(Object o) {
16004        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
16005    }
16006
16007    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
16008        Insets parentInsets = mParent instanceof View ?
16009                ((View) mParent).getOpticalInsets() : Insets.NONE;
16010        Insets childInsets = getOpticalInsets();
16011        return setFrame(
16012                left   + parentInsets.left - childInsets.left,
16013                top    + parentInsets.top  - childInsets.top,
16014                right  + parentInsets.left + childInsets.right,
16015                bottom + parentInsets.top  + childInsets.bottom);
16016    }
16017
16018    /**
16019     * Assign a size and position to a view and all of its
16020     * descendants
16021     *
16022     * <p>This is the second phase of the layout mechanism.
16023     * (The first is measuring). In this phase, each parent calls
16024     * layout on all of its children to position them.
16025     * This is typically done using the child measurements
16026     * that were stored in the measure pass().</p>
16027     *
16028     * <p>Derived classes should not override this method.
16029     * Derived classes with children should override
16030     * onLayout. In that method, they should
16031     * call layout on each of their children.</p>
16032     *
16033     * @param l Left position, relative to parent
16034     * @param t Top position, relative to parent
16035     * @param r Right position, relative to parent
16036     * @param b Bottom position, relative to parent
16037     */
16038    @SuppressWarnings({"unchecked"})
16039    public void layout(int l, int t, int r, int b) {
16040        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
16041            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
16042            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16043        }
16044
16045        int oldL = mLeft;
16046        int oldT = mTop;
16047        int oldB = mBottom;
16048        int oldR = mRight;
16049
16050        boolean changed = isLayoutModeOptical(mParent) ?
16051                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
16052
16053        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
16054            onLayout(changed, l, t, r, b);
16055            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
16056
16057            ListenerInfo li = mListenerInfo;
16058            if (li != null && li.mOnLayoutChangeListeners != null) {
16059                ArrayList<OnLayoutChangeListener> listenersCopy =
16060                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
16061                int numListeners = listenersCopy.size();
16062                for (int i = 0; i < numListeners; ++i) {
16063                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
16064                }
16065            }
16066        }
16067
16068        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
16069        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
16070    }
16071
16072    /**
16073     * Called from layout when this view should
16074     * assign a size and position to each of its children.
16075     *
16076     * Derived classes with children should override
16077     * this method and call layout on each of
16078     * their children.
16079     * @param changed This is a new size or position for this view
16080     * @param left Left position, relative to parent
16081     * @param top Top position, relative to parent
16082     * @param right Right position, relative to parent
16083     * @param bottom Bottom position, relative to parent
16084     */
16085    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
16086    }
16087
16088    /**
16089     * Assign a size and position to this view.
16090     *
16091     * This is called from layout.
16092     *
16093     * @param left Left position, relative to parent
16094     * @param top Top position, relative to parent
16095     * @param right Right position, relative to parent
16096     * @param bottom Bottom position, relative to parent
16097     * @return true if the new size and position are different than the
16098     *         previous ones
16099     * {@hide}
16100     */
16101    protected boolean setFrame(int left, int top, int right, int bottom) {
16102        boolean changed = false;
16103
16104        if (DBG) {
16105            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
16106                    + right + "," + bottom + ")");
16107        }
16108
16109        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
16110            changed = true;
16111
16112            // Remember our drawn bit
16113            int drawn = mPrivateFlags & PFLAG_DRAWN;
16114
16115            int oldWidth = mRight - mLeft;
16116            int oldHeight = mBottom - mTop;
16117            int newWidth = right - left;
16118            int newHeight = bottom - top;
16119            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
16120
16121            // Invalidate our old position
16122            invalidate(sizeChanged);
16123
16124            mLeft = left;
16125            mTop = top;
16126            mRight = right;
16127            mBottom = bottom;
16128            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
16129
16130            mPrivateFlags |= PFLAG_HAS_BOUNDS;
16131
16132
16133            if (sizeChanged) {
16134                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
16135            }
16136
16137            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
16138                // If we are visible, force the DRAWN bit to on so that
16139                // this invalidate will go through (at least to our parent).
16140                // This is because someone may have invalidated this view
16141                // before this call to setFrame came in, thereby clearing
16142                // the DRAWN bit.
16143                mPrivateFlags |= PFLAG_DRAWN;
16144                invalidate(sizeChanged);
16145                // parent display list may need to be recreated based on a change in the bounds
16146                // of any child
16147                invalidateParentCaches();
16148            }
16149
16150            // Reset drawn bit to original value (invalidate turns it off)
16151            mPrivateFlags |= drawn;
16152
16153            mBackgroundSizeChanged = true;
16154            if (mForegroundInfo != null) {
16155                mForegroundInfo.mBoundsChanged = true;
16156            }
16157
16158            notifySubtreeAccessibilityStateChangedIfNeeded();
16159        }
16160        return changed;
16161    }
16162
16163    /**
16164     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
16165     * @hide
16166     */
16167    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
16168        setFrame(left, top, right, bottom);
16169    }
16170
16171    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
16172        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
16173        if (mOverlay != null) {
16174            mOverlay.getOverlayView().setRight(newWidth);
16175            mOverlay.getOverlayView().setBottom(newHeight);
16176        }
16177        rebuildOutline();
16178    }
16179
16180    /**
16181     * Finalize inflating a view from XML.  This is called as the last phase
16182     * of inflation, after all child views have been added.
16183     *
16184     * <p>Even if the subclass overrides onFinishInflate, they should always be
16185     * sure to call the super method, so that we get called.
16186     */
16187    @CallSuper
16188    protected void onFinishInflate() {
16189    }
16190
16191    /**
16192     * Returns the resources associated with this view.
16193     *
16194     * @return Resources object.
16195     */
16196    public Resources getResources() {
16197        return mResources;
16198    }
16199
16200    /**
16201     * Invalidates the specified Drawable.
16202     *
16203     * @param drawable the drawable to invalidate
16204     */
16205    @Override
16206    public void invalidateDrawable(@NonNull Drawable drawable) {
16207        if (verifyDrawable(drawable)) {
16208            final Rect dirty = drawable.getDirtyBounds();
16209            final int scrollX = mScrollX;
16210            final int scrollY = mScrollY;
16211
16212            invalidate(dirty.left + scrollX, dirty.top + scrollY,
16213                    dirty.right + scrollX, dirty.bottom + scrollY);
16214            rebuildOutline();
16215        }
16216    }
16217
16218    /**
16219     * Schedules an action on a drawable to occur at a specified time.
16220     *
16221     * @param who the recipient of the action
16222     * @param what the action to run on the drawable
16223     * @param when the time at which the action must occur. Uses the
16224     *        {@link SystemClock#uptimeMillis} timebase.
16225     */
16226    @Override
16227    public void scheduleDrawable(Drawable who, Runnable what, long when) {
16228        if (verifyDrawable(who) && what != null) {
16229            final long delay = when - SystemClock.uptimeMillis();
16230            if (mAttachInfo != null) {
16231                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
16232                        Choreographer.CALLBACK_ANIMATION, what, who,
16233                        Choreographer.subtractFrameDelay(delay));
16234            } else {
16235                ViewRootImpl.getRunQueue().postDelayed(what, delay);
16236            }
16237        }
16238    }
16239
16240    /**
16241     * Cancels a scheduled action on a drawable.
16242     *
16243     * @param who the recipient of the action
16244     * @param what the action to cancel
16245     */
16246    @Override
16247    public void unscheduleDrawable(Drawable who, Runnable what) {
16248        if (verifyDrawable(who) && what != null) {
16249            if (mAttachInfo != null) {
16250                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16251                        Choreographer.CALLBACK_ANIMATION, what, who);
16252            }
16253            ViewRootImpl.getRunQueue().removeCallbacks(what);
16254        }
16255    }
16256
16257    /**
16258     * Unschedule any events associated with the given Drawable.  This can be
16259     * used when selecting a new Drawable into a view, so that the previous
16260     * one is completely unscheduled.
16261     *
16262     * @param who The Drawable to unschedule.
16263     *
16264     * @see #drawableStateChanged
16265     */
16266    public void unscheduleDrawable(Drawable who) {
16267        if (mAttachInfo != null && who != null) {
16268            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16269                    Choreographer.CALLBACK_ANIMATION, null, who);
16270        }
16271    }
16272
16273    /**
16274     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
16275     * that the View directionality can and will be resolved before its Drawables.
16276     *
16277     * Will call {@link View#onResolveDrawables} when resolution is done.
16278     *
16279     * @hide
16280     */
16281    protected void resolveDrawables() {
16282        // Drawables resolution may need to happen before resolving the layout direction (which is
16283        // done only during the measure() call).
16284        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
16285        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
16286        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
16287        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
16288        // direction to be resolved as its resolved value will be the same as its raw value.
16289        if (!isLayoutDirectionResolved() &&
16290                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
16291            return;
16292        }
16293
16294        final int layoutDirection = isLayoutDirectionResolved() ?
16295                getLayoutDirection() : getRawLayoutDirection();
16296
16297        if (mBackground != null) {
16298            mBackground.setLayoutDirection(layoutDirection);
16299        }
16300        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16301            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
16302        }
16303        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
16304        onResolveDrawables(layoutDirection);
16305    }
16306
16307    boolean areDrawablesResolved() {
16308        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
16309    }
16310
16311    /**
16312     * Called when layout direction has been resolved.
16313     *
16314     * The default implementation does nothing.
16315     *
16316     * @param layoutDirection The resolved layout direction.
16317     *
16318     * @see #LAYOUT_DIRECTION_LTR
16319     * @see #LAYOUT_DIRECTION_RTL
16320     *
16321     * @hide
16322     */
16323    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
16324    }
16325
16326    /**
16327     * @hide
16328     */
16329    protected void resetResolvedDrawables() {
16330        resetResolvedDrawablesInternal();
16331    }
16332
16333    void resetResolvedDrawablesInternal() {
16334        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
16335    }
16336
16337    /**
16338     * If your view subclass is displaying its own Drawable objects, it should
16339     * override this function and return true for any Drawable it is
16340     * displaying.  This allows animations for those drawables to be
16341     * scheduled.
16342     *
16343     * <p>Be sure to call through to the super class when overriding this
16344     * function.
16345     *
16346     * @param who The Drawable to verify.  Return true if it is one you are
16347     *            displaying, else return the result of calling through to the
16348     *            super class.
16349     *
16350     * @return boolean If true than the Drawable is being displayed in the
16351     *         view; else false and it is not allowed to animate.
16352     *
16353     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
16354     * @see #drawableStateChanged()
16355     */
16356    @CallSuper
16357    protected boolean verifyDrawable(Drawable who) {
16358        return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who)
16359                || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
16360    }
16361
16362    /**
16363     * This function is called whenever the state of the view changes in such
16364     * a way that it impacts the state of drawables being shown.
16365     * <p>
16366     * If the View has a StateListAnimator, it will also be called to run necessary state
16367     * change animations.
16368     * <p>
16369     * Be sure to call through to the superclass when overriding this function.
16370     *
16371     * @see Drawable#setState(int[])
16372     */
16373    @CallSuper
16374    protected void drawableStateChanged() {
16375        final int[] state = getDrawableState();
16376
16377        final Drawable bg = mBackground;
16378        if (bg != null && bg.isStateful()) {
16379            bg.setState(state);
16380        }
16381
16382        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
16383        if (fg != null && fg.isStateful()) {
16384            fg.setState(state);
16385        }
16386
16387        if (mScrollCache != null) {
16388            final Drawable scrollBar = mScrollCache.scrollBar;
16389            if (scrollBar != null && scrollBar.isStateful()) {
16390                scrollBar.setState(state);
16391            }
16392        }
16393
16394        if (mStateListAnimator != null) {
16395            mStateListAnimator.setState(state);
16396        }
16397    }
16398
16399    /**
16400     * This function is called whenever the view hotspot changes and needs to
16401     * be propagated to drawables or child views managed by the view.
16402     * <p>
16403     * Dispatching to child views is handled by
16404     * {@link #dispatchDrawableHotspotChanged(float, float)}.
16405     * <p>
16406     * Be sure to call through to the superclass when overriding this function.
16407     *
16408     * @param x hotspot x coordinate
16409     * @param y hotspot y coordinate
16410     */
16411    @CallSuper
16412    public void drawableHotspotChanged(float x, float y) {
16413        if (mBackground != null) {
16414            mBackground.setHotspot(x, y);
16415        }
16416        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16417            mForegroundInfo.mDrawable.setHotspot(x, y);
16418        }
16419
16420        dispatchDrawableHotspotChanged(x, y);
16421    }
16422
16423    /**
16424     * Dispatches drawableHotspotChanged to all of this View's children.
16425     *
16426     * @param x hotspot x coordinate
16427     * @param y hotspot y coordinate
16428     * @see #drawableHotspotChanged(float, float)
16429     */
16430    public void dispatchDrawableHotspotChanged(float x, float y) {
16431    }
16432
16433    /**
16434     * Call this to force a view to update its drawable state. This will cause
16435     * drawableStateChanged to be called on this view. Views that are interested
16436     * in the new state should call getDrawableState.
16437     *
16438     * @see #drawableStateChanged
16439     * @see #getDrawableState
16440     */
16441    public void refreshDrawableState() {
16442        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16443        drawableStateChanged();
16444
16445        ViewParent parent = mParent;
16446        if (parent != null) {
16447            parent.childDrawableStateChanged(this);
16448        }
16449    }
16450
16451    /**
16452     * Return an array of resource IDs of the drawable states representing the
16453     * current state of the view.
16454     *
16455     * @return The current drawable state
16456     *
16457     * @see Drawable#setState(int[])
16458     * @see #drawableStateChanged()
16459     * @see #onCreateDrawableState(int)
16460     */
16461    public final int[] getDrawableState() {
16462        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
16463            return mDrawableState;
16464        } else {
16465            mDrawableState = onCreateDrawableState(0);
16466            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
16467            return mDrawableState;
16468        }
16469    }
16470
16471    /**
16472     * Generate the new {@link android.graphics.drawable.Drawable} state for
16473     * this view. This is called by the view
16474     * system when the cached Drawable state is determined to be invalid.  To
16475     * retrieve the current state, you should use {@link #getDrawableState}.
16476     *
16477     * @param extraSpace if non-zero, this is the number of extra entries you
16478     * would like in the returned array in which you can place your own
16479     * states.
16480     *
16481     * @return Returns an array holding the current {@link Drawable} state of
16482     * the view.
16483     *
16484     * @see #mergeDrawableStates(int[], int[])
16485     */
16486    protected int[] onCreateDrawableState(int extraSpace) {
16487        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
16488                mParent instanceof View) {
16489            return ((View) mParent).onCreateDrawableState(extraSpace);
16490        }
16491
16492        int[] drawableState;
16493
16494        int privateFlags = mPrivateFlags;
16495
16496        int viewStateIndex = 0;
16497        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
16498        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
16499        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
16500        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
16501        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
16502        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
16503        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
16504                HardwareRenderer.isAvailable()) {
16505            // This is set if HW acceleration is requested, even if the current
16506            // process doesn't allow it.  This is just to allow app preview
16507            // windows to better match their app.
16508            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
16509        }
16510        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
16511
16512        final int privateFlags2 = mPrivateFlags2;
16513        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
16514            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
16515        }
16516        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
16517            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
16518        }
16519
16520        drawableState = StateSet.get(viewStateIndex);
16521
16522        //noinspection ConstantIfStatement
16523        if (false) {
16524            Log.i("View", "drawableStateIndex=" + viewStateIndex);
16525            Log.i("View", toString()
16526                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
16527                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
16528                    + " fo=" + hasFocus()
16529                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
16530                    + " wf=" + hasWindowFocus()
16531                    + ": " + Arrays.toString(drawableState));
16532        }
16533
16534        if (extraSpace == 0) {
16535            return drawableState;
16536        }
16537
16538        final int[] fullState;
16539        if (drawableState != null) {
16540            fullState = new int[drawableState.length + extraSpace];
16541            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
16542        } else {
16543            fullState = new int[extraSpace];
16544        }
16545
16546        return fullState;
16547    }
16548
16549    /**
16550     * Merge your own state values in <var>additionalState</var> into the base
16551     * state values <var>baseState</var> that were returned by
16552     * {@link #onCreateDrawableState(int)}.
16553     *
16554     * @param baseState The base state values returned by
16555     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
16556     * own additional state values.
16557     *
16558     * @param additionalState The additional state values you would like
16559     * added to <var>baseState</var>; this array is not modified.
16560     *
16561     * @return As a convenience, the <var>baseState</var> array you originally
16562     * passed into the function is returned.
16563     *
16564     * @see #onCreateDrawableState(int)
16565     */
16566    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
16567        final int N = baseState.length;
16568        int i = N - 1;
16569        while (i >= 0 && baseState[i] == 0) {
16570            i--;
16571        }
16572        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
16573        return baseState;
16574    }
16575
16576    /**
16577     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
16578     * on all Drawable objects associated with this view.
16579     * <p>
16580     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
16581     * attached to this view.
16582     */
16583    public void jumpDrawablesToCurrentState() {
16584        if (mBackground != null) {
16585            mBackground.jumpToCurrentState();
16586        }
16587        if (mStateListAnimator != null) {
16588            mStateListAnimator.jumpToCurrentState();
16589        }
16590        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16591            mForegroundInfo.mDrawable.jumpToCurrentState();
16592        }
16593    }
16594
16595    /**
16596     * Sets the background color for this view.
16597     * @param color the color of the background
16598     */
16599    @RemotableViewMethod
16600    public void setBackgroundColor(@ColorInt int color) {
16601        if (mBackground instanceof ColorDrawable) {
16602            ((ColorDrawable) mBackground.mutate()).setColor(color);
16603            computeOpaqueFlags();
16604            mBackgroundResource = 0;
16605        } else {
16606            setBackground(new ColorDrawable(color));
16607        }
16608    }
16609
16610    /**
16611     * If the view has a ColorDrawable background, returns the color of that
16612     * drawable.
16613     *
16614     * @return The color of the ColorDrawable background, if set, otherwise 0.
16615     */
16616    @ColorInt
16617    public int getBackgroundColor() {
16618        if (mBackground instanceof ColorDrawable) {
16619            return ((ColorDrawable) mBackground).getColor();
16620        }
16621        return 0;
16622    }
16623
16624    /**
16625     * Set the background to a given resource. The resource should refer to
16626     * a Drawable object or 0 to remove the background.
16627     * @param resid The identifier of the resource.
16628     *
16629     * @attr ref android.R.styleable#View_background
16630     */
16631    @RemotableViewMethod
16632    public void setBackgroundResource(@DrawableRes int resid) {
16633        if (resid != 0 && resid == mBackgroundResource) {
16634            return;
16635        }
16636
16637        Drawable d = null;
16638        if (resid != 0) {
16639            d = mContext.getDrawable(resid);
16640        }
16641        setBackground(d);
16642
16643        mBackgroundResource = resid;
16644    }
16645
16646    /**
16647     * Set the background to a given Drawable, or remove the background. If the
16648     * background has padding, this View's padding is set to the background's
16649     * padding. However, when a background is removed, this View's padding isn't
16650     * touched. If setting the padding is desired, please use
16651     * {@link #setPadding(int, int, int, int)}.
16652     *
16653     * @param background The Drawable to use as the background, or null to remove the
16654     *        background
16655     */
16656    public void setBackground(Drawable background) {
16657        //noinspection deprecation
16658        setBackgroundDrawable(background);
16659    }
16660
16661    /**
16662     * @deprecated use {@link #setBackground(Drawable)} instead
16663     */
16664    @Deprecated
16665    public void setBackgroundDrawable(Drawable background) {
16666        computeOpaqueFlags();
16667
16668        if (background == mBackground) {
16669            return;
16670        }
16671
16672        boolean requestLayout = false;
16673
16674        mBackgroundResource = 0;
16675
16676        /*
16677         * Regardless of whether we're setting a new background or not, we want
16678         * to clear the previous drawable.
16679         */
16680        if (mBackground != null) {
16681            mBackground.setCallback(null);
16682            unscheduleDrawable(mBackground);
16683        }
16684
16685        if (background != null) {
16686            Rect padding = sThreadLocal.get();
16687            if (padding == null) {
16688                padding = new Rect();
16689                sThreadLocal.set(padding);
16690            }
16691            resetResolvedDrawablesInternal();
16692            background.setLayoutDirection(getLayoutDirection());
16693            if (background.getPadding(padding)) {
16694                resetResolvedPaddingInternal();
16695                switch (background.getLayoutDirection()) {
16696                    case LAYOUT_DIRECTION_RTL:
16697                        mUserPaddingLeftInitial = padding.right;
16698                        mUserPaddingRightInitial = padding.left;
16699                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16700                        break;
16701                    case LAYOUT_DIRECTION_LTR:
16702                    default:
16703                        mUserPaddingLeftInitial = padding.left;
16704                        mUserPaddingRightInitial = padding.right;
16705                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16706                }
16707                mLeftPaddingDefined = false;
16708                mRightPaddingDefined = false;
16709            }
16710
16711            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16712            // if it has a different minimum size, we should layout again
16713            if (mBackground == null
16714                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
16715                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16716                requestLayout = true;
16717            }
16718
16719            background.setCallback(this);
16720            if (background.isStateful()) {
16721                background.setState(getDrawableState());
16722            }
16723            background.setVisible(getVisibility() == VISIBLE, false);
16724            mBackground = background;
16725
16726            applyBackgroundTint();
16727
16728            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16729                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16730                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16731                requestLayout = true;
16732            }
16733        } else {
16734            /* Remove the background */
16735            mBackground = null;
16736
16737            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16738                /*
16739                 * This view ONLY drew the background before and we're removing
16740                 * the background, so now it won't draw anything
16741                 * (hence we SKIP_DRAW)
16742                 */
16743                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16744                mPrivateFlags |= PFLAG_SKIP_DRAW;
16745            }
16746
16747            /*
16748             * When the background is set, we try to apply its padding to this
16749             * View. When the background is removed, we don't touch this View's
16750             * padding. This is noted in the Javadocs. Hence, we don't need to
16751             * requestLayout(), the invalidate() below is sufficient.
16752             */
16753
16754            // The old background's minimum size could have affected this
16755            // View's layout, so let's requestLayout
16756            requestLayout = true;
16757        }
16758
16759        computeOpaqueFlags();
16760
16761        if (requestLayout) {
16762            requestLayout();
16763        }
16764
16765        mBackgroundSizeChanged = true;
16766        invalidate(true);
16767    }
16768
16769    /**
16770     * Gets the background drawable
16771     *
16772     * @return The drawable used as the background for this view, if any.
16773     *
16774     * @see #setBackground(Drawable)
16775     *
16776     * @attr ref android.R.styleable#View_background
16777     */
16778    public Drawable getBackground() {
16779        return mBackground;
16780    }
16781
16782    /**
16783     * Applies a tint to the background drawable. Does not modify the current tint
16784     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16785     * <p>
16786     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16787     * mutate the drawable and apply the specified tint and tint mode using
16788     * {@link Drawable#setTintList(ColorStateList)}.
16789     *
16790     * @param tint the tint to apply, may be {@code null} to clear tint
16791     *
16792     * @attr ref android.R.styleable#View_backgroundTint
16793     * @see #getBackgroundTintList()
16794     * @see Drawable#setTintList(ColorStateList)
16795     */
16796    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16797        if (mBackgroundTint == null) {
16798            mBackgroundTint = new TintInfo();
16799        }
16800        mBackgroundTint.mTintList = tint;
16801        mBackgroundTint.mHasTintList = true;
16802
16803        applyBackgroundTint();
16804    }
16805
16806    /**
16807     * Return the tint applied to the background drawable, if specified.
16808     *
16809     * @return the tint applied to the background drawable
16810     * @attr ref android.R.styleable#View_backgroundTint
16811     * @see #setBackgroundTintList(ColorStateList)
16812     */
16813    @Nullable
16814    public ColorStateList getBackgroundTintList() {
16815        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
16816    }
16817
16818    /**
16819     * Specifies the blending mode used to apply the tint specified by
16820     * {@link #setBackgroundTintList(ColorStateList)}} to the background
16821     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
16822     *
16823     * @param tintMode the blending mode used to apply the tint, may be
16824     *                 {@code null} to clear tint
16825     * @attr ref android.R.styleable#View_backgroundTintMode
16826     * @see #getBackgroundTintMode()
16827     * @see Drawable#setTintMode(PorterDuff.Mode)
16828     */
16829    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16830        if (mBackgroundTint == null) {
16831            mBackgroundTint = new TintInfo();
16832        }
16833        mBackgroundTint.mTintMode = tintMode;
16834        mBackgroundTint.mHasTintMode = true;
16835
16836        applyBackgroundTint();
16837    }
16838
16839    /**
16840     * Return the blending mode used to apply the tint to the background
16841     * drawable, if specified.
16842     *
16843     * @return the blending mode used to apply the tint to the background
16844     *         drawable
16845     * @attr ref android.R.styleable#View_backgroundTintMode
16846     * @see #setBackgroundTintMode(PorterDuff.Mode)
16847     */
16848    @Nullable
16849    public PorterDuff.Mode getBackgroundTintMode() {
16850        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
16851    }
16852
16853    private void applyBackgroundTint() {
16854        if (mBackground != null && mBackgroundTint != null) {
16855            final TintInfo tintInfo = mBackgroundTint;
16856            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
16857                mBackground = mBackground.mutate();
16858
16859                if (tintInfo.mHasTintList) {
16860                    mBackground.setTintList(tintInfo.mTintList);
16861                }
16862
16863                if (tintInfo.mHasTintMode) {
16864                    mBackground.setTintMode(tintInfo.mTintMode);
16865                }
16866
16867                // The drawable (or one of its children) may not have been
16868                // stateful before applying the tint, so let's try again.
16869                if (mBackground.isStateful()) {
16870                    mBackground.setState(getDrawableState());
16871                }
16872            }
16873        }
16874    }
16875
16876    /**
16877     * Returns the drawable used as the foreground of this View. The
16878     * foreground drawable, if non-null, is always drawn on top of the view's content.
16879     *
16880     * @return a Drawable or null if no foreground was set
16881     *
16882     * @see #onDrawForeground(Canvas)
16883     */
16884    public Drawable getForeground() {
16885        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
16886    }
16887
16888    /**
16889     * Supply a Drawable that is to be rendered on top of all of the content in the view.
16890     *
16891     * @param foreground the Drawable to be drawn on top of the children
16892     *
16893     * @attr ref android.R.styleable#View_foreground
16894     */
16895    public void setForeground(Drawable foreground) {
16896        if (mForegroundInfo == null) {
16897            if (foreground == null) {
16898                // Nothing to do.
16899                return;
16900            }
16901            mForegroundInfo = new ForegroundInfo();
16902        }
16903
16904        if (foreground == mForegroundInfo.mDrawable) {
16905            // Nothing to do
16906            return;
16907        }
16908
16909        if (mForegroundInfo.mDrawable != null) {
16910            mForegroundInfo.mDrawable.setCallback(null);
16911            unscheduleDrawable(mForegroundInfo.mDrawable);
16912        }
16913
16914        mForegroundInfo.mDrawable = foreground;
16915        mForegroundInfo.mBoundsChanged = true;
16916        if (foreground != null) {
16917            setWillNotDraw(false);
16918            foreground.setCallback(this);
16919            foreground.setLayoutDirection(getLayoutDirection());
16920            if (foreground.isStateful()) {
16921                foreground.setState(getDrawableState());
16922            }
16923            applyForegroundTint();
16924        }
16925        requestLayout();
16926        invalidate();
16927    }
16928
16929    /**
16930     * Magic bit used to support features of framework-internal window decor implementation details.
16931     * This used to live exclusively in FrameLayout.
16932     *
16933     * @return true if the foreground should draw inside the padding region or false
16934     *         if it should draw inset by the view's padding
16935     * @hide internal use only; only used by FrameLayout and internal screen layouts.
16936     */
16937    public boolean isForegroundInsidePadding() {
16938        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
16939    }
16940
16941    /**
16942     * Describes how the foreground is positioned.
16943     *
16944     * @return foreground gravity.
16945     *
16946     * @see #setForegroundGravity(int)
16947     *
16948     * @attr ref android.R.styleable#View_foregroundGravity
16949     */
16950    public int getForegroundGravity() {
16951        return mForegroundInfo != null ? mForegroundInfo.mGravity
16952                : Gravity.START | Gravity.TOP;
16953    }
16954
16955    /**
16956     * Describes how the foreground is positioned. Defaults to START and TOP.
16957     *
16958     * @param gravity see {@link android.view.Gravity}
16959     *
16960     * @see #getForegroundGravity()
16961     *
16962     * @attr ref android.R.styleable#View_foregroundGravity
16963     */
16964    public void setForegroundGravity(int gravity) {
16965        if (mForegroundInfo == null) {
16966            mForegroundInfo = new ForegroundInfo();
16967        }
16968
16969        if (mForegroundInfo.mGravity != gravity) {
16970            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
16971                gravity |= Gravity.START;
16972            }
16973
16974            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
16975                gravity |= Gravity.TOP;
16976            }
16977
16978            mForegroundInfo.mGravity = gravity;
16979            requestLayout();
16980        }
16981    }
16982
16983    /**
16984     * Applies a tint to the foreground drawable. Does not modify the current tint
16985     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16986     * <p>
16987     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
16988     * mutate the drawable and apply the specified tint and tint mode using
16989     * {@link Drawable#setTintList(ColorStateList)}.
16990     *
16991     * @param tint the tint to apply, may be {@code null} to clear tint
16992     *
16993     * @attr ref android.R.styleable#View_foregroundTint
16994     * @see #getForegroundTintList()
16995     * @see Drawable#setTintList(ColorStateList)
16996     */
16997    public void setForegroundTintList(@Nullable ColorStateList tint) {
16998        if (mForegroundInfo == null) {
16999            mForegroundInfo = new ForegroundInfo();
17000        }
17001        if (mForegroundInfo.mTintInfo == null) {
17002            mForegroundInfo.mTintInfo = new TintInfo();
17003        }
17004        mForegroundInfo.mTintInfo.mTintList = tint;
17005        mForegroundInfo.mTintInfo.mHasTintList = true;
17006
17007        applyForegroundTint();
17008    }
17009
17010    /**
17011     * Return the tint applied to the foreground drawable, if specified.
17012     *
17013     * @return the tint applied to the foreground drawable
17014     * @attr ref android.R.styleable#View_foregroundTint
17015     * @see #setForegroundTintList(ColorStateList)
17016     */
17017    @Nullable
17018    public ColorStateList getForegroundTintList() {
17019        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17020                ? mForegroundInfo.mTintInfo.mTintList : null;
17021    }
17022
17023    /**
17024     * Specifies the blending mode used to apply the tint specified by
17025     * {@link #setForegroundTintList(ColorStateList)}} to the background
17026     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
17027     *
17028     * @param tintMode the blending mode used to apply the tint, may be
17029     *                 {@code null} to clear tint
17030     * @attr ref android.R.styleable#View_foregroundTintMode
17031     * @see #getForegroundTintMode()
17032     * @see Drawable#setTintMode(PorterDuff.Mode)
17033     */
17034    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
17035        if (mBackgroundTint == null) {
17036            mBackgroundTint = new TintInfo();
17037        }
17038        mBackgroundTint.mTintMode = tintMode;
17039        mBackgroundTint.mHasTintMode = true;
17040
17041        applyBackgroundTint();
17042    }
17043
17044    /**
17045     * Return the blending mode used to apply the tint to the foreground
17046     * drawable, if specified.
17047     *
17048     * @return the blending mode used to apply the tint to the foreground
17049     *         drawable
17050     * @attr ref android.R.styleable#View_foregroundTintMode
17051     * @see #setBackgroundTintMode(PorterDuff.Mode)
17052     */
17053    @Nullable
17054    public PorterDuff.Mode getForegroundTintMode() {
17055        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17056                ? mForegroundInfo.mTintInfo.mTintMode : null;
17057    }
17058
17059    private void applyForegroundTint() {
17060        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
17061                && mForegroundInfo.mTintInfo != null) {
17062            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
17063            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17064                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
17065
17066                if (tintInfo.mHasTintList) {
17067                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
17068                }
17069
17070                if (tintInfo.mHasTintMode) {
17071                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
17072                }
17073
17074                // The drawable (or one of its children) may not have been
17075                // stateful before applying the tint, so let's try again.
17076                if (mForegroundInfo.mDrawable.isStateful()) {
17077                    mForegroundInfo.mDrawable.setState(getDrawableState());
17078                }
17079            }
17080        }
17081    }
17082
17083    /**
17084     * Draw any foreground content for this view.
17085     *
17086     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
17087     * drawable or other view-specific decorations. The foreground is drawn on top of the
17088     * primary view content.</p>
17089     *
17090     * @param canvas canvas to draw into
17091     */
17092    public void onDrawForeground(Canvas canvas) {
17093        onDrawScrollBars(canvas);
17094
17095        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17096        if (foreground != null) {
17097            if (mForegroundInfo.mBoundsChanged) {
17098                mForegroundInfo.mBoundsChanged = false;
17099                final Rect selfBounds = mForegroundInfo.mSelfBounds;
17100                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
17101
17102                if (mForegroundInfo.mInsidePadding) {
17103                    selfBounds.set(0, 0, getWidth(), getHeight());
17104                } else {
17105                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
17106                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
17107                }
17108
17109                final int ld = getLayoutDirection();
17110                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
17111                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
17112                foreground.setBounds(overlayBounds);
17113            }
17114
17115            foreground.draw(canvas);
17116        }
17117    }
17118
17119    /**
17120     * Sets the padding. The view may add on the space required to display
17121     * the scrollbars, depending on the style and visibility of the scrollbars.
17122     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
17123     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
17124     * from the values set in this call.
17125     *
17126     * @attr ref android.R.styleable#View_padding
17127     * @attr ref android.R.styleable#View_paddingBottom
17128     * @attr ref android.R.styleable#View_paddingLeft
17129     * @attr ref android.R.styleable#View_paddingRight
17130     * @attr ref android.R.styleable#View_paddingTop
17131     * @param left the left padding in pixels
17132     * @param top the top padding in pixels
17133     * @param right the right padding in pixels
17134     * @param bottom the bottom padding in pixels
17135     */
17136    public void setPadding(int left, int top, int right, int bottom) {
17137        resetResolvedPaddingInternal();
17138
17139        mUserPaddingStart = UNDEFINED_PADDING;
17140        mUserPaddingEnd = UNDEFINED_PADDING;
17141
17142        mUserPaddingLeftInitial = left;
17143        mUserPaddingRightInitial = right;
17144
17145        mLeftPaddingDefined = true;
17146        mRightPaddingDefined = true;
17147
17148        internalSetPadding(left, top, right, bottom);
17149    }
17150
17151    /**
17152     * @hide
17153     */
17154    protected void internalSetPadding(int left, int top, int right, int bottom) {
17155        mUserPaddingLeft = left;
17156        mUserPaddingRight = right;
17157        mUserPaddingBottom = bottom;
17158
17159        final int viewFlags = mViewFlags;
17160        boolean changed = false;
17161
17162        // Common case is there are no scroll bars.
17163        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
17164            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
17165                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
17166                        ? 0 : getVerticalScrollbarWidth();
17167                switch (mVerticalScrollbarPosition) {
17168                    case SCROLLBAR_POSITION_DEFAULT:
17169                        if (isLayoutRtl()) {
17170                            left += offset;
17171                        } else {
17172                            right += offset;
17173                        }
17174                        break;
17175                    case SCROLLBAR_POSITION_RIGHT:
17176                        right += offset;
17177                        break;
17178                    case SCROLLBAR_POSITION_LEFT:
17179                        left += offset;
17180                        break;
17181                }
17182            }
17183            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
17184                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
17185                        ? 0 : getHorizontalScrollbarHeight();
17186            }
17187        }
17188
17189        if (mPaddingLeft != left) {
17190            changed = true;
17191            mPaddingLeft = left;
17192        }
17193        if (mPaddingTop != top) {
17194            changed = true;
17195            mPaddingTop = top;
17196        }
17197        if (mPaddingRight != right) {
17198            changed = true;
17199            mPaddingRight = right;
17200        }
17201        if (mPaddingBottom != bottom) {
17202            changed = true;
17203            mPaddingBottom = bottom;
17204        }
17205
17206        if (changed) {
17207            requestLayout();
17208            invalidateOutline();
17209        }
17210    }
17211
17212    /**
17213     * Sets the relative padding. The view may add on the space required to display
17214     * the scrollbars, depending on the style and visibility of the scrollbars.
17215     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
17216     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
17217     * from the values set in this call.
17218     *
17219     * @attr ref android.R.styleable#View_padding
17220     * @attr ref android.R.styleable#View_paddingBottom
17221     * @attr ref android.R.styleable#View_paddingStart
17222     * @attr ref android.R.styleable#View_paddingEnd
17223     * @attr ref android.R.styleable#View_paddingTop
17224     * @param start the start padding in pixels
17225     * @param top the top padding in pixels
17226     * @param end the end padding in pixels
17227     * @param bottom the bottom padding in pixels
17228     */
17229    public void setPaddingRelative(int start, int top, int end, int bottom) {
17230        resetResolvedPaddingInternal();
17231
17232        mUserPaddingStart = start;
17233        mUserPaddingEnd = end;
17234        mLeftPaddingDefined = true;
17235        mRightPaddingDefined = true;
17236
17237        switch(getLayoutDirection()) {
17238            case LAYOUT_DIRECTION_RTL:
17239                mUserPaddingLeftInitial = end;
17240                mUserPaddingRightInitial = start;
17241                internalSetPadding(end, top, start, bottom);
17242                break;
17243            case LAYOUT_DIRECTION_LTR:
17244            default:
17245                mUserPaddingLeftInitial = start;
17246                mUserPaddingRightInitial = end;
17247                internalSetPadding(start, top, end, bottom);
17248        }
17249    }
17250
17251    /**
17252     * Returns the top padding of this view.
17253     *
17254     * @return the top padding in pixels
17255     */
17256    public int getPaddingTop() {
17257        return mPaddingTop;
17258    }
17259
17260    /**
17261     * Returns the bottom padding of this view. If there are inset and enabled
17262     * scrollbars, this value may include the space required to display the
17263     * scrollbars as well.
17264     *
17265     * @return the bottom padding in pixels
17266     */
17267    public int getPaddingBottom() {
17268        return mPaddingBottom;
17269    }
17270
17271    /**
17272     * Returns the left padding of this view. If there are inset and enabled
17273     * scrollbars, this value may include the space required to display the
17274     * scrollbars as well.
17275     *
17276     * @return the left padding in pixels
17277     */
17278    public int getPaddingLeft() {
17279        if (!isPaddingResolved()) {
17280            resolvePadding();
17281        }
17282        return mPaddingLeft;
17283    }
17284
17285    /**
17286     * Returns the start padding of this view depending on its resolved layout direction.
17287     * If there are inset and enabled scrollbars, this value may include the space
17288     * required to display the scrollbars as well.
17289     *
17290     * @return the start padding in pixels
17291     */
17292    public int getPaddingStart() {
17293        if (!isPaddingResolved()) {
17294            resolvePadding();
17295        }
17296        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17297                mPaddingRight : mPaddingLeft;
17298    }
17299
17300    /**
17301     * Returns the right padding of this view. If there are inset and enabled
17302     * scrollbars, this value may include the space required to display the
17303     * scrollbars as well.
17304     *
17305     * @return the right padding in pixels
17306     */
17307    public int getPaddingRight() {
17308        if (!isPaddingResolved()) {
17309            resolvePadding();
17310        }
17311        return mPaddingRight;
17312    }
17313
17314    /**
17315     * Returns the end padding of this view depending on its resolved layout direction.
17316     * If there are inset and enabled scrollbars, this value may include the space
17317     * required to display the scrollbars as well.
17318     *
17319     * @return the end padding in pixels
17320     */
17321    public int getPaddingEnd() {
17322        if (!isPaddingResolved()) {
17323            resolvePadding();
17324        }
17325        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17326                mPaddingLeft : mPaddingRight;
17327    }
17328
17329    /**
17330     * Return if the padding has been set through relative values
17331     * {@link #setPaddingRelative(int, int, int, int)} or through
17332     * @attr ref android.R.styleable#View_paddingStart or
17333     * @attr ref android.R.styleable#View_paddingEnd
17334     *
17335     * @return true if the padding is relative or false if it is not.
17336     */
17337    public boolean isPaddingRelative() {
17338        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
17339    }
17340
17341    Insets computeOpticalInsets() {
17342        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
17343    }
17344
17345    /**
17346     * @hide
17347     */
17348    public void resetPaddingToInitialValues() {
17349        if (isRtlCompatibilityMode()) {
17350            mPaddingLeft = mUserPaddingLeftInitial;
17351            mPaddingRight = mUserPaddingRightInitial;
17352            return;
17353        }
17354        if (isLayoutRtl()) {
17355            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
17356            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
17357        } else {
17358            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
17359            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
17360        }
17361    }
17362
17363    /**
17364     * @hide
17365     */
17366    public Insets getOpticalInsets() {
17367        if (mLayoutInsets == null) {
17368            mLayoutInsets = computeOpticalInsets();
17369        }
17370        return mLayoutInsets;
17371    }
17372
17373    /**
17374     * Set this view's optical insets.
17375     *
17376     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
17377     * property. Views that compute their own optical insets should call it as part of measurement.
17378     * This method does not request layout. If you are setting optical insets outside of
17379     * measure/layout itself you will want to call requestLayout() yourself.
17380     * </p>
17381     * @hide
17382     */
17383    public void setOpticalInsets(Insets insets) {
17384        mLayoutInsets = insets;
17385    }
17386
17387    /**
17388     * Changes the selection state of this view. A view can be selected or not.
17389     * Note that selection is not the same as focus. Views are typically
17390     * selected in the context of an AdapterView like ListView or GridView;
17391     * the selected view is the view that is highlighted.
17392     *
17393     * @param selected true if the view must be selected, false otherwise
17394     */
17395    public void setSelected(boolean selected) {
17396        //noinspection DoubleNegation
17397        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
17398            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
17399            if (!selected) resetPressedState();
17400            invalidate(true);
17401            refreshDrawableState();
17402            dispatchSetSelected(selected);
17403            if (selected) {
17404                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
17405            } else {
17406                notifyViewAccessibilityStateChangedIfNeeded(
17407                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
17408            }
17409        }
17410    }
17411
17412    /**
17413     * Dispatch setSelected to all of this View's children.
17414     *
17415     * @see #setSelected(boolean)
17416     *
17417     * @param selected The new selected state
17418     */
17419    protected void dispatchSetSelected(boolean selected) {
17420    }
17421
17422    /**
17423     * Indicates the selection state of this view.
17424     *
17425     * @return true if the view is selected, false otherwise
17426     */
17427    @ViewDebug.ExportedProperty
17428    public boolean isSelected() {
17429        return (mPrivateFlags & PFLAG_SELECTED) != 0;
17430    }
17431
17432    /**
17433     * Changes the activated state of this view. A view can be activated or not.
17434     * Note that activation is not the same as selection.  Selection is
17435     * a transient property, representing the view (hierarchy) the user is
17436     * currently interacting with.  Activation is a longer-term state that the
17437     * user can move views in and out of.  For example, in a list view with
17438     * single or multiple selection enabled, the views in the current selection
17439     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
17440     * here.)  The activated state is propagated down to children of the view it
17441     * is set on.
17442     *
17443     * @param activated true if the view must be activated, false otherwise
17444     */
17445    public void setActivated(boolean activated) {
17446        //noinspection DoubleNegation
17447        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
17448            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
17449            invalidate(true);
17450            refreshDrawableState();
17451            dispatchSetActivated(activated);
17452        }
17453    }
17454
17455    /**
17456     * Dispatch setActivated to all of this View's children.
17457     *
17458     * @see #setActivated(boolean)
17459     *
17460     * @param activated The new activated state
17461     */
17462    protected void dispatchSetActivated(boolean activated) {
17463    }
17464
17465    /**
17466     * Indicates the activation state of this view.
17467     *
17468     * @return true if the view is activated, false otherwise
17469     */
17470    @ViewDebug.ExportedProperty
17471    public boolean isActivated() {
17472        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
17473    }
17474
17475    /**
17476     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
17477     * observer can be used to get notifications when global events, like
17478     * layout, happen.
17479     *
17480     * The returned ViewTreeObserver observer is not guaranteed to remain
17481     * valid for the lifetime of this View. If the caller of this method keeps
17482     * a long-lived reference to ViewTreeObserver, it should always check for
17483     * the return value of {@link ViewTreeObserver#isAlive()}.
17484     *
17485     * @return The ViewTreeObserver for this view's hierarchy.
17486     */
17487    public ViewTreeObserver getViewTreeObserver() {
17488        if (mAttachInfo != null) {
17489            return mAttachInfo.mTreeObserver;
17490        }
17491        if (mFloatingTreeObserver == null) {
17492            mFloatingTreeObserver = new ViewTreeObserver();
17493        }
17494        return mFloatingTreeObserver;
17495    }
17496
17497    /**
17498     * <p>Finds the topmost view in the current view hierarchy.</p>
17499     *
17500     * @return the topmost view containing this view
17501     */
17502    public View getRootView() {
17503        if (mAttachInfo != null) {
17504            final View v = mAttachInfo.mRootView;
17505            if (v != null) {
17506                return v;
17507            }
17508        }
17509
17510        View parent = this;
17511
17512        while (parent.mParent != null && parent.mParent instanceof View) {
17513            parent = (View) parent.mParent;
17514        }
17515
17516        return parent;
17517    }
17518
17519    /**
17520     * Transforms a motion event from view-local coordinates to on-screen
17521     * coordinates.
17522     *
17523     * @param ev the view-local motion event
17524     * @return false if the transformation could not be applied
17525     * @hide
17526     */
17527    public boolean toGlobalMotionEvent(MotionEvent ev) {
17528        final AttachInfo info = mAttachInfo;
17529        if (info == null) {
17530            return false;
17531        }
17532
17533        final Matrix m = info.mTmpMatrix;
17534        m.set(Matrix.IDENTITY_MATRIX);
17535        transformMatrixToGlobal(m);
17536        ev.transform(m);
17537        return true;
17538    }
17539
17540    /**
17541     * Transforms a motion event from on-screen coordinates to view-local
17542     * coordinates.
17543     *
17544     * @param ev the on-screen motion event
17545     * @return false if the transformation could not be applied
17546     * @hide
17547     */
17548    public boolean toLocalMotionEvent(MotionEvent ev) {
17549        final AttachInfo info = mAttachInfo;
17550        if (info == null) {
17551            return false;
17552        }
17553
17554        final Matrix m = info.mTmpMatrix;
17555        m.set(Matrix.IDENTITY_MATRIX);
17556        transformMatrixToLocal(m);
17557        ev.transform(m);
17558        return true;
17559    }
17560
17561    /**
17562     * Modifies the input matrix such that it maps view-local coordinates to
17563     * on-screen coordinates.
17564     *
17565     * @param m input matrix to modify
17566     * @hide
17567     */
17568    public void transformMatrixToGlobal(Matrix m) {
17569        final ViewParent parent = mParent;
17570        if (parent instanceof View) {
17571            final View vp = (View) parent;
17572            vp.transformMatrixToGlobal(m);
17573            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
17574        } else if (parent instanceof ViewRootImpl) {
17575            final ViewRootImpl vr = (ViewRootImpl) parent;
17576            vr.transformMatrixToGlobal(m);
17577            m.preTranslate(0, -vr.mCurScrollY);
17578        }
17579
17580        m.preTranslate(mLeft, mTop);
17581
17582        if (!hasIdentityMatrix()) {
17583            m.preConcat(getMatrix());
17584        }
17585    }
17586
17587    /**
17588     * Modifies the input matrix such that it maps on-screen coordinates to
17589     * view-local coordinates.
17590     *
17591     * @param m input matrix to modify
17592     * @hide
17593     */
17594    public void transformMatrixToLocal(Matrix m) {
17595        final ViewParent parent = mParent;
17596        if (parent instanceof View) {
17597            final View vp = (View) parent;
17598            vp.transformMatrixToLocal(m);
17599            m.postTranslate(vp.mScrollX, vp.mScrollY);
17600        } else if (parent instanceof ViewRootImpl) {
17601            final ViewRootImpl vr = (ViewRootImpl) parent;
17602            vr.transformMatrixToLocal(m);
17603            m.postTranslate(0, vr.mCurScrollY);
17604        }
17605
17606        m.postTranslate(-mLeft, -mTop);
17607
17608        if (!hasIdentityMatrix()) {
17609            m.postConcat(getInverseMatrix());
17610        }
17611    }
17612
17613    /**
17614     * @hide
17615     */
17616    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
17617            @ViewDebug.IntToString(from = 0, to = "x"),
17618            @ViewDebug.IntToString(from = 1, to = "y")
17619    })
17620    public int[] getLocationOnScreen() {
17621        int[] location = new int[2];
17622        getLocationOnScreen(location);
17623        return location;
17624    }
17625
17626    /**
17627     * <p>Computes the coordinates of this view on the screen. The argument
17628     * must be an array of two integers. After the method returns, the array
17629     * contains the x and y location in that order.</p>
17630     *
17631     * @param location an array of two integers in which to hold the coordinates
17632     */
17633    public void getLocationOnScreen(@Size(2) int[] location) {
17634        getLocationInWindow(location);
17635
17636        final AttachInfo info = mAttachInfo;
17637        if (info != null) {
17638            location[0] += info.mWindowLeft;
17639            location[1] += info.mWindowTop;
17640        }
17641    }
17642
17643    /**
17644     * <p>Computes the coordinates of this view in its window. The argument
17645     * must be an array of two integers. After the method returns, the array
17646     * contains the x and y location in that order.</p>
17647     *
17648     * @param location an array of two integers in which to hold the coordinates
17649     */
17650    public void getLocationInWindow(@Size(2) int[] location) {
17651        if (location == null || location.length < 2) {
17652            throw new IllegalArgumentException("location must be an array of two integers");
17653        }
17654
17655        if (mAttachInfo == null) {
17656            // When the view is not attached to a window, this method does not make sense
17657            location[0] = location[1] = 0;
17658            return;
17659        }
17660
17661        float[] position = mAttachInfo.mTmpTransformLocation;
17662        position[0] = position[1] = 0.0f;
17663
17664        if (!hasIdentityMatrix()) {
17665            getMatrix().mapPoints(position);
17666        }
17667
17668        position[0] += mLeft;
17669        position[1] += mTop;
17670
17671        ViewParent viewParent = mParent;
17672        while (viewParent instanceof View) {
17673            final View view = (View) viewParent;
17674
17675            position[0] -= view.mScrollX;
17676            position[1] -= view.mScrollY;
17677
17678            if (!view.hasIdentityMatrix()) {
17679                view.getMatrix().mapPoints(position);
17680            }
17681
17682            position[0] += view.mLeft;
17683            position[1] += view.mTop;
17684
17685            viewParent = view.mParent;
17686         }
17687
17688        if (viewParent instanceof ViewRootImpl) {
17689            // *cough*
17690            final ViewRootImpl vr = (ViewRootImpl) viewParent;
17691            position[1] -= vr.mCurScrollY;
17692        }
17693
17694        location[0] = (int) (position[0] + 0.5f);
17695        location[1] = (int) (position[1] + 0.5f);
17696    }
17697
17698    /**
17699     * {@hide}
17700     * @param id the id of the view to be found
17701     * @return the view of the specified id, null if cannot be found
17702     */
17703    protected View findViewTraversal(@IdRes int id) {
17704        if (id == mID) {
17705            return this;
17706        }
17707        return null;
17708    }
17709
17710    /**
17711     * {@hide}
17712     * @param tag the tag of the view to be found
17713     * @return the view of specified tag, null if cannot be found
17714     */
17715    protected View findViewWithTagTraversal(Object tag) {
17716        if (tag != null && tag.equals(mTag)) {
17717            return this;
17718        }
17719        return null;
17720    }
17721
17722    /**
17723     * {@hide}
17724     * @param predicate The predicate to evaluate.
17725     * @param childToSkip If not null, ignores this child during the recursive traversal.
17726     * @return The first view that matches the predicate or null.
17727     */
17728    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
17729        if (predicate.apply(this)) {
17730            return this;
17731        }
17732        return null;
17733    }
17734
17735    /**
17736     * Look for a child view with the given id.  If this view has the given
17737     * id, return this view.
17738     *
17739     * @param id The id to search for.
17740     * @return The view that has the given id in the hierarchy or null
17741     */
17742    @Nullable
17743    public final View findViewById(@IdRes int id) {
17744        if (id < 0) {
17745            return null;
17746        }
17747        return findViewTraversal(id);
17748    }
17749
17750    /**
17751     * Finds a view by its unuque and stable accessibility id.
17752     *
17753     * @param accessibilityId The searched accessibility id.
17754     * @return The found view.
17755     */
17756    final View findViewByAccessibilityId(int accessibilityId) {
17757        if (accessibilityId < 0) {
17758            return null;
17759        }
17760        return findViewByAccessibilityIdTraversal(accessibilityId);
17761    }
17762
17763    /**
17764     * Performs the traversal to find a view by its unuque and stable accessibility id.
17765     *
17766     * <strong>Note:</strong>This method does not stop at the root namespace
17767     * boundary since the user can touch the screen at an arbitrary location
17768     * potentially crossing the root namespace bounday which will send an
17769     * accessibility event to accessibility services and they should be able
17770     * to obtain the event source. Also accessibility ids are guaranteed to be
17771     * unique in the window.
17772     *
17773     * @param accessibilityId The accessibility id.
17774     * @return The found view.
17775     *
17776     * @hide
17777     */
17778    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
17779        if (getAccessibilityViewId() == accessibilityId) {
17780            return this;
17781        }
17782        return null;
17783    }
17784
17785    /**
17786     * Look for a child view with the given tag.  If this view has the given
17787     * tag, return this view.
17788     *
17789     * @param tag The tag to search for, using "tag.equals(getTag())".
17790     * @return The View that has the given tag in the hierarchy or null
17791     */
17792    public final View findViewWithTag(Object tag) {
17793        if (tag == null) {
17794            return null;
17795        }
17796        return findViewWithTagTraversal(tag);
17797    }
17798
17799    /**
17800     * {@hide}
17801     * Look for a child view that matches the specified predicate.
17802     * If this view matches the predicate, return this view.
17803     *
17804     * @param predicate The predicate to evaluate.
17805     * @return The first view that matches the predicate or null.
17806     */
17807    public final View findViewByPredicate(Predicate<View> predicate) {
17808        return findViewByPredicateTraversal(predicate, null);
17809    }
17810
17811    /**
17812     * {@hide}
17813     * Look for a child view that matches the specified predicate,
17814     * starting with the specified view and its descendents and then
17815     * recusively searching the ancestors and siblings of that view
17816     * until this view is reached.
17817     *
17818     * This method is useful in cases where the predicate does not match
17819     * a single unique view (perhaps multiple views use the same id)
17820     * and we are trying to find the view that is "closest" in scope to the
17821     * starting view.
17822     *
17823     * @param start The view to start from.
17824     * @param predicate The predicate to evaluate.
17825     * @return The first view that matches the predicate or null.
17826     */
17827    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
17828        View childToSkip = null;
17829        for (;;) {
17830            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
17831            if (view != null || start == this) {
17832                return view;
17833            }
17834
17835            ViewParent parent = start.getParent();
17836            if (parent == null || !(parent instanceof View)) {
17837                return null;
17838            }
17839
17840            childToSkip = start;
17841            start = (View) parent;
17842        }
17843    }
17844
17845    /**
17846     * Sets the identifier for this view. The identifier does not have to be
17847     * unique in this view's hierarchy. The identifier should be a positive
17848     * number.
17849     *
17850     * @see #NO_ID
17851     * @see #getId()
17852     * @see #findViewById(int)
17853     *
17854     * @param id a number used to identify the view
17855     *
17856     * @attr ref android.R.styleable#View_id
17857     */
17858    public void setId(@IdRes int id) {
17859        mID = id;
17860        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
17861            mID = generateViewId();
17862        }
17863    }
17864
17865    /**
17866     * {@hide}
17867     *
17868     * @param isRoot true if the view belongs to the root namespace, false
17869     *        otherwise
17870     */
17871    public void setIsRootNamespace(boolean isRoot) {
17872        if (isRoot) {
17873            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
17874        } else {
17875            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
17876        }
17877    }
17878
17879    /**
17880     * {@hide}
17881     *
17882     * @return true if the view belongs to the root namespace, false otherwise
17883     */
17884    public boolean isRootNamespace() {
17885        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
17886    }
17887
17888    /**
17889     * Returns this view's identifier.
17890     *
17891     * @return a positive integer used to identify the view or {@link #NO_ID}
17892     *         if the view has no ID
17893     *
17894     * @see #setId(int)
17895     * @see #findViewById(int)
17896     * @attr ref android.R.styleable#View_id
17897     */
17898    @IdRes
17899    @ViewDebug.CapturedViewProperty
17900    public int getId() {
17901        return mID;
17902    }
17903
17904    /**
17905     * Returns this view's tag.
17906     *
17907     * @return the Object stored in this view as a tag, or {@code null} if not
17908     *         set
17909     *
17910     * @see #setTag(Object)
17911     * @see #getTag(int)
17912     */
17913    @ViewDebug.ExportedProperty
17914    public Object getTag() {
17915        return mTag;
17916    }
17917
17918    /**
17919     * Sets the tag associated with this view. A tag can be used to mark
17920     * a view in its hierarchy and does not have to be unique within the
17921     * hierarchy. Tags can also be used to store data within a view without
17922     * resorting to another data structure.
17923     *
17924     * @param tag an Object to tag the view with
17925     *
17926     * @see #getTag()
17927     * @see #setTag(int, Object)
17928     */
17929    public void setTag(final Object tag) {
17930        mTag = tag;
17931    }
17932
17933    /**
17934     * Returns the tag associated with this view and the specified key.
17935     *
17936     * @param key The key identifying the tag
17937     *
17938     * @return the Object stored in this view as a tag, or {@code null} if not
17939     *         set
17940     *
17941     * @see #setTag(int, Object)
17942     * @see #getTag()
17943     */
17944    public Object getTag(int key) {
17945        if (mKeyedTags != null) return mKeyedTags.get(key);
17946        return null;
17947    }
17948
17949    /**
17950     * Sets a tag associated with this view and a key. A tag can be used
17951     * to mark a view in its hierarchy and does not have to be unique within
17952     * the hierarchy. Tags can also be used to store data within a view
17953     * without resorting to another data structure.
17954     *
17955     * The specified key should be an id declared in the resources of the
17956     * application to ensure it is unique (see the <a
17957     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
17958     * Keys identified as belonging to
17959     * the Android framework or not associated with any package will cause
17960     * an {@link IllegalArgumentException} to be thrown.
17961     *
17962     * @param key The key identifying the tag
17963     * @param tag An Object to tag the view with
17964     *
17965     * @throws IllegalArgumentException If they specified key is not valid
17966     *
17967     * @see #setTag(Object)
17968     * @see #getTag(int)
17969     */
17970    public void setTag(int key, final Object tag) {
17971        // If the package id is 0x00 or 0x01, it's either an undefined package
17972        // or a framework id
17973        if ((key >>> 24) < 2) {
17974            throw new IllegalArgumentException("The key must be an application-specific "
17975                    + "resource id.");
17976        }
17977
17978        setKeyedTag(key, tag);
17979    }
17980
17981    /**
17982     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
17983     * framework id.
17984     *
17985     * @hide
17986     */
17987    public void setTagInternal(int key, Object tag) {
17988        if ((key >>> 24) != 0x1) {
17989            throw new IllegalArgumentException("The key must be a framework-specific "
17990                    + "resource id.");
17991        }
17992
17993        setKeyedTag(key, tag);
17994    }
17995
17996    private void setKeyedTag(int key, Object tag) {
17997        if (mKeyedTags == null) {
17998            mKeyedTags = new SparseArray<Object>(2);
17999        }
18000
18001        mKeyedTags.put(key, tag);
18002    }
18003
18004    /**
18005     * Prints information about this view in the log output, with the tag
18006     * {@link #VIEW_LOG_TAG}.
18007     *
18008     * @hide
18009     */
18010    public void debug() {
18011        debug(0);
18012    }
18013
18014    /**
18015     * Prints information about this view in the log output, with the tag
18016     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
18017     * indentation defined by the <code>depth</code>.
18018     *
18019     * @param depth the indentation level
18020     *
18021     * @hide
18022     */
18023    protected void debug(int depth) {
18024        String output = debugIndent(depth - 1);
18025
18026        output += "+ " + this;
18027        int id = getId();
18028        if (id != -1) {
18029            output += " (id=" + id + ")";
18030        }
18031        Object tag = getTag();
18032        if (tag != null) {
18033            output += " (tag=" + tag + ")";
18034        }
18035        Log.d(VIEW_LOG_TAG, output);
18036
18037        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
18038            output = debugIndent(depth) + " FOCUSED";
18039            Log.d(VIEW_LOG_TAG, output);
18040        }
18041
18042        output = debugIndent(depth);
18043        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
18044                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
18045                + "} ";
18046        Log.d(VIEW_LOG_TAG, output);
18047
18048        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
18049                || mPaddingBottom != 0) {
18050            output = debugIndent(depth);
18051            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
18052                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
18053            Log.d(VIEW_LOG_TAG, output);
18054        }
18055
18056        output = debugIndent(depth);
18057        output += "mMeasureWidth=" + mMeasuredWidth +
18058                " mMeasureHeight=" + mMeasuredHeight;
18059        Log.d(VIEW_LOG_TAG, output);
18060
18061        output = debugIndent(depth);
18062        if (mLayoutParams == null) {
18063            output += "BAD! no layout params";
18064        } else {
18065            output = mLayoutParams.debug(output);
18066        }
18067        Log.d(VIEW_LOG_TAG, output);
18068
18069        output = debugIndent(depth);
18070        output += "flags={";
18071        output += View.printFlags(mViewFlags);
18072        output += "}";
18073        Log.d(VIEW_LOG_TAG, output);
18074
18075        output = debugIndent(depth);
18076        output += "privateFlags={";
18077        output += View.printPrivateFlags(mPrivateFlags);
18078        output += "}";
18079        Log.d(VIEW_LOG_TAG, output);
18080    }
18081
18082    /**
18083     * Creates a string of whitespaces used for indentation.
18084     *
18085     * @param depth the indentation level
18086     * @return a String containing (depth * 2 + 3) * 2 white spaces
18087     *
18088     * @hide
18089     */
18090    protected static String debugIndent(int depth) {
18091        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
18092        for (int i = 0; i < (depth * 2) + 3; i++) {
18093            spaces.append(' ').append(' ');
18094        }
18095        return spaces.toString();
18096    }
18097
18098    /**
18099     * <p>Return the offset of the widget's text baseline from the widget's top
18100     * boundary. If this widget does not support baseline alignment, this
18101     * method returns -1. </p>
18102     *
18103     * @return the offset of the baseline within the widget's bounds or -1
18104     *         if baseline alignment is not supported
18105     */
18106    @ViewDebug.ExportedProperty(category = "layout")
18107    public int getBaseline() {
18108        return -1;
18109    }
18110
18111    /**
18112     * Returns whether the view hierarchy is currently undergoing a layout pass. This
18113     * information is useful to avoid situations such as calling {@link #requestLayout()} during
18114     * a layout pass.
18115     *
18116     * @return whether the view hierarchy is currently undergoing a layout pass
18117     */
18118    public boolean isInLayout() {
18119        ViewRootImpl viewRoot = getViewRootImpl();
18120        return (viewRoot != null && viewRoot.isInLayout());
18121    }
18122
18123    /**
18124     * Call this when something has changed which has invalidated the
18125     * layout of this view. This will schedule a layout pass of the view
18126     * tree. This should not be called while the view hierarchy is currently in a layout
18127     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
18128     * end of the current layout pass (and then layout will run again) or after the current
18129     * frame is drawn and the next layout occurs.
18130     *
18131     * <p>Subclasses which override this method should call the superclass method to
18132     * handle possible request-during-layout errors correctly.</p>
18133     */
18134    @CallSuper
18135    public void requestLayout() {
18136        if (mMeasureCache != null) mMeasureCache.clear();
18137
18138        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
18139            // Only trigger request-during-layout logic if this is the view requesting it,
18140            // not the views in its parent hierarchy
18141            ViewRootImpl viewRoot = getViewRootImpl();
18142            if (viewRoot != null && viewRoot.isInLayout()) {
18143                if (!viewRoot.requestLayoutDuringLayout(this)) {
18144                    return;
18145                }
18146            }
18147            mAttachInfo.mViewRequestingLayout = this;
18148        }
18149
18150        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18151        mPrivateFlags |= PFLAG_INVALIDATED;
18152
18153        if (mParent != null && !mParent.isLayoutRequested()) {
18154            mParent.requestLayout();
18155        }
18156        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
18157            mAttachInfo.mViewRequestingLayout = null;
18158        }
18159    }
18160
18161    /**
18162     * Forces this view to be laid out during the next layout pass.
18163     * This method does not call requestLayout() or forceLayout()
18164     * on the parent.
18165     */
18166    public void forceLayout() {
18167        if (mMeasureCache != null) mMeasureCache.clear();
18168
18169        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18170        mPrivateFlags |= PFLAG_INVALIDATED;
18171    }
18172
18173    /**
18174     * <p>
18175     * This is called to find out how big a view should be. The parent
18176     * supplies constraint information in the width and height parameters.
18177     * </p>
18178     *
18179     * <p>
18180     * The actual measurement work of a view is performed in
18181     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
18182     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
18183     * </p>
18184     *
18185     *
18186     * @param widthMeasureSpec Horizontal space requirements as imposed by the
18187     *        parent
18188     * @param heightMeasureSpec Vertical space requirements as imposed by the
18189     *        parent
18190     *
18191     * @see #onMeasure(int, int)
18192     */
18193    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
18194        boolean optical = isLayoutModeOptical(this);
18195        if (optical != isLayoutModeOptical(mParent)) {
18196            Insets insets = getOpticalInsets();
18197            int oWidth  = insets.left + insets.right;
18198            int oHeight = insets.top  + insets.bottom;
18199            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
18200            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
18201        }
18202
18203        // Suppress sign extension for the low bytes
18204        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
18205        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
18206
18207        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18208        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
18209                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
18210        final boolean matchingSize = isExactly &&
18211                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
18212                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
18213        if (forceLayout || !matchingSize &&
18214                (widthMeasureSpec != mOldWidthMeasureSpec ||
18215                        heightMeasureSpec != mOldHeightMeasureSpec)) {
18216
18217            // first clears the measured dimension flag
18218            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
18219
18220            resolveRtlPropertiesIfNeeded();
18221
18222            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
18223            if (cacheIndex < 0 || sIgnoreMeasureCache) {
18224                // measure ourselves, this should set the measured dimension flag back
18225                onMeasure(widthMeasureSpec, heightMeasureSpec);
18226                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18227            } else {
18228                long value = mMeasureCache.valueAt(cacheIndex);
18229                // Casting a long to int drops the high 32 bits, no mask needed
18230                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
18231                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18232            }
18233
18234            // flag not set, setMeasuredDimension() was not invoked, we raise
18235            // an exception to warn the developer
18236            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
18237                throw new IllegalStateException("View with id " + getId() + ": "
18238                        + getClass().getName() + "#onMeasure() did not set the"
18239                        + " measured dimension by calling"
18240                        + " setMeasuredDimension()");
18241            }
18242
18243            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
18244        }
18245
18246        mOldWidthMeasureSpec = widthMeasureSpec;
18247        mOldHeightMeasureSpec = heightMeasureSpec;
18248
18249        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
18250                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
18251    }
18252
18253    /**
18254     * <p>
18255     * Measure the view and its content to determine the measured width and the
18256     * measured height. This method is invoked by {@link #measure(int, int)} and
18257     * should be overridden by subclasses to provide accurate and efficient
18258     * measurement of their contents.
18259     * </p>
18260     *
18261     * <p>
18262     * <strong>CONTRACT:</strong> When overriding this method, you
18263     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
18264     * measured width and height of this view. Failure to do so will trigger an
18265     * <code>IllegalStateException</code>, thrown by
18266     * {@link #measure(int, int)}. Calling the superclass'
18267     * {@link #onMeasure(int, int)} is a valid use.
18268     * </p>
18269     *
18270     * <p>
18271     * The base class implementation of measure defaults to the background size,
18272     * unless a larger size is allowed by the MeasureSpec. Subclasses should
18273     * override {@link #onMeasure(int, int)} to provide better measurements of
18274     * their content.
18275     * </p>
18276     *
18277     * <p>
18278     * If this method is overridden, it is the subclass's responsibility to make
18279     * sure the measured height and width are at least the view's minimum height
18280     * and width ({@link #getSuggestedMinimumHeight()} and
18281     * {@link #getSuggestedMinimumWidth()}).
18282     * </p>
18283     *
18284     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
18285     *                         The requirements are encoded with
18286     *                         {@link android.view.View.MeasureSpec}.
18287     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
18288     *                         The requirements are encoded with
18289     *                         {@link android.view.View.MeasureSpec}.
18290     *
18291     * @see #getMeasuredWidth()
18292     * @see #getMeasuredHeight()
18293     * @see #setMeasuredDimension(int, int)
18294     * @see #getSuggestedMinimumHeight()
18295     * @see #getSuggestedMinimumWidth()
18296     * @see android.view.View.MeasureSpec#getMode(int)
18297     * @see android.view.View.MeasureSpec#getSize(int)
18298     */
18299    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
18300        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
18301                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
18302    }
18303
18304    /**
18305     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
18306     * measured width and measured height. Failing to do so will trigger an
18307     * exception at measurement time.</p>
18308     *
18309     * @param measuredWidth The measured width of this view.  May be a complex
18310     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18311     * {@link #MEASURED_STATE_TOO_SMALL}.
18312     * @param measuredHeight The measured height of this view.  May be a complex
18313     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18314     * {@link #MEASURED_STATE_TOO_SMALL}.
18315     */
18316    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
18317        boolean optical = isLayoutModeOptical(this);
18318        if (optical != isLayoutModeOptical(mParent)) {
18319            Insets insets = getOpticalInsets();
18320            int opticalWidth  = insets.left + insets.right;
18321            int opticalHeight = insets.top  + insets.bottom;
18322
18323            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
18324            measuredHeight += optical ? opticalHeight : -opticalHeight;
18325        }
18326        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
18327    }
18328
18329    /**
18330     * Sets the measured dimension without extra processing for things like optical bounds.
18331     * Useful for reapplying consistent values that have already been cooked with adjustments
18332     * for optical bounds, etc. such as those from the measurement cache.
18333     *
18334     * @param measuredWidth The measured width of this view.  May be a complex
18335     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18336     * {@link #MEASURED_STATE_TOO_SMALL}.
18337     * @param measuredHeight The measured height of this view.  May be a complex
18338     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18339     * {@link #MEASURED_STATE_TOO_SMALL}.
18340     */
18341    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
18342        mMeasuredWidth = measuredWidth;
18343        mMeasuredHeight = measuredHeight;
18344
18345        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
18346    }
18347
18348    /**
18349     * Merge two states as returned by {@link #getMeasuredState()}.
18350     * @param curState The current state as returned from a view or the result
18351     * of combining multiple views.
18352     * @param newState The new view state to combine.
18353     * @return Returns a new integer reflecting the combination of the two
18354     * states.
18355     */
18356    public static int combineMeasuredStates(int curState, int newState) {
18357        return curState | newState;
18358    }
18359
18360    /**
18361     * Version of {@link #resolveSizeAndState(int, int, int)}
18362     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
18363     */
18364    public static int resolveSize(int size, int measureSpec) {
18365        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
18366    }
18367
18368    /**
18369     * Utility to reconcile a desired size and state, with constraints imposed
18370     * by a MeasureSpec. Will take the desired size, unless a different size
18371     * is imposed by the constraints. The returned value is a compound integer,
18372     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
18373     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
18374     * resulting size is smaller than the size the view wants to be.
18375     *
18376     * @param size How big the view wants to be.
18377     * @param measureSpec Constraints imposed by the parent.
18378     * @param childMeasuredState Size information bit mask for the view's
18379     *                           children.
18380     * @return Size information bit mask as defined by
18381     *         {@link #MEASURED_SIZE_MASK} and
18382     *         {@link #MEASURED_STATE_TOO_SMALL}.
18383     */
18384    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
18385        final int specMode = MeasureSpec.getMode(measureSpec);
18386        final int specSize = MeasureSpec.getSize(measureSpec);
18387        final int result;
18388        switch (specMode) {
18389            case MeasureSpec.AT_MOST:
18390                if (specSize < size) {
18391                    result = specSize | MEASURED_STATE_TOO_SMALL;
18392                } else {
18393                    result = size;
18394                }
18395                break;
18396            case MeasureSpec.EXACTLY:
18397                result = specSize;
18398                break;
18399            case MeasureSpec.UNSPECIFIED:
18400            default:
18401                result = size;
18402        }
18403        return result | (childMeasuredState & MEASURED_STATE_MASK);
18404    }
18405
18406    /**
18407     * Utility to return a default size. Uses the supplied size if the
18408     * MeasureSpec imposed no constraints. Will get larger if allowed
18409     * by the MeasureSpec.
18410     *
18411     * @param size Default size for this view
18412     * @param measureSpec Constraints imposed by the parent
18413     * @return The size this view should be.
18414     */
18415    public static int getDefaultSize(int size, int measureSpec) {
18416        int result = size;
18417        int specMode = MeasureSpec.getMode(measureSpec);
18418        int specSize = MeasureSpec.getSize(measureSpec);
18419
18420        switch (specMode) {
18421        case MeasureSpec.UNSPECIFIED:
18422            result = size;
18423            break;
18424        case MeasureSpec.AT_MOST:
18425        case MeasureSpec.EXACTLY:
18426            result = specSize;
18427            break;
18428        }
18429        return result;
18430    }
18431
18432    /**
18433     * Returns the suggested minimum height that the view should use. This
18434     * returns the maximum of the view's minimum height
18435     * and the background's minimum height
18436     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
18437     * <p>
18438     * When being used in {@link #onMeasure(int, int)}, the caller should still
18439     * ensure the returned height is within the requirements of the parent.
18440     *
18441     * @return The suggested minimum height of the view.
18442     */
18443    protected int getSuggestedMinimumHeight() {
18444        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
18445
18446    }
18447
18448    /**
18449     * Returns the suggested minimum width that the view should use. This
18450     * returns the maximum of the view's minimum width)
18451     * and the background's minimum width
18452     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
18453     * <p>
18454     * When being used in {@link #onMeasure(int, int)}, the caller should still
18455     * ensure the returned width is within the requirements of the parent.
18456     *
18457     * @return The suggested minimum width of the view.
18458     */
18459    protected int getSuggestedMinimumWidth() {
18460        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
18461    }
18462
18463    /**
18464     * Returns the minimum height of the view.
18465     *
18466     * @return the minimum height the view will try to be.
18467     *
18468     * @see #setMinimumHeight(int)
18469     *
18470     * @attr ref android.R.styleable#View_minHeight
18471     */
18472    public int getMinimumHeight() {
18473        return mMinHeight;
18474    }
18475
18476    /**
18477     * Sets the minimum height of the view. It is not guaranteed the view will
18478     * be able to achieve this minimum height (for example, if its parent layout
18479     * constrains it with less available height).
18480     *
18481     * @param minHeight The minimum height the view will try to be.
18482     *
18483     * @see #getMinimumHeight()
18484     *
18485     * @attr ref android.R.styleable#View_minHeight
18486     */
18487    public void setMinimumHeight(int minHeight) {
18488        mMinHeight = minHeight;
18489        requestLayout();
18490    }
18491
18492    /**
18493     * Returns the minimum width of the view.
18494     *
18495     * @return the minimum width the view will try to be.
18496     *
18497     * @see #setMinimumWidth(int)
18498     *
18499     * @attr ref android.R.styleable#View_minWidth
18500     */
18501    public int getMinimumWidth() {
18502        return mMinWidth;
18503    }
18504
18505    /**
18506     * Sets the minimum width of the view. It is not guaranteed the view will
18507     * be able to achieve this minimum width (for example, if its parent layout
18508     * constrains it with less available width).
18509     *
18510     * @param minWidth The minimum width the view will try to be.
18511     *
18512     * @see #getMinimumWidth()
18513     *
18514     * @attr ref android.R.styleable#View_minWidth
18515     */
18516    public void setMinimumWidth(int minWidth) {
18517        mMinWidth = minWidth;
18518        requestLayout();
18519
18520    }
18521
18522    /**
18523     * Get the animation currently associated with this view.
18524     *
18525     * @return The animation that is currently playing or
18526     *         scheduled to play for this view.
18527     */
18528    public Animation getAnimation() {
18529        return mCurrentAnimation;
18530    }
18531
18532    /**
18533     * Start the specified animation now.
18534     *
18535     * @param animation the animation to start now
18536     */
18537    public void startAnimation(Animation animation) {
18538        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
18539        setAnimation(animation);
18540        invalidateParentCaches();
18541        invalidate(true);
18542    }
18543
18544    /**
18545     * Cancels any animations for this view.
18546     */
18547    public void clearAnimation() {
18548        if (mCurrentAnimation != null) {
18549            mCurrentAnimation.detach();
18550        }
18551        mCurrentAnimation = null;
18552        invalidateParentIfNeeded();
18553    }
18554
18555    /**
18556     * Sets the next animation to play for this view.
18557     * If you want the animation to play immediately, use
18558     * {@link #startAnimation(android.view.animation.Animation)} instead.
18559     * This method provides allows fine-grained
18560     * control over the start time and invalidation, but you
18561     * must make sure that 1) the animation has a start time set, and
18562     * 2) the view's parent (which controls animations on its children)
18563     * will be invalidated when the animation is supposed to
18564     * start.
18565     *
18566     * @param animation The next animation, or null.
18567     */
18568    public void setAnimation(Animation animation) {
18569        mCurrentAnimation = animation;
18570
18571        if (animation != null) {
18572            // If the screen is off assume the animation start time is now instead of
18573            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
18574            // would cause the animation to start when the screen turns back on
18575            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
18576                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
18577                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
18578            }
18579            animation.reset();
18580        }
18581    }
18582
18583    /**
18584     * Invoked by a parent ViewGroup to notify the start of the animation
18585     * currently associated with this view. If you override this method,
18586     * always call super.onAnimationStart();
18587     *
18588     * @see #setAnimation(android.view.animation.Animation)
18589     * @see #getAnimation()
18590     */
18591    @CallSuper
18592    protected void onAnimationStart() {
18593        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
18594    }
18595
18596    /**
18597     * Invoked by a parent ViewGroup to notify the end of the animation
18598     * currently associated with this view. If you override this method,
18599     * always call super.onAnimationEnd();
18600     *
18601     * @see #setAnimation(android.view.animation.Animation)
18602     * @see #getAnimation()
18603     */
18604    @CallSuper
18605    protected void onAnimationEnd() {
18606        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
18607    }
18608
18609    /**
18610     * Invoked if there is a Transform that involves alpha. Subclass that can
18611     * draw themselves with the specified alpha should return true, and then
18612     * respect that alpha when their onDraw() is called. If this returns false
18613     * then the view may be redirected to draw into an offscreen buffer to
18614     * fulfill the request, which will look fine, but may be slower than if the
18615     * subclass handles it internally. The default implementation returns false.
18616     *
18617     * @param alpha The alpha (0..255) to apply to the view's drawing
18618     * @return true if the view can draw with the specified alpha.
18619     */
18620    protected boolean onSetAlpha(int alpha) {
18621        return false;
18622    }
18623
18624    /**
18625     * This is used by the RootView to perform an optimization when
18626     * the view hierarchy contains one or several SurfaceView.
18627     * SurfaceView is always considered transparent, but its children are not,
18628     * therefore all View objects remove themselves from the global transparent
18629     * region (passed as a parameter to this function).
18630     *
18631     * @param region The transparent region for this ViewAncestor (window).
18632     *
18633     * @return Returns true if the effective visibility of the view at this
18634     * point is opaque, regardless of the transparent region; returns false
18635     * if it is possible for underlying windows to be seen behind the view.
18636     *
18637     * {@hide}
18638     */
18639    public boolean gatherTransparentRegion(Region region) {
18640        final AttachInfo attachInfo = mAttachInfo;
18641        if (region != null && attachInfo != null) {
18642            final int pflags = mPrivateFlags;
18643            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
18644                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
18645                // remove it from the transparent region.
18646                final int[] location = attachInfo.mTransparentLocation;
18647                getLocationInWindow(location);
18648                region.op(location[0], location[1], location[0] + mRight - mLeft,
18649                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
18650            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
18651                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
18652                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
18653                // exists, so we remove the background drawable's non-transparent
18654                // parts from this transparent region.
18655                applyDrawableToTransparentRegion(mBackground, region);
18656            }
18657            final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18658            if (foreground != null) {
18659                applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
18660            }
18661        }
18662        return true;
18663    }
18664
18665    /**
18666     * Play a sound effect for this view.
18667     *
18668     * <p>The framework will play sound effects for some built in actions, such as
18669     * clicking, but you may wish to play these effects in your widget,
18670     * for instance, for internal navigation.
18671     *
18672     * <p>The sound effect will only be played if sound effects are enabled by the user, and
18673     * {@link #isSoundEffectsEnabled()} is true.
18674     *
18675     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
18676     */
18677    public void playSoundEffect(int soundConstant) {
18678        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
18679            return;
18680        }
18681        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
18682    }
18683
18684    /**
18685     * BZZZTT!!1!
18686     *
18687     * <p>Provide haptic feedback to the user for this view.
18688     *
18689     * <p>The framework will provide haptic feedback for some built in actions,
18690     * such as long presses, but you may wish to provide feedback for your
18691     * own widget.
18692     *
18693     * <p>The feedback will only be performed if
18694     * {@link #isHapticFeedbackEnabled()} is true.
18695     *
18696     * @param feedbackConstant One of the constants defined in
18697     * {@link HapticFeedbackConstants}
18698     */
18699    public boolean performHapticFeedback(int feedbackConstant) {
18700        return performHapticFeedback(feedbackConstant, 0);
18701    }
18702
18703    /**
18704     * BZZZTT!!1!
18705     *
18706     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
18707     *
18708     * @param feedbackConstant One of the constants defined in
18709     * {@link HapticFeedbackConstants}
18710     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
18711     */
18712    public boolean performHapticFeedback(int feedbackConstant, int flags) {
18713        if (mAttachInfo == null) {
18714            return false;
18715        }
18716        //noinspection SimplifiableIfStatement
18717        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
18718                && !isHapticFeedbackEnabled()) {
18719            return false;
18720        }
18721        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
18722                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
18723    }
18724
18725    /**
18726     * Request that the visibility of the status bar or other screen/window
18727     * decorations be changed.
18728     *
18729     * <p>This method is used to put the over device UI into temporary modes
18730     * where the user's attention is focused more on the application content,
18731     * by dimming or hiding surrounding system affordances.  This is typically
18732     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
18733     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
18734     * to be placed behind the action bar (and with these flags other system
18735     * affordances) so that smooth transitions between hiding and showing them
18736     * can be done.
18737     *
18738     * <p>Two representative examples of the use of system UI visibility is
18739     * implementing a content browsing application (like a magazine reader)
18740     * and a video playing application.
18741     *
18742     * <p>The first code shows a typical implementation of a View in a content
18743     * browsing application.  In this implementation, the application goes
18744     * into a content-oriented mode by hiding the status bar and action bar,
18745     * and putting the navigation elements into lights out mode.  The user can
18746     * then interact with content while in this mode.  Such an application should
18747     * provide an easy way for the user to toggle out of the mode (such as to
18748     * check information in the status bar or access notifications).  In the
18749     * implementation here, this is done simply by tapping on the content.
18750     *
18751     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
18752     *      content}
18753     *
18754     * <p>This second code sample shows a typical implementation of a View
18755     * in a video playing application.  In this situation, while the video is
18756     * playing the application would like to go into a complete full-screen mode,
18757     * to use as much of the display as possible for the video.  When in this state
18758     * the user can not interact with the application; the system intercepts
18759     * touching on the screen to pop the UI out of full screen mode.  See
18760     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
18761     *
18762     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
18763     *      content}
18764     *
18765     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18766     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18767     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18768     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18769     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18770     */
18771    public void setSystemUiVisibility(int visibility) {
18772        if (visibility != mSystemUiVisibility) {
18773            mSystemUiVisibility = visibility;
18774            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18775                mParent.recomputeViewAttributes(this);
18776            }
18777        }
18778    }
18779
18780    /**
18781     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
18782     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18783     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18784     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18785     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18786     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18787     */
18788    public int getSystemUiVisibility() {
18789        return mSystemUiVisibility;
18790    }
18791
18792    /**
18793     * Returns the current system UI visibility that is currently set for
18794     * the entire window.  This is the combination of the
18795     * {@link #setSystemUiVisibility(int)} values supplied by all of the
18796     * views in the window.
18797     */
18798    public int getWindowSystemUiVisibility() {
18799        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
18800    }
18801
18802    /**
18803     * Override to find out when the window's requested system UI visibility
18804     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
18805     * This is different from the callbacks received through
18806     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
18807     * in that this is only telling you about the local request of the window,
18808     * not the actual values applied by the system.
18809     */
18810    public void onWindowSystemUiVisibilityChanged(int visible) {
18811    }
18812
18813    /**
18814     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
18815     * the view hierarchy.
18816     */
18817    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
18818        onWindowSystemUiVisibilityChanged(visible);
18819    }
18820
18821    /**
18822     * Set a listener to receive callbacks when the visibility of the system bar changes.
18823     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
18824     */
18825    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
18826        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
18827        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18828            mParent.recomputeViewAttributes(this);
18829        }
18830    }
18831
18832    /**
18833     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
18834     * the view hierarchy.
18835     */
18836    public void dispatchSystemUiVisibilityChanged(int visibility) {
18837        ListenerInfo li = mListenerInfo;
18838        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
18839            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
18840                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
18841        }
18842    }
18843
18844    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
18845        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
18846        if (val != mSystemUiVisibility) {
18847            setSystemUiVisibility(val);
18848            return true;
18849        }
18850        return false;
18851    }
18852
18853    /** @hide */
18854    public void setDisabledSystemUiVisibility(int flags) {
18855        if (mAttachInfo != null) {
18856            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
18857                mAttachInfo.mDisabledSystemUiVisibility = flags;
18858                if (mParent != null) {
18859                    mParent.recomputeViewAttributes(this);
18860                }
18861            }
18862        }
18863    }
18864
18865    /**
18866     * Creates an image that the system displays during the drag and drop
18867     * operation. This is called a &quot;drag shadow&quot;. The default implementation
18868     * for a DragShadowBuilder based on a View returns an image that has exactly the same
18869     * appearance as the given View. The default also positions the center of the drag shadow
18870     * directly under the touch point. If no View is provided (the constructor with no parameters
18871     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
18872     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
18873     * default is an invisible drag shadow.
18874     * <p>
18875     * You are not required to use the View you provide to the constructor as the basis of the
18876     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
18877     * anything you want as the drag shadow.
18878     * </p>
18879     * <p>
18880     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
18881     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
18882     *  size and position of the drag shadow. It uses this data to construct a
18883     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
18884     *  so that your application can draw the shadow image in the Canvas.
18885     * </p>
18886     *
18887     * <div class="special reference">
18888     * <h3>Developer Guides</h3>
18889     * <p>For a guide to implementing drag and drop features, read the
18890     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18891     * </div>
18892     */
18893    public static class DragShadowBuilder {
18894        private final WeakReference<View> mView;
18895
18896        /**
18897         * Constructs a shadow image builder based on a View. By default, the resulting drag
18898         * shadow will have the same appearance and dimensions as the View, with the touch point
18899         * over the center of the View.
18900         * @param view A View. Any View in scope can be used.
18901         */
18902        public DragShadowBuilder(View view) {
18903            mView = new WeakReference<View>(view);
18904        }
18905
18906        /**
18907         * Construct a shadow builder object with no associated View.  This
18908         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
18909         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
18910         * to supply the drag shadow's dimensions and appearance without
18911         * reference to any View object. If they are not overridden, then the result is an
18912         * invisible drag shadow.
18913         */
18914        public DragShadowBuilder() {
18915            mView = new WeakReference<View>(null);
18916        }
18917
18918        /**
18919         * Returns the View object that had been passed to the
18920         * {@link #View.DragShadowBuilder(View)}
18921         * constructor.  If that View parameter was {@code null} or if the
18922         * {@link #View.DragShadowBuilder()}
18923         * constructor was used to instantiate the builder object, this method will return
18924         * null.
18925         *
18926         * @return The View object associate with this builder object.
18927         */
18928        @SuppressWarnings({"JavadocReference"})
18929        final public View getView() {
18930            return mView.get();
18931        }
18932
18933        /**
18934         * Provides the metrics for the shadow image. These include the dimensions of
18935         * the shadow image, and the point within that shadow that should
18936         * be centered under the touch location while dragging.
18937         * <p>
18938         * The default implementation sets the dimensions of the shadow to be the
18939         * same as the dimensions of the View itself and centers the shadow under
18940         * the touch point.
18941         * </p>
18942         *
18943         * @param shadowSize A {@link android.graphics.Point} containing the width and height
18944         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
18945         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
18946         * image.
18947         *
18948         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
18949         * shadow image that should be underneath the touch point during the drag and drop
18950         * operation. Your application must set {@link android.graphics.Point#x} to the
18951         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
18952         */
18953        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
18954            final View view = mView.get();
18955            if (view != null) {
18956                shadowSize.set(view.getWidth(), view.getHeight());
18957                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
18958            } else {
18959                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
18960            }
18961        }
18962
18963        /**
18964         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
18965         * based on the dimensions it received from the
18966         * {@link #onProvideShadowMetrics(Point, Point)} callback.
18967         *
18968         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
18969         */
18970        public void onDrawShadow(Canvas canvas) {
18971            final View view = mView.get();
18972            if (view != null) {
18973                view.draw(canvas);
18974            } else {
18975                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
18976            }
18977        }
18978    }
18979
18980    /**
18981     * Starts a drag and drop operation. When your application calls this method, it passes a
18982     * {@link android.view.View.DragShadowBuilder} object to the system. The
18983     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
18984     * to get metrics for the drag shadow, and then calls the object's
18985     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
18986     * <p>
18987     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
18988     *  drag events to all the View objects in your application that are currently visible. It does
18989     *  this either by calling the View object's drag listener (an implementation of
18990     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
18991     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
18992     *  Both are passed a {@link android.view.DragEvent} object that has a
18993     *  {@link android.view.DragEvent#getAction()} value of
18994     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
18995     * </p>
18996     * <p>
18997     * Your application can invoke startDrag() on any attached View object. The View object does not
18998     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
18999     * be related to the View the user selected for dragging.
19000     * </p>
19001     * @param data A {@link android.content.ClipData} object pointing to the data to be
19002     * transferred by the drag and drop operation.
19003     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
19004     * drag shadow.
19005     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
19006     * drop operation. This Object is put into every DragEvent object sent by the system during the
19007     * current drag.
19008     * <p>
19009     * myLocalState is a lightweight mechanism for the sending information from the dragged View
19010     * to the target Views. For example, it can contain flags that differentiate between a
19011     * a copy operation and a move operation.
19012     * </p>
19013     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
19014     * so the parameter should be set to 0.
19015     * @return {@code true} if the method completes successfully, or
19016     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
19017     * do a drag, and so no drag operation is in progress.
19018     */
19019    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
19020            Object myLocalState, int flags) {
19021        if (ViewDebug.DEBUG_DRAG) {
19022            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
19023        }
19024        boolean okay = false;
19025
19026        Point shadowSize = new Point();
19027        Point shadowTouchPoint = new Point();
19028        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
19029
19030        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
19031                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
19032            throw new IllegalStateException("Drag shadow dimensions must not be negative");
19033        }
19034
19035        if (ViewDebug.DEBUG_DRAG) {
19036            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
19037                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
19038        }
19039        Surface surface = new Surface();
19040        try {
19041            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
19042                    flags, shadowSize.x, shadowSize.y, surface);
19043            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
19044                    + " surface=" + surface);
19045            if (token != null) {
19046                Canvas canvas = surface.lockCanvas(null);
19047                try {
19048                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
19049                    shadowBuilder.onDrawShadow(canvas);
19050                } finally {
19051                    surface.unlockCanvasAndPost(canvas);
19052                }
19053
19054                final ViewRootImpl root = getViewRootImpl();
19055
19056                // Cache the local state object for delivery with DragEvents
19057                root.setLocalDragState(myLocalState);
19058
19059                // repurpose 'shadowSize' for the last touch point
19060                root.getLastTouchPoint(shadowSize);
19061
19062                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
19063                        shadowSize.x, shadowSize.y,
19064                        shadowTouchPoint.x, shadowTouchPoint.y, data);
19065                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
19066
19067                // Off and running!  Release our local surface instance; the drag
19068                // shadow surface is now managed by the system process.
19069                surface.release();
19070            }
19071        } catch (Exception e) {
19072            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
19073            surface.destroy();
19074        }
19075
19076        return okay;
19077    }
19078
19079    /**
19080     * Handles drag events sent by the system following a call to
19081     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
19082     *<p>
19083     * When the system calls this method, it passes a
19084     * {@link android.view.DragEvent} object. A call to
19085     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
19086     * in DragEvent. The method uses these to determine what is happening in the drag and drop
19087     * operation.
19088     * @param event The {@link android.view.DragEvent} sent by the system.
19089     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
19090     * in DragEvent, indicating the type of drag event represented by this object.
19091     * @return {@code true} if the method was successful, otherwise {@code false}.
19092     * <p>
19093     *  The method should return {@code true} in response to an action type of
19094     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
19095     *  operation.
19096     * </p>
19097     * <p>
19098     *  The method should also return {@code true} in response to an action type of
19099     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
19100     *  {@code false} if it didn't.
19101     * </p>
19102     */
19103    public boolean onDragEvent(DragEvent event) {
19104        return false;
19105    }
19106
19107    /**
19108     * Detects if this View is enabled and has a drag event listener.
19109     * If both are true, then it calls the drag event listener with the
19110     * {@link android.view.DragEvent} it received. If the drag event listener returns
19111     * {@code true}, then dispatchDragEvent() returns {@code true}.
19112     * <p>
19113     * For all other cases, the method calls the
19114     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
19115     * method and returns its result.
19116     * </p>
19117     * <p>
19118     * This ensures that a drag event is always consumed, even if the View does not have a drag
19119     * event listener. However, if the View has a listener and the listener returns true, then
19120     * onDragEvent() is not called.
19121     * </p>
19122     */
19123    public boolean dispatchDragEvent(DragEvent event) {
19124        ListenerInfo li = mListenerInfo;
19125        //noinspection SimplifiableIfStatement
19126        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
19127                && li.mOnDragListener.onDrag(this, event)) {
19128            return true;
19129        }
19130        return onDragEvent(event);
19131    }
19132
19133    boolean canAcceptDrag() {
19134        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
19135    }
19136
19137    /**
19138     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
19139     * it is ever exposed at all.
19140     * @hide
19141     */
19142    public void onCloseSystemDialogs(String reason) {
19143    }
19144
19145    /**
19146     * Given a Drawable whose bounds have been set to draw into this view,
19147     * update a Region being computed for
19148     * {@link #gatherTransparentRegion(android.graphics.Region)} so
19149     * that any non-transparent parts of the Drawable are removed from the
19150     * given transparent region.
19151     *
19152     * @param dr The Drawable whose transparency is to be applied to the region.
19153     * @param region A Region holding the current transparency information,
19154     * where any parts of the region that are set are considered to be
19155     * transparent.  On return, this region will be modified to have the
19156     * transparency information reduced by the corresponding parts of the
19157     * Drawable that are not transparent.
19158     * {@hide}
19159     */
19160    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
19161        if (DBG) {
19162            Log.i("View", "Getting transparent region for: " + this);
19163        }
19164        final Region r = dr.getTransparentRegion();
19165        final Rect db = dr.getBounds();
19166        final AttachInfo attachInfo = mAttachInfo;
19167        if (r != null && attachInfo != null) {
19168            final int w = getRight()-getLeft();
19169            final int h = getBottom()-getTop();
19170            if (db.left > 0) {
19171                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
19172                r.op(0, 0, db.left, h, Region.Op.UNION);
19173            }
19174            if (db.right < w) {
19175                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
19176                r.op(db.right, 0, w, h, Region.Op.UNION);
19177            }
19178            if (db.top > 0) {
19179                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
19180                r.op(0, 0, w, db.top, Region.Op.UNION);
19181            }
19182            if (db.bottom < h) {
19183                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
19184                r.op(0, db.bottom, w, h, Region.Op.UNION);
19185            }
19186            final int[] location = attachInfo.mTransparentLocation;
19187            getLocationInWindow(location);
19188            r.translate(location[0], location[1]);
19189            region.op(r, Region.Op.INTERSECT);
19190        } else {
19191            region.op(db, Region.Op.DIFFERENCE);
19192        }
19193    }
19194
19195    private void checkForLongClick(int delayOffset) {
19196        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
19197            mHasPerformedLongPress = false;
19198
19199            if (mPendingCheckForLongPress == null) {
19200                mPendingCheckForLongPress = new CheckForLongPress();
19201            }
19202            mPendingCheckForLongPress.rememberWindowAttachCount();
19203            postDelayed(mPendingCheckForLongPress,
19204                    ViewConfiguration.getLongPressTimeout() - delayOffset);
19205        }
19206    }
19207
19208    /**
19209     * Inflate a view from an XML resource.  This convenience method wraps the {@link
19210     * LayoutInflater} class, which provides a full range of options for view inflation.
19211     *
19212     * @param context The Context object for your activity or application.
19213     * @param resource The resource ID to inflate
19214     * @param root A view group that will be the parent.  Used to properly inflate the
19215     * layout_* parameters.
19216     * @see LayoutInflater
19217     */
19218    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
19219        LayoutInflater factory = LayoutInflater.from(context);
19220        return factory.inflate(resource, root);
19221    }
19222
19223    /**
19224     * Scroll the view with standard behavior for scrolling beyond the normal
19225     * content boundaries. Views that call this method should override
19226     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
19227     * results of an over-scroll operation.
19228     *
19229     * Views can use this method to handle any touch or fling-based scrolling.
19230     *
19231     * @param deltaX Change in X in pixels
19232     * @param deltaY Change in Y in pixels
19233     * @param scrollX Current X scroll value in pixels before applying deltaX
19234     * @param scrollY Current Y scroll value in pixels before applying deltaY
19235     * @param scrollRangeX Maximum content scroll range along the X axis
19236     * @param scrollRangeY Maximum content scroll range along the Y axis
19237     * @param maxOverScrollX Number of pixels to overscroll by in either direction
19238     *          along the X axis.
19239     * @param maxOverScrollY Number of pixels to overscroll by in either direction
19240     *          along the Y axis.
19241     * @param isTouchEvent true if this scroll operation is the result of a touch event.
19242     * @return true if scrolling was clamped to an over-scroll boundary along either
19243     *          axis, false otherwise.
19244     */
19245    @SuppressWarnings({"UnusedParameters"})
19246    protected boolean overScrollBy(int deltaX, int deltaY,
19247            int scrollX, int scrollY,
19248            int scrollRangeX, int scrollRangeY,
19249            int maxOverScrollX, int maxOverScrollY,
19250            boolean isTouchEvent) {
19251        final int overScrollMode = mOverScrollMode;
19252        final boolean canScrollHorizontal =
19253                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
19254        final boolean canScrollVertical =
19255                computeVerticalScrollRange() > computeVerticalScrollExtent();
19256        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
19257                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
19258        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
19259                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
19260
19261        int newScrollX = scrollX + deltaX;
19262        if (!overScrollHorizontal) {
19263            maxOverScrollX = 0;
19264        }
19265
19266        int newScrollY = scrollY + deltaY;
19267        if (!overScrollVertical) {
19268            maxOverScrollY = 0;
19269        }
19270
19271        // Clamp values if at the limits and record
19272        final int left = -maxOverScrollX;
19273        final int right = maxOverScrollX + scrollRangeX;
19274        final int top = -maxOverScrollY;
19275        final int bottom = maxOverScrollY + scrollRangeY;
19276
19277        boolean clampedX = false;
19278        if (newScrollX > right) {
19279            newScrollX = right;
19280            clampedX = true;
19281        } else if (newScrollX < left) {
19282            newScrollX = left;
19283            clampedX = true;
19284        }
19285
19286        boolean clampedY = false;
19287        if (newScrollY > bottom) {
19288            newScrollY = bottom;
19289            clampedY = true;
19290        } else if (newScrollY < top) {
19291            newScrollY = top;
19292            clampedY = true;
19293        }
19294
19295        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
19296
19297        return clampedX || clampedY;
19298    }
19299
19300    /**
19301     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
19302     * respond to the results of an over-scroll operation.
19303     *
19304     * @param scrollX New X scroll value in pixels
19305     * @param scrollY New Y scroll value in pixels
19306     * @param clampedX True if scrollX was clamped to an over-scroll boundary
19307     * @param clampedY True if scrollY was clamped to an over-scroll boundary
19308     */
19309    protected void onOverScrolled(int scrollX, int scrollY,
19310            boolean clampedX, boolean clampedY) {
19311        // Intentionally empty.
19312    }
19313
19314    /**
19315     * Returns the over-scroll mode for this view. The result will be
19316     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19317     * (allow over-scrolling only if the view content is larger than the container),
19318     * or {@link #OVER_SCROLL_NEVER}.
19319     *
19320     * @return This view's over-scroll mode.
19321     */
19322    public int getOverScrollMode() {
19323        return mOverScrollMode;
19324    }
19325
19326    /**
19327     * Set the over-scroll mode for this view. Valid over-scroll modes are
19328     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19329     * (allow over-scrolling only if the view content is larger than the container),
19330     * or {@link #OVER_SCROLL_NEVER}.
19331     *
19332     * Setting the over-scroll mode of a view will have an effect only if the
19333     * view is capable of scrolling.
19334     *
19335     * @param overScrollMode The new over-scroll mode for this view.
19336     */
19337    public void setOverScrollMode(int overScrollMode) {
19338        if (overScrollMode != OVER_SCROLL_ALWAYS &&
19339                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
19340                overScrollMode != OVER_SCROLL_NEVER) {
19341            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
19342        }
19343        mOverScrollMode = overScrollMode;
19344    }
19345
19346    /**
19347     * Enable or disable nested scrolling for this view.
19348     *
19349     * <p>If this property is set to true the view will be permitted to initiate nested
19350     * scrolling operations with a compatible parent view in the current hierarchy. If this
19351     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
19352     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
19353     * the nested scroll.</p>
19354     *
19355     * @param enabled true to enable nested scrolling, false to disable
19356     *
19357     * @see #isNestedScrollingEnabled()
19358     */
19359    public void setNestedScrollingEnabled(boolean enabled) {
19360        if (enabled) {
19361            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
19362        } else {
19363            stopNestedScroll();
19364            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
19365        }
19366    }
19367
19368    /**
19369     * Returns true if nested scrolling is enabled for this view.
19370     *
19371     * <p>If nested scrolling is enabled and this View class implementation supports it,
19372     * this view will act as a nested scrolling child view when applicable, forwarding data
19373     * about the scroll operation in progress to a compatible and cooperating nested scrolling
19374     * parent.</p>
19375     *
19376     * @return true if nested scrolling is enabled
19377     *
19378     * @see #setNestedScrollingEnabled(boolean)
19379     */
19380    public boolean isNestedScrollingEnabled() {
19381        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
19382                PFLAG3_NESTED_SCROLLING_ENABLED;
19383    }
19384
19385    /**
19386     * Begin a nestable scroll operation along the given axes.
19387     *
19388     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
19389     *
19390     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
19391     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
19392     * In the case of touch scrolling the nested scroll will be terminated automatically in
19393     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
19394     * In the event of programmatic scrolling the caller must explicitly call
19395     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
19396     *
19397     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
19398     * If it returns false the caller may ignore the rest of this contract until the next scroll.
19399     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
19400     *
19401     * <p>At each incremental step of the scroll the caller should invoke
19402     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
19403     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
19404     * parent at least partially consumed the scroll and the caller should adjust the amount it
19405     * scrolls by.</p>
19406     *
19407     * <p>After applying the remainder of the scroll delta the caller should invoke
19408     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
19409     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
19410     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
19411     * </p>
19412     *
19413     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
19414     *             {@link #SCROLL_AXIS_VERTICAL}.
19415     * @return true if a cooperative parent was found and nested scrolling has been enabled for
19416     *         the current gesture.
19417     *
19418     * @see #stopNestedScroll()
19419     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19420     * @see #dispatchNestedScroll(int, int, int, int, int[])
19421     */
19422    public boolean startNestedScroll(int axes) {
19423        if (hasNestedScrollingParent()) {
19424            // Already in progress
19425            return true;
19426        }
19427        if (isNestedScrollingEnabled()) {
19428            ViewParent p = getParent();
19429            View child = this;
19430            while (p != null) {
19431                try {
19432                    if (p.onStartNestedScroll(child, this, axes)) {
19433                        mNestedScrollingParent = p;
19434                        p.onNestedScrollAccepted(child, this, axes);
19435                        return true;
19436                    }
19437                } catch (AbstractMethodError e) {
19438                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
19439                            "method onStartNestedScroll", e);
19440                    // Allow the search upward to continue
19441                }
19442                if (p instanceof View) {
19443                    child = (View) p;
19444                }
19445                p = p.getParent();
19446            }
19447        }
19448        return false;
19449    }
19450
19451    /**
19452     * Stop a nested scroll in progress.
19453     *
19454     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
19455     *
19456     * @see #startNestedScroll(int)
19457     */
19458    public void stopNestedScroll() {
19459        if (mNestedScrollingParent != null) {
19460            mNestedScrollingParent.onStopNestedScroll(this);
19461            mNestedScrollingParent = null;
19462        }
19463    }
19464
19465    /**
19466     * Returns true if this view has a nested scrolling parent.
19467     *
19468     * <p>The presence of a nested scrolling parent indicates that this view has initiated
19469     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
19470     *
19471     * @return whether this view has a nested scrolling parent
19472     */
19473    public boolean hasNestedScrollingParent() {
19474        return mNestedScrollingParent != null;
19475    }
19476
19477    /**
19478     * Dispatch one step of a nested scroll in progress.
19479     *
19480     * <p>Implementations of views that support nested scrolling should call this to report
19481     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
19482     * is not currently in progress or nested scrolling is not
19483     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
19484     *
19485     * <p>Compatible View implementations should also call
19486     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
19487     * consuming a component of the scroll event themselves.</p>
19488     *
19489     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
19490     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
19491     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
19492     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
19493     * @param offsetInWindow Optional. If not null, on return this will contain the offset
19494     *                       in local view coordinates of this view from before this operation
19495     *                       to after it completes. View implementations may use this to adjust
19496     *                       expected input coordinate tracking.
19497     * @return true if the event was dispatched, false if it could not be dispatched.
19498     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19499     */
19500    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
19501            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
19502        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19503            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
19504                int startX = 0;
19505                int startY = 0;
19506                if (offsetInWindow != null) {
19507                    getLocationInWindow(offsetInWindow);
19508                    startX = offsetInWindow[0];
19509                    startY = offsetInWindow[1];
19510                }
19511
19512                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
19513                        dxUnconsumed, dyUnconsumed);
19514
19515                if (offsetInWindow != null) {
19516                    getLocationInWindow(offsetInWindow);
19517                    offsetInWindow[0] -= startX;
19518                    offsetInWindow[1] -= startY;
19519                }
19520                return true;
19521            } else if (offsetInWindow != null) {
19522                // No motion, no dispatch. Keep offsetInWindow up to date.
19523                offsetInWindow[0] = 0;
19524                offsetInWindow[1] = 0;
19525            }
19526        }
19527        return false;
19528    }
19529
19530    /**
19531     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
19532     *
19533     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
19534     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
19535     * scrolling operation to consume some or all of the scroll operation before the child view
19536     * consumes it.</p>
19537     *
19538     * @param dx Horizontal scroll distance in pixels
19539     * @param dy Vertical scroll distance in pixels
19540     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
19541     *                 and consumed[1] the consumed dy.
19542     * @param offsetInWindow Optional. If not null, on return this will contain the offset
19543     *                       in local view coordinates of this view from before this operation
19544     *                       to after it completes. View implementations may use this to adjust
19545     *                       expected input coordinate tracking.
19546     * @return true if the parent consumed some or all of the scroll delta
19547     * @see #dispatchNestedScroll(int, int, int, int, int[])
19548     */
19549    public boolean dispatchNestedPreScroll(int dx, int dy,
19550            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
19551        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19552            if (dx != 0 || dy != 0) {
19553                int startX = 0;
19554                int startY = 0;
19555                if (offsetInWindow != null) {
19556                    getLocationInWindow(offsetInWindow);
19557                    startX = offsetInWindow[0];
19558                    startY = offsetInWindow[1];
19559                }
19560
19561                if (consumed == null) {
19562                    if (mTempNestedScrollConsumed == null) {
19563                        mTempNestedScrollConsumed = new int[2];
19564                    }
19565                    consumed = mTempNestedScrollConsumed;
19566                }
19567                consumed[0] = 0;
19568                consumed[1] = 0;
19569                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
19570
19571                if (offsetInWindow != null) {
19572                    getLocationInWindow(offsetInWindow);
19573                    offsetInWindow[0] -= startX;
19574                    offsetInWindow[1] -= startY;
19575                }
19576                return consumed[0] != 0 || consumed[1] != 0;
19577            } else if (offsetInWindow != null) {
19578                offsetInWindow[0] = 0;
19579                offsetInWindow[1] = 0;
19580            }
19581        }
19582        return false;
19583    }
19584
19585    /**
19586     * Dispatch a fling to a nested scrolling parent.
19587     *
19588     * <p>This method should be used to indicate that a nested scrolling child has detected
19589     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
19590     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
19591     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
19592     * along a scrollable axis.</p>
19593     *
19594     * <p>If a nested scrolling child view would normally fling but it is at the edge of
19595     * its own content, it can use this method to delegate the fling to its nested scrolling
19596     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
19597     *
19598     * @param velocityX Horizontal fling velocity in pixels per second
19599     * @param velocityY Vertical fling velocity in pixels per second
19600     * @param consumed true if the child consumed the fling, false otherwise
19601     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
19602     */
19603    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
19604        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19605            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
19606        }
19607        return false;
19608    }
19609
19610    /**
19611     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
19612     *
19613     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
19614     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
19615     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
19616     * before the child view consumes it. If this method returns <code>true</code>, a nested
19617     * parent view consumed the fling and this view should not scroll as a result.</p>
19618     *
19619     * <p>For a better user experience, only one view in a nested scrolling chain should consume
19620     * the fling at a time. If a parent view consumed the fling this method will return false.
19621     * Custom view implementations should account for this in two ways:</p>
19622     *
19623     * <ul>
19624     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
19625     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
19626     *     position regardless.</li>
19627     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
19628     *     even to settle back to a valid idle position.</li>
19629     * </ul>
19630     *
19631     * <p>Views should also not offer fling velocities to nested parent views along an axis
19632     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
19633     * should not offer a horizontal fling velocity to its parents since scrolling along that
19634     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
19635     *
19636     * @param velocityX Horizontal fling velocity in pixels per second
19637     * @param velocityY Vertical fling velocity in pixels per second
19638     * @return true if a nested scrolling parent consumed the fling
19639     */
19640    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
19641        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19642            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
19643        }
19644        return false;
19645    }
19646
19647    /**
19648     * Gets a scale factor that determines the distance the view should scroll
19649     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
19650     * @return The vertical scroll scale factor.
19651     * @hide
19652     */
19653    protected float getVerticalScrollFactor() {
19654        if (mVerticalScrollFactor == 0) {
19655            TypedValue outValue = new TypedValue();
19656            if (!mContext.getTheme().resolveAttribute(
19657                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
19658                throw new IllegalStateException(
19659                        "Expected theme to define listPreferredItemHeight.");
19660            }
19661            mVerticalScrollFactor = outValue.getDimension(
19662                    mContext.getResources().getDisplayMetrics());
19663        }
19664        return mVerticalScrollFactor;
19665    }
19666
19667    /**
19668     * Gets a scale factor that determines the distance the view should scroll
19669     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
19670     * @return The horizontal scroll scale factor.
19671     * @hide
19672     */
19673    protected float getHorizontalScrollFactor() {
19674        // TODO: Should use something else.
19675        return getVerticalScrollFactor();
19676    }
19677
19678    /**
19679     * Return the value specifying the text direction or policy that was set with
19680     * {@link #setTextDirection(int)}.
19681     *
19682     * @return the defined text direction. It can be one of:
19683     *
19684     * {@link #TEXT_DIRECTION_INHERIT},
19685     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19686     * {@link #TEXT_DIRECTION_ANY_RTL},
19687     * {@link #TEXT_DIRECTION_LTR},
19688     * {@link #TEXT_DIRECTION_RTL},
19689     * {@link #TEXT_DIRECTION_LOCALE},
19690     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19691     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
19692     *
19693     * @attr ref android.R.styleable#View_textDirection
19694     *
19695     * @hide
19696     */
19697    @ViewDebug.ExportedProperty(category = "text", mapping = {
19698            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19699            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19700            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19701            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19702            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19703            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
19704            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
19705            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
19706    })
19707    public int getRawTextDirection() {
19708        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
19709    }
19710
19711    /**
19712     * Set the text direction.
19713     *
19714     * @param textDirection the direction to set. Should be one of:
19715     *
19716     * {@link #TEXT_DIRECTION_INHERIT},
19717     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19718     * {@link #TEXT_DIRECTION_ANY_RTL},
19719     * {@link #TEXT_DIRECTION_LTR},
19720     * {@link #TEXT_DIRECTION_RTL},
19721     * {@link #TEXT_DIRECTION_LOCALE}
19722     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19723     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
19724     *
19725     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
19726     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
19727     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
19728     *
19729     * @attr ref android.R.styleable#View_textDirection
19730     */
19731    public void setTextDirection(int textDirection) {
19732        if (getRawTextDirection() != textDirection) {
19733            // Reset the current text direction and the resolved one
19734            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
19735            resetResolvedTextDirection();
19736            // Set the new text direction
19737            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
19738            // Do resolution
19739            resolveTextDirection();
19740            // Notify change
19741            onRtlPropertiesChanged(getLayoutDirection());
19742            // Refresh
19743            requestLayout();
19744            invalidate(true);
19745        }
19746    }
19747
19748    /**
19749     * Return the resolved text direction.
19750     *
19751     * @return the resolved text direction. Returns one of:
19752     *
19753     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19754     * {@link #TEXT_DIRECTION_ANY_RTL},
19755     * {@link #TEXT_DIRECTION_LTR},
19756     * {@link #TEXT_DIRECTION_RTL},
19757     * {@link #TEXT_DIRECTION_LOCALE},
19758     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19759     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
19760     *
19761     * @attr ref android.R.styleable#View_textDirection
19762     */
19763    @ViewDebug.ExportedProperty(category = "text", mapping = {
19764            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19765            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19766            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19767            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19768            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19769            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
19770            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
19771            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
19772    })
19773    public int getTextDirection() {
19774        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
19775    }
19776
19777    /**
19778     * Resolve the text direction.
19779     *
19780     * @return true if resolution has been done, false otherwise.
19781     *
19782     * @hide
19783     */
19784    public boolean resolveTextDirection() {
19785        // Reset any previous text direction resolution
19786        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19787
19788        if (hasRtlSupport()) {
19789            // Set resolved text direction flag depending on text direction flag
19790            final int textDirection = getRawTextDirection();
19791            switch(textDirection) {
19792                case TEXT_DIRECTION_INHERIT:
19793                    if (!canResolveTextDirection()) {
19794                        // We cannot do the resolution if there is no parent, so use the default one
19795                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19796                        // Resolution will need to happen again later
19797                        return false;
19798                    }
19799
19800                    // Parent has not yet resolved, so we still return the default
19801                    try {
19802                        if (!mParent.isTextDirectionResolved()) {
19803                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19804                            // Resolution will need to happen again later
19805                            return false;
19806                        }
19807                    } catch (AbstractMethodError e) {
19808                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19809                                " does not fully implement ViewParent", e);
19810                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
19811                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19812                        return true;
19813                    }
19814
19815                    // Set current resolved direction to the same value as the parent's one
19816                    int parentResolvedDirection;
19817                    try {
19818                        parentResolvedDirection = mParent.getTextDirection();
19819                    } catch (AbstractMethodError e) {
19820                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19821                                " does not fully implement ViewParent", e);
19822                        parentResolvedDirection = TEXT_DIRECTION_LTR;
19823                    }
19824                    switch (parentResolvedDirection) {
19825                        case TEXT_DIRECTION_FIRST_STRONG:
19826                        case TEXT_DIRECTION_ANY_RTL:
19827                        case TEXT_DIRECTION_LTR:
19828                        case TEXT_DIRECTION_RTL:
19829                        case TEXT_DIRECTION_LOCALE:
19830                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
19831                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
19832                            mPrivateFlags2 |=
19833                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19834                            break;
19835                        default:
19836                            // Default resolved direction is "first strong" heuristic
19837                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19838                    }
19839                    break;
19840                case TEXT_DIRECTION_FIRST_STRONG:
19841                case TEXT_DIRECTION_ANY_RTL:
19842                case TEXT_DIRECTION_LTR:
19843                case TEXT_DIRECTION_RTL:
19844                case TEXT_DIRECTION_LOCALE:
19845                case TEXT_DIRECTION_FIRST_STRONG_LTR:
19846                case TEXT_DIRECTION_FIRST_STRONG_RTL:
19847                    // Resolved direction is the same as text direction
19848                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
19849                    break;
19850                default:
19851                    // Default resolved direction is "first strong" heuristic
19852                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19853            }
19854        } else {
19855            // Default resolved direction is "first strong" heuristic
19856            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19857        }
19858
19859        // Set to resolved
19860        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
19861        return true;
19862    }
19863
19864    /**
19865     * Check if text direction resolution can be done.
19866     *
19867     * @return true if text direction resolution can be done otherwise return false.
19868     */
19869    public boolean canResolveTextDirection() {
19870        switch (getRawTextDirection()) {
19871            case TEXT_DIRECTION_INHERIT:
19872                if (mParent != null) {
19873                    try {
19874                        return mParent.canResolveTextDirection();
19875                    } catch (AbstractMethodError e) {
19876                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19877                                " does not fully implement ViewParent", e);
19878                    }
19879                }
19880                return false;
19881
19882            default:
19883                return true;
19884        }
19885    }
19886
19887    /**
19888     * Reset resolved text direction. Text direction will be resolved during a call to
19889     * {@link #onMeasure(int, int)}.
19890     *
19891     * @hide
19892     */
19893    public void resetResolvedTextDirection() {
19894        // Reset any previous text direction resolution
19895        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19896        // Set to default value
19897        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19898    }
19899
19900    /**
19901     * @return true if text direction is inherited.
19902     *
19903     * @hide
19904     */
19905    public boolean isTextDirectionInherited() {
19906        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
19907    }
19908
19909    /**
19910     * @return true if text direction is resolved.
19911     */
19912    public boolean isTextDirectionResolved() {
19913        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
19914    }
19915
19916    /**
19917     * Return the value specifying the text alignment or policy that was set with
19918     * {@link #setTextAlignment(int)}.
19919     *
19920     * @return the defined text alignment. It can be one of:
19921     *
19922     * {@link #TEXT_ALIGNMENT_INHERIT},
19923     * {@link #TEXT_ALIGNMENT_GRAVITY},
19924     * {@link #TEXT_ALIGNMENT_CENTER},
19925     * {@link #TEXT_ALIGNMENT_TEXT_START},
19926     * {@link #TEXT_ALIGNMENT_TEXT_END},
19927     * {@link #TEXT_ALIGNMENT_VIEW_START},
19928     * {@link #TEXT_ALIGNMENT_VIEW_END}
19929     *
19930     * @attr ref android.R.styleable#View_textAlignment
19931     *
19932     * @hide
19933     */
19934    @ViewDebug.ExportedProperty(category = "text", mapping = {
19935            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
19936            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
19937            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
19938            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
19939            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
19940            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
19941            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
19942    })
19943    @TextAlignment
19944    public int getRawTextAlignment() {
19945        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
19946    }
19947
19948    /**
19949     * Set the text alignment.
19950     *
19951     * @param textAlignment The text alignment to set. Should be one of
19952     *
19953     * {@link #TEXT_ALIGNMENT_INHERIT},
19954     * {@link #TEXT_ALIGNMENT_GRAVITY},
19955     * {@link #TEXT_ALIGNMENT_CENTER},
19956     * {@link #TEXT_ALIGNMENT_TEXT_START},
19957     * {@link #TEXT_ALIGNMENT_TEXT_END},
19958     * {@link #TEXT_ALIGNMENT_VIEW_START},
19959     * {@link #TEXT_ALIGNMENT_VIEW_END}
19960     *
19961     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
19962     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
19963     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
19964     *
19965     * @attr ref android.R.styleable#View_textAlignment
19966     */
19967    public void setTextAlignment(@TextAlignment int textAlignment) {
19968        if (textAlignment != getRawTextAlignment()) {
19969            // Reset the current and resolved text alignment
19970            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
19971            resetResolvedTextAlignment();
19972            // Set the new text alignment
19973            mPrivateFlags2 |=
19974                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
19975            // Do resolution
19976            resolveTextAlignment();
19977            // Notify change
19978            onRtlPropertiesChanged(getLayoutDirection());
19979            // Refresh
19980            requestLayout();
19981            invalidate(true);
19982        }
19983    }
19984
19985    /**
19986     * Return the resolved text alignment.
19987     *
19988     * @return the resolved text alignment. Returns one of:
19989     *
19990     * {@link #TEXT_ALIGNMENT_GRAVITY},
19991     * {@link #TEXT_ALIGNMENT_CENTER},
19992     * {@link #TEXT_ALIGNMENT_TEXT_START},
19993     * {@link #TEXT_ALIGNMENT_TEXT_END},
19994     * {@link #TEXT_ALIGNMENT_VIEW_START},
19995     * {@link #TEXT_ALIGNMENT_VIEW_END}
19996     *
19997     * @attr ref android.R.styleable#View_textAlignment
19998     */
19999    @ViewDebug.ExportedProperty(category = "text", mapping = {
20000            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
20001            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
20002            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
20003            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
20004            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
20005            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
20006            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
20007    })
20008    @TextAlignment
20009    public int getTextAlignment() {
20010        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
20011                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
20012    }
20013
20014    /**
20015     * Resolve the text alignment.
20016     *
20017     * @return true if resolution has been done, false otherwise.
20018     *
20019     * @hide
20020     */
20021    public boolean resolveTextAlignment() {
20022        // Reset any previous text alignment resolution
20023        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20024
20025        if (hasRtlSupport()) {
20026            // Set resolved text alignment flag depending on text alignment flag
20027            final int textAlignment = getRawTextAlignment();
20028            switch (textAlignment) {
20029                case TEXT_ALIGNMENT_INHERIT:
20030                    // Check if we can resolve the text alignment
20031                    if (!canResolveTextAlignment()) {
20032                        // We cannot do the resolution if there is no parent so use the default
20033                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20034                        // Resolution will need to happen again later
20035                        return false;
20036                    }
20037
20038                    // Parent has not yet resolved, so we still return the default
20039                    try {
20040                        if (!mParent.isTextAlignmentResolved()) {
20041                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20042                            // Resolution will need to happen again later
20043                            return false;
20044                        }
20045                    } catch (AbstractMethodError e) {
20046                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20047                                " does not fully implement ViewParent", e);
20048                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
20049                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20050                        return true;
20051                    }
20052
20053                    int parentResolvedTextAlignment;
20054                    try {
20055                        parentResolvedTextAlignment = mParent.getTextAlignment();
20056                    } catch (AbstractMethodError e) {
20057                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20058                                " does not fully implement ViewParent", e);
20059                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
20060                    }
20061                    switch (parentResolvedTextAlignment) {
20062                        case TEXT_ALIGNMENT_GRAVITY:
20063                        case TEXT_ALIGNMENT_TEXT_START:
20064                        case TEXT_ALIGNMENT_TEXT_END:
20065                        case TEXT_ALIGNMENT_CENTER:
20066                        case TEXT_ALIGNMENT_VIEW_START:
20067                        case TEXT_ALIGNMENT_VIEW_END:
20068                            // Resolved text alignment is the same as the parent resolved
20069                            // text alignment
20070                            mPrivateFlags2 |=
20071                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20072                            break;
20073                        default:
20074                            // Use default resolved text alignment
20075                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20076                    }
20077                    break;
20078                case TEXT_ALIGNMENT_GRAVITY:
20079                case TEXT_ALIGNMENT_TEXT_START:
20080                case TEXT_ALIGNMENT_TEXT_END:
20081                case TEXT_ALIGNMENT_CENTER:
20082                case TEXT_ALIGNMENT_VIEW_START:
20083                case TEXT_ALIGNMENT_VIEW_END:
20084                    // Resolved text alignment is the same as text alignment
20085                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20086                    break;
20087                default:
20088                    // Use default resolved text alignment
20089                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20090            }
20091        } else {
20092            // Use default resolved text alignment
20093            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20094        }
20095
20096        // Set the resolved
20097        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20098        return true;
20099    }
20100
20101    /**
20102     * Check if text alignment resolution can be done.
20103     *
20104     * @return true if text alignment resolution can be done otherwise return false.
20105     */
20106    public boolean canResolveTextAlignment() {
20107        switch (getRawTextAlignment()) {
20108            case TEXT_DIRECTION_INHERIT:
20109                if (mParent != null) {
20110                    try {
20111                        return mParent.canResolveTextAlignment();
20112                    } catch (AbstractMethodError e) {
20113                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20114                                " does not fully implement ViewParent", e);
20115                    }
20116                }
20117                return false;
20118
20119            default:
20120                return true;
20121        }
20122    }
20123
20124    /**
20125     * Reset resolved text alignment. Text alignment will be resolved during a call to
20126     * {@link #onMeasure(int, int)}.
20127     *
20128     * @hide
20129     */
20130    public void resetResolvedTextAlignment() {
20131        // Reset any previous text alignment resolution
20132        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20133        // Set to default
20134        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20135    }
20136
20137    /**
20138     * @return true if text alignment is inherited.
20139     *
20140     * @hide
20141     */
20142    public boolean isTextAlignmentInherited() {
20143        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
20144    }
20145
20146    /**
20147     * @return true if text alignment is resolved.
20148     */
20149    public boolean isTextAlignmentResolved() {
20150        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20151    }
20152
20153    /**
20154     * Generate a value suitable for use in {@link #setId(int)}.
20155     * This value will not collide with ID values generated at build time by aapt for R.id.
20156     *
20157     * @return a generated ID value
20158     */
20159    public static int generateViewId() {
20160        for (;;) {
20161            final int result = sNextGeneratedId.get();
20162            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
20163            int newValue = result + 1;
20164            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
20165            if (sNextGeneratedId.compareAndSet(result, newValue)) {
20166                return result;
20167            }
20168        }
20169    }
20170
20171    /**
20172     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
20173     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
20174     *                           a normal View or a ViewGroup with
20175     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
20176     * @hide
20177     */
20178    public void captureTransitioningViews(List<View> transitioningViews) {
20179        if (getVisibility() == View.VISIBLE) {
20180            transitioningViews.add(this);
20181        }
20182    }
20183
20184    /**
20185     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
20186     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
20187     * @hide
20188     */
20189    public void findNamedViews(Map<String, View> namedElements) {
20190        if (getVisibility() == VISIBLE || mGhostView != null) {
20191            String transitionName = getTransitionName();
20192            if (transitionName != null) {
20193                namedElements.put(transitionName, this);
20194            }
20195        }
20196    }
20197
20198    //
20199    // Properties
20200    //
20201    /**
20202     * A Property wrapper around the <code>alpha</code> functionality handled by the
20203     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
20204     */
20205    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
20206        @Override
20207        public void setValue(View object, float value) {
20208            object.setAlpha(value);
20209        }
20210
20211        @Override
20212        public Float get(View object) {
20213            return object.getAlpha();
20214        }
20215    };
20216
20217    /**
20218     * A Property wrapper around the <code>translationX</code> functionality handled by the
20219     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
20220     */
20221    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
20222        @Override
20223        public void setValue(View object, float value) {
20224            object.setTranslationX(value);
20225        }
20226
20227                @Override
20228        public Float get(View object) {
20229            return object.getTranslationX();
20230        }
20231    };
20232
20233    /**
20234     * A Property wrapper around the <code>translationY</code> functionality handled by the
20235     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
20236     */
20237    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
20238        @Override
20239        public void setValue(View object, float value) {
20240            object.setTranslationY(value);
20241        }
20242
20243        @Override
20244        public Float get(View object) {
20245            return object.getTranslationY();
20246        }
20247    };
20248
20249    /**
20250     * A Property wrapper around the <code>translationZ</code> functionality handled by the
20251     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
20252     */
20253    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
20254        @Override
20255        public void setValue(View object, float value) {
20256            object.setTranslationZ(value);
20257        }
20258
20259        @Override
20260        public Float get(View object) {
20261            return object.getTranslationZ();
20262        }
20263    };
20264
20265    /**
20266     * A Property wrapper around the <code>x</code> functionality handled by the
20267     * {@link View#setX(float)} and {@link View#getX()} methods.
20268     */
20269    public static final Property<View, Float> X = new FloatProperty<View>("x") {
20270        @Override
20271        public void setValue(View object, float value) {
20272            object.setX(value);
20273        }
20274
20275        @Override
20276        public Float get(View object) {
20277            return object.getX();
20278        }
20279    };
20280
20281    /**
20282     * A Property wrapper around the <code>y</code> functionality handled by the
20283     * {@link View#setY(float)} and {@link View#getY()} methods.
20284     */
20285    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
20286        @Override
20287        public void setValue(View object, float value) {
20288            object.setY(value);
20289        }
20290
20291        @Override
20292        public Float get(View object) {
20293            return object.getY();
20294        }
20295    };
20296
20297    /**
20298     * A Property wrapper around the <code>z</code> functionality handled by the
20299     * {@link View#setZ(float)} and {@link View#getZ()} methods.
20300     */
20301    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
20302        @Override
20303        public void setValue(View object, float value) {
20304            object.setZ(value);
20305        }
20306
20307        @Override
20308        public Float get(View object) {
20309            return object.getZ();
20310        }
20311    };
20312
20313    /**
20314     * A Property wrapper around the <code>rotation</code> functionality handled by the
20315     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
20316     */
20317    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
20318        @Override
20319        public void setValue(View object, float value) {
20320            object.setRotation(value);
20321        }
20322
20323        @Override
20324        public Float get(View object) {
20325            return object.getRotation();
20326        }
20327    };
20328
20329    /**
20330     * A Property wrapper around the <code>rotationX</code> functionality handled by the
20331     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
20332     */
20333    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
20334        @Override
20335        public void setValue(View object, float value) {
20336            object.setRotationX(value);
20337        }
20338
20339        @Override
20340        public Float get(View object) {
20341            return object.getRotationX();
20342        }
20343    };
20344
20345    /**
20346     * A Property wrapper around the <code>rotationY</code> functionality handled by the
20347     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
20348     */
20349    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
20350        @Override
20351        public void setValue(View object, float value) {
20352            object.setRotationY(value);
20353        }
20354
20355        @Override
20356        public Float get(View object) {
20357            return object.getRotationY();
20358        }
20359    };
20360
20361    /**
20362     * A Property wrapper around the <code>scaleX</code> functionality handled by the
20363     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
20364     */
20365    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
20366        @Override
20367        public void setValue(View object, float value) {
20368            object.setScaleX(value);
20369        }
20370
20371        @Override
20372        public Float get(View object) {
20373            return object.getScaleX();
20374        }
20375    };
20376
20377    /**
20378     * A Property wrapper around the <code>scaleY</code> functionality handled by the
20379     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
20380     */
20381    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
20382        @Override
20383        public void setValue(View object, float value) {
20384            object.setScaleY(value);
20385        }
20386
20387        @Override
20388        public Float get(View object) {
20389            return object.getScaleY();
20390        }
20391    };
20392
20393    /**
20394     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
20395     * Each MeasureSpec represents a requirement for either the width or the height.
20396     * A MeasureSpec is comprised of a size and a mode. There are three possible
20397     * modes:
20398     * <dl>
20399     * <dt>UNSPECIFIED</dt>
20400     * <dd>
20401     * The parent has not imposed any constraint on the child. It can be whatever size
20402     * it wants.
20403     * </dd>
20404     *
20405     * <dt>EXACTLY</dt>
20406     * <dd>
20407     * The parent has determined an exact size for the child. The child is going to be
20408     * given those bounds regardless of how big it wants to be.
20409     * </dd>
20410     *
20411     * <dt>AT_MOST</dt>
20412     * <dd>
20413     * The child can be as large as it wants up to the specified size.
20414     * </dd>
20415     * </dl>
20416     *
20417     * MeasureSpecs are implemented as ints to reduce object allocation. This class
20418     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
20419     */
20420    public static class MeasureSpec {
20421        private static final int MODE_SHIFT = 30;
20422        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
20423
20424        /**
20425         * Measure specification mode: The parent has not imposed any constraint
20426         * on the child. It can be whatever size it wants.
20427         */
20428        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
20429
20430        /**
20431         * Measure specification mode: The parent has determined an exact size
20432         * for the child. The child is going to be given those bounds regardless
20433         * of how big it wants to be.
20434         */
20435        public static final int EXACTLY     = 1 << MODE_SHIFT;
20436
20437        /**
20438         * Measure specification mode: The child can be as large as it wants up
20439         * to the specified size.
20440         */
20441        public static final int AT_MOST     = 2 << MODE_SHIFT;
20442
20443        /**
20444         * Creates a measure specification based on the supplied size and mode.
20445         *
20446         * The mode must always be one of the following:
20447         * <ul>
20448         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
20449         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
20450         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
20451         * </ul>
20452         *
20453         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
20454         * implementation was such that the order of arguments did not matter
20455         * and overflow in either value could impact the resulting MeasureSpec.
20456         * {@link android.widget.RelativeLayout} was affected by this bug.
20457         * Apps targeting API levels greater than 17 will get the fixed, more strict
20458         * behavior.</p>
20459         *
20460         * @param size the size of the measure specification
20461         * @param mode the mode of the measure specification
20462         * @return the measure specification based on size and mode
20463         */
20464        public static int makeMeasureSpec(int size, int mode) {
20465            if (sUseBrokenMakeMeasureSpec) {
20466                return size + mode;
20467            } else {
20468                return (size & ~MODE_MASK) | (mode & MODE_MASK);
20469            }
20470        }
20471
20472        /**
20473         * Extracts the mode from the supplied measure specification.
20474         *
20475         * @param measureSpec the measure specification to extract the mode from
20476         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
20477         *         {@link android.view.View.MeasureSpec#AT_MOST} or
20478         *         {@link android.view.View.MeasureSpec#EXACTLY}
20479         */
20480        public static int getMode(int measureSpec) {
20481            return (measureSpec & MODE_MASK);
20482        }
20483
20484        /**
20485         * Extracts the size from the supplied measure specification.
20486         *
20487         * @param measureSpec the measure specification to extract the size from
20488         * @return the size in pixels defined in the supplied measure specification
20489         */
20490        public static int getSize(int measureSpec) {
20491            return (measureSpec & ~MODE_MASK);
20492        }
20493
20494        static int adjust(int measureSpec, int delta) {
20495            final int mode = getMode(measureSpec);
20496            int size = getSize(measureSpec);
20497            if (mode == UNSPECIFIED) {
20498                // No need to adjust size for UNSPECIFIED mode.
20499                return makeMeasureSpec(size, UNSPECIFIED);
20500            }
20501            size += delta;
20502            if (size < 0) {
20503                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
20504                        ") spec: " + toString(measureSpec) + " delta: " + delta);
20505                size = 0;
20506            }
20507            return makeMeasureSpec(size, mode);
20508        }
20509
20510        /**
20511         * Returns a String representation of the specified measure
20512         * specification.
20513         *
20514         * @param measureSpec the measure specification to convert to a String
20515         * @return a String with the following format: "MeasureSpec: MODE SIZE"
20516         */
20517        public static String toString(int measureSpec) {
20518            int mode = getMode(measureSpec);
20519            int size = getSize(measureSpec);
20520
20521            StringBuilder sb = new StringBuilder("MeasureSpec: ");
20522
20523            if (mode == UNSPECIFIED)
20524                sb.append("UNSPECIFIED ");
20525            else if (mode == EXACTLY)
20526                sb.append("EXACTLY ");
20527            else if (mode == AT_MOST)
20528                sb.append("AT_MOST ");
20529            else
20530                sb.append(mode).append(" ");
20531
20532            sb.append(size);
20533            return sb.toString();
20534        }
20535    }
20536
20537    private final class CheckForLongPress implements Runnable {
20538        private int mOriginalWindowAttachCount;
20539
20540        @Override
20541        public void run() {
20542            if (isPressed() && (mParent != null)
20543                    && mOriginalWindowAttachCount == mWindowAttachCount) {
20544                if (performLongClick()) {
20545                    mHasPerformedLongPress = true;
20546                }
20547            }
20548        }
20549
20550        public void rememberWindowAttachCount() {
20551            mOriginalWindowAttachCount = mWindowAttachCount;
20552        }
20553    }
20554
20555    private final class CheckForTap implements Runnable {
20556        public float x;
20557        public float y;
20558
20559        @Override
20560        public void run() {
20561            mPrivateFlags &= ~PFLAG_PREPRESSED;
20562            setPressed(true, x, y);
20563            checkForLongClick(ViewConfiguration.getTapTimeout());
20564        }
20565    }
20566
20567    private final class PerformClick implements Runnable {
20568        @Override
20569        public void run() {
20570            performClick();
20571        }
20572    }
20573
20574    /** @hide */
20575    public void hackTurnOffWindowResizeAnim(boolean off) {
20576        mAttachInfo.mTurnOffWindowResizeAnim = off;
20577    }
20578
20579    /**
20580     * This method returns a ViewPropertyAnimator object, which can be used to animate
20581     * specific properties on this View.
20582     *
20583     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
20584     */
20585    public ViewPropertyAnimator animate() {
20586        if (mAnimator == null) {
20587            mAnimator = new ViewPropertyAnimator(this);
20588        }
20589        return mAnimator;
20590    }
20591
20592    /**
20593     * Sets the name of the View to be used to identify Views in Transitions.
20594     * Names should be unique in the View hierarchy.
20595     *
20596     * @param transitionName The name of the View to uniquely identify it for Transitions.
20597     */
20598    public final void setTransitionName(String transitionName) {
20599        mTransitionName = transitionName;
20600    }
20601
20602    /**
20603     * Returns the name of the View to be used to identify Views in Transitions.
20604     * Names should be unique in the View hierarchy.
20605     *
20606     * <p>This returns null if the View has not been given a name.</p>
20607     *
20608     * @return The name used of the View to be used to identify Views in Transitions or null
20609     * if no name has been given.
20610     */
20611    @ViewDebug.ExportedProperty
20612    public String getTransitionName() {
20613        return mTransitionName;
20614    }
20615
20616    /**
20617     * Interface definition for a callback to be invoked when a hardware key event is
20618     * dispatched to this view. The callback will be invoked before the key event is
20619     * given to the view. This is only useful for hardware keyboards; a software input
20620     * method has no obligation to trigger this listener.
20621     */
20622    public interface OnKeyListener {
20623        /**
20624         * Called when a hardware key is dispatched to a view. This allows listeners to
20625         * get a chance to respond before the target view.
20626         * <p>Key presses in software keyboards will generally NOT trigger this method,
20627         * although some may elect to do so in some situations. Do not assume a
20628         * software input method has to be key-based; even if it is, it may use key presses
20629         * in a different way than you expect, so there is no way to reliably catch soft
20630         * input key presses.
20631         *
20632         * @param v The view the key has been dispatched to.
20633         * @param keyCode The code for the physical key that was pressed
20634         * @param event The KeyEvent object containing full information about
20635         *        the event.
20636         * @return True if the listener has consumed the event, false otherwise.
20637         */
20638        boolean onKey(View v, int keyCode, KeyEvent event);
20639    }
20640
20641    /**
20642     * Interface definition for a callback to be invoked when a touch event is
20643     * dispatched to this view. The callback will be invoked before the touch
20644     * event is given to the view.
20645     */
20646    public interface OnTouchListener {
20647        /**
20648         * Called when a touch event is dispatched to a view. This allows listeners to
20649         * get a chance to respond before the target view.
20650         *
20651         * @param v The view the touch event has been dispatched to.
20652         * @param event The MotionEvent object containing full information about
20653         *        the event.
20654         * @return True if the listener has consumed the event, false otherwise.
20655         */
20656        boolean onTouch(View v, MotionEvent event);
20657    }
20658
20659    /**
20660     * Interface definition for a callback to be invoked when a hover event is
20661     * dispatched to this view. The callback will be invoked before the hover
20662     * event is given to the view.
20663     */
20664    public interface OnHoverListener {
20665        /**
20666         * Called when a hover event is dispatched to a view. This allows listeners to
20667         * get a chance to respond before the target view.
20668         *
20669         * @param v The view the hover event has been dispatched to.
20670         * @param event The MotionEvent object containing full information about
20671         *        the event.
20672         * @return True if the listener has consumed the event, false otherwise.
20673         */
20674        boolean onHover(View v, MotionEvent event);
20675    }
20676
20677    /**
20678     * Interface definition for a callback to be invoked when a generic motion event is
20679     * dispatched to this view. The callback will be invoked before the generic motion
20680     * event is given to the view.
20681     */
20682    public interface OnGenericMotionListener {
20683        /**
20684         * Called when a generic motion event is dispatched to a view. This allows listeners to
20685         * get a chance to respond before the target view.
20686         *
20687         * @param v The view the generic motion event has been dispatched to.
20688         * @param event The MotionEvent object containing full information about
20689         *        the event.
20690         * @return True if the listener has consumed the event, false otherwise.
20691         */
20692        boolean onGenericMotion(View v, MotionEvent event);
20693    }
20694
20695    /**
20696     * Interface definition for a callback to be invoked when a view has been clicked and held.
20697     */
20698    public interface OnLongClickListener {
20699        /**
20700         * Called when a view has been clicked and held.
20701         *
20702         * @param v The view that was clicked and held.
20703         *
20704         * @return true if the callback consumed the long click, false otherwise.
20705         */
20706        boolean onLongClick(View v);
20707    }
20708
20709    /**
20710     * Interface definition for a callback to be invoked when a drag is being dispatched
20711     * to this view.  The callback will be invoked before the hosting view's own
20712     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
20713     * onDrag(event) behavior, it should return 'false' from this callback.
20714     *
20715     * <div class="special reference">
20716     * <h3>Developer Guides</h3>
20717     * <p>For a guide to implementing drag and drop features, read the
20718     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20719     * </div>
20720     */
20721    public interface OnDragListener {
20722        /**
20723         * Called when a drag event is dispatched to a view. This allows listeners
20724         * to get a chance to override base View behavior.
20725         *
20726         * @param v The View that received the drag event.
20727         * @param event The {@link android.view.DragEvent} object for the drag event.
20728         * @return {@code true} if the drag event was handled successfully, or {@code false}
20729         * if the drag event was not handled. Note that {@code false} will trigger the View
20730         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
20731         */
20732        boolean onDrag(View v, DragEvent event);
20733    }
20734
20735    /**
20736     * Interface definition for a callback to be invoked when the focus state of
20737     * a view changed.
20738     */
20739    public interface OnFocusChangeListener {
20740        /**
20741         * Called when the focus state of a view has changed.
20742         *
20743         * @param v The view whose state has changed.
20744         * @param hasFocus The new focus state of v.
20745         */
20746        void onFocusChange(View v, boolean hasFocus);
20747    }
20748
20749    /**
20750     * Interface definition for a callback to be invoked when a view is clicked.
20751     */
20752    public interface OnClickListener {
20753        /**
20754         * Called when a view has been clicked.
20755         *
20756         * @param v The view that was clicked.
20757         */
20758        void onClick(View v);
20759    }
20760
20761    /**
20762     * Interface definition for a callback to be invoked when the context menu
20763     * for this view is being built.
20764     */
20765    public interface OnCreateContextMenuListener {
20766        /**
20767         * Called when the context menu for this view is being built. It is not
20768         * safe to hold onto the menu after this method returns.
20769         *
20770         * @param menu The context menu that is being built
20771         * @param v The view for which the context menu is being built
20772         * @param menuInfo Extra information about the item for which the
20773         *            context menu should be shown. This information will vary
20774         *            depending on the class of v.
20775         */
20776        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
20777    }
20778
20779    /**
20780     * Interface definition for a callback to be invoked when the status bar changes
20781     * visibility.  This reports <strong>global</strong> changes to the system UI
20782     * state, not what the application is requesting.
20783     *
20784     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
20785     */
20786    public interface OnSystemUiVisibilityChangeListener {
20787        /**
20788         * Called when the status bar changes visibility because of a call to
20789         * {@link View#setSystemUiVisibility(int)}.
20790         *
20791         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20792         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
20793         * This tells you the <strong>global</strong> state of these UI visibility
20794         * flags, not what your app is currently applying.
20795         */
20796        public void onSystemUiVisibilityChange(int visibility);
20797    }
20798
20799    /**
20800     * Interface definition for a callback to be invoked when this view is attached
20801     * or detached from its window.
20802     */
20803    public interface OnAttachStateChangeListener {
20804        /**
20805         * Called when the view is attached to a window.
20806         * @param v The view that was attached
20807         */
20808        public void onViewAttachedToWindow(View v);
20809        /**
20810         * Called when the view is detached from a window.
20811         * @param v The view that was detached
20812         */
20813        public void onViewDetachedFromWindow(View v);
20814    }
20815
20816    /**
20817     * Listener for applying window insets on a view in a custom way.
20818     *
20819     * <p>Apps may choose to implement this interface if they want to apply custom policy
20820     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
20821     * is set, its
20822     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
20823     * method will be called instead of the View's own
20824     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
20825     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
20826     * the View's normal behavior as part of its own.</p>
20827     */
20828    public interface OnApplyWindowInsetsListener {
20829        /**
20830         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
20831         * on a View, this listener method will be called instead of the view's own
20832         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
20833         *
20834         * @param v The view applying window insets
20835         * @param insets The insets to apply
20836         * @return The insets supplied, minus any insets that were consumed
20837         */
20838        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
20839    }
20840
20841    private final class UnsetPressedState implements Runnable {
20842        @Override
20843        public void run() {
20844            setPressed(false);
20845        }
20846    }
20847
20848    /**
20849     * Base class for derived classes that want to save and restore their own
20850     * state in {@link android.view.View#onSaveInstanceState()}.
20851     */
20852    public static class BaseSavedState extends AbsSavedState {
20853        String mStartActivityRequestWhoSaved;
20854
20855        /**
20856         * Constructor used when reading from a parcel. Reads the state of the superclass.
20857         *
20858         * @param source
20859         */
20860        public BaseSavedState(Parcel source) {
20861            super(source);
20862            mStartActivityRequestWhoSaved = source.readString();
20863        }
20864
20865        /**
20866         * Constructor called by derived classes when creating their SavedState objects
20867         *
20868         * @param superState The state of the superclass of this view
20869         */
20870        public BaseSavedState(Parcelable superState) {
20871            super(superState);
20872        }
20873
20874        @Override
20875        public void writeToParcel(Parcel out, int flags) {
20876            super.writeToParcel(out, flags);
20877            out.writeString(mStartActivityRequestWhoSaved);
20878        }
20879
20880        public static final Parcelable.Creator<BaseSavedState> CREATOR =
20881                new Parcelable.Creator<BaseSavedState>() {
20882            public BaseSavedState createFromParcel(Parcel in) {
20883                return new BaseSavedState(in);
20884            }
20885
20886            public BaseSavedState[] newArray(int size) {
20887                return new BaseSavedState[size];
20888            }
20889        };
20890    }
20891
20892    /**
20893     * A set of information given to a view when it is attached to its parent
20894     * window.
20895     */
20896    final static class AttachInfo {
20897        interface Callbacks {
20898            void playSoundEffect(int effectId);
20899            boolean performHapticFeedback(int effectId, boolean always);
20900        }
20901
20902        /**
20903         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
20904         * to a Handler. This class contains the target (View) to invalidate and
20905         * the coordinates of the dirty rectangle.
20906         *
20907         * For performance purposes, this class also implements a pool of up to
20908         * POOL_LIMIT objects that get reused. This reduces memory allocations
20909         * whenever possible.
20910         */
20911        static class InvalidateInfo {
20912            private static final int POOL_LIMIT = 10;
20913
20914            private static final SynchronizedPool<InvalidateInfo> sPool =
20915                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
20916
20917            View target;
20918
20919            int left;
20920            int top;
20921            int right;
20922            int bottom;
20923
20924            public static InvalidateInfo obtain() {
20925                InvalidateInfo instance = sPool.acquire();
20926                return (instance != null) ? instance : new InvalidateInfo();
20927            }
20928
20929            public void recycle() {
20930                target = null;
20931                sPool.release(this);
20932            }
20933        }
20934
20935        final IWindowSession mSession;
20936
20937        final IWindow mWindow;
20938
20939        final IBinder mWindowToken;
20940
20941        final Display mDisplay;
20942
20943        final Callbacks mRootCallbacks;
20944
20945        IWindowId mIWindowId;
20946        WindowId mWindowId;
20947
20948        /**
20949         * The top view of the hierarchy.
20950         */
20951        View mRootView;
20952
20953        IBinder mPanelParentWindowToken;
20954
20955        boolean mHardwareAccelerated;
20956        boolean mHardwareAccelerationRequested;
20957        HardwareRenderer mHardwareRenderer;
20958        List<RenderNode> mPendingAnimatingRenderNodes;
20959
20960        /**
20961         * The state of the display to which the window is attached, as reported
20962         * by {@link Display#getState()}.  Note that the display state constants
20963         * declared by {@link Display} do not exactly line up with the screen state
20964         * constants declared by {@link View} (there are more display states than
20965         * screen states).
20966         */
20967        int mDisplayState = Display.STATE_UNKNOWN;
20968
20969        /**
20970         * Scale factor used by the compatibility mode
20971         */
20972        float mApplicationScale;
20973
20974        /**
20975         * Indicates whether the application is in compatibility mode
20976         */
20977        boolean mScalingRequired;
20978
20979        /**
20980         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
20981         */
20982        boolean mTurnOffWindowResizeAnim;
20983
20984        /**
20985         * Left position of this view's window
20986         */
20987        int mWindowLeft;
20988
20989        /**
20990         * Top position of this view's window
20991         */
20992        int mWindowTop;
20993
20994        /**
20995         * Indicates whether views need to use 32-bit drawing caches
20996         */
20997        boolean mUse32BitDrawingCache;
20998
20999        /**
21000         * For windows that are full-screen but using insets to layout inside
21001         * of the screen areas, these are the current insets to appear inside
21002         * the overscan area of the display.
21003         */
21004        final Rect mOverscanInsets = new Rect();
21005
21006        /**
21007         * For windows that are full-screen but using insets to layout inside
21008         * of the screen decorations, these are the current insets for the
21009         * content of the window.
21010         */
21011        final Rect mContentInsets = new Rect();
21012
21013        /**
21014         * For windows that are full-screen but using insets to layout inside
21015         * of the screen decorations, these are the current insets for the
21016         * actual visible parts of the window.
21017         */
21018        final Rect mVisibleInsets = new Rect();
21019
21020        /**
21021         * For windows that are full-screen but using insets to layout inside
21022         * of the screen decorations, these are the current insets for the
21023         * stable system windows.
21024         */
21025        final Rect mStableInsets = new Rect();
21026
21027        /**
21028         * The internal insets given by this window.  This value is
21029         * supplied by the client (through
21030         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
21031         * be given to the window manager when changed to be used in laying
21032         * out windows behind it.
21033         */
21034        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
21035                = new ViewTreeObserver.InternalInsetsInfo();
21036
21037        /**
21038         * Set to true when mGivenInternalInsets is non-empty.
21039         */
21040        boolean mHasNonEmptyGivenInternalInsets;
21041
21042        /**
21043         * All views in the window's hierarchy that serve as scroll containers,
21044         * used to determine if the window can be resized or must be panned
21045         * to adjust for a soft input area.
21046         */
21047        final ArrayList<View> mScrollContainers = new ArrayList<View>();
21048
21049        final KeyEvent.DispatcherState mKeyDispatchState
21050                = new KeyEvent.DispatcherState();
21051
21052        /**
21053         * Indicates whether the view's window currently has the focus.
21054         */
21055        boolean mHasWindowFocus;
21056
21057        /**
21058         * The current visibility of the window.
21059         */
21060        int mWindowVisibility;
21061
21062        /**
21063         * Indicates the time at which drawing started to occur.
21064         */
21065        long mDrawingTime;
21066
21067        /**
21068         * Indicates whether or not ignoring the DIRTY_MASK flags.
21069         */
21070        boolean mIgnoreDirtyState;
21071
21072        /**
21073         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
21074         * to avoid clearing that flag prematurely.
21075         */
21076        boolean mSetIgnoreDirtyState = false;
21077
21078        /**
21079         * Indicates whether the view's window is currently in touch mode.
21080         */
21081        boolean mInTouchMode;
21082
21083        /**
21084         * Indicates whether the view has requested unbuffered input dispatching for the current
21085         * event stream.
21086         */
21087        boolean mUnbufferedDispatchRequested;
21088
21089        /**
21090         * Indicates that ViewAncestor should trigger a global layout change
21091         * the next time it performs a traversal
21092         */
21093        boolean mRecomputeGlobalAttributes;
21094
21095        /**
21096         * Always report new attributes at next traversal.
21097         */
21098        boolean mForceReportNewAttributes;
21099
21100        /**
21101         * Set during a traveral if any views want to keep the screen on.
21102         */
21103        boolean mKeepScreenOn;
21104
21105        /**
21106         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
21107         */
21108        int mSystemUiVisibility;
21109
21110        /**
21111         * Hack to force certain system UI visibility flags to be cleared.
21112         */
21113        int mDisabledSystemUiVisibility;
21114
21115        /**
21116         * Last global system UI visibility reported by the window manager.
21117         */
21118        int mGlobalSystemUiVisibility;
21119
21120        /**
21121         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
21122         * attached.
21123         */
21124        boolean mHasSystemUiListeners;
21125
21126        /**
21127         * Set if the window has requested to extend into the overscan region
21128         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
21129         */
21130        boolean mOverscanRequested;
21131
21132        /**
21133         * Set if the visibility of any views has changed.
21134         */
21135        boolean mViewVisibilityChanged;
21136
21137        /**
21138         * Set to true if a view has been scrolled.
21139         */
21140        boolean mViewScrollChanged;
21141
21142        /**
21143         * Set to true if high contrast mode enabled
21144         */
21145        boolean mHighContrastText;
21146
21147        /**
21148         * Global to the view hierarchy used as a temporary for dealing with
21149         * x/y points in the transparent region computations.
21150         */
21151        final int[] mTransparentLocation = new int[2];
21152
21153        /**
21154         * Global to the view hierarchy used as a temporary for dealing with
21155         * x/y points in the ViewGroup.invalidateChild implementation.
21156         */
21157        final int[] mInvalidateChildLocation = new int[2];
21158
21159        /**
21160         * Global to the view hierarchy used as a temporary for dealng with
21161         * computing absolute on-screen location.
21162         */
21163        final int[] mTmpLocation = new int[2];
21164
21165        /**
21166         * Global to the view hierarchy used as a temporary for dealing with
21167         * x/y location when view is transformed.
21168         */
21169        final float[] mTmpTransformLocation = new float[2];
21170
21171        /**
21172         * The view tree observer used to dispatch global events like
21173         * layout, pre-draw, touch mode change, etc.
21174         */
21175        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
21176
21177        /**
21178         * A Canvas used by the view hierarchy to perform bitmap caching.
21179         */
21180        Canvas mCanvas;
21181
21182        /**
21183         * The view root impl.
21184         */
21185        final ViewRootImpl mViewRootImpl;
21186
21187        /**
21188         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
21189         * handler can be used to pump events in the UI events queue.
21190         */
21191        final Handler mHandler;
21192
21193        /**
21194         * Temporary for use in computing invalidate rectangles while
21195         * calling up the hierarchy.
21196         */
21197        final Rect mTmpInvalRect = new Rect();
21198
21199        /**
21200         * Temporary for use in computing hit areas with transformed views
21201         */
21202        final RectF mTmpTransformRect = new RectF();
21203
21204        /**
21205         * Temporary for use in computing hit areas with transformed views
21206         */
21207        final RectF mTmpTransformRect1 = new RectF();
21208
21209        /**
21210         * Temporary list of rectanges.
21211         */
21212        final List<RectF> mTmpRectList = new ArrayList<>();
21213
21214        /**
21215         * Temporary for use in transforming invalidation rect
21216         */
21217        final Matrix mTmpMatrix = new Matrix();
21218
21219        /**
21220         * Temporary for use in transforming invalidation rect
21221         */
21222        final Transformation mTmpTransformation = new Transformation();
21223
21224        /**
21225         * Temporary for use in querying outlines from OutlineProviders
21226         */
21227        final Outline mTmpOutline = new Outline();
21228
21229        /**
21230         * Temporary list for use in collecting focusable descendents of a view.
21231         */
21232        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
21233
21234        /**
21235         * The id of the window for accessibility purposes.
21236         */
21237        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
21238
21239        /**
21240         * Flags related to accessibility processing.
21241         *
21242         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
21243         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
21244         */
21245        int mAccessibilityFetchFlags;
21246
21247        /**
21248         * The drawable for highlighting accessibility focus.
21249         */
21250        Drawable mAccessibilityFocusDrawable;
21251
21252        /**
21253         * Show where the margins, bounds and layout bounds are for each view.
21254         */
21255        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
21256
21257        /**
21258         * Point used to compute visible regions.
21259         */
21260        final Point mPoint = new Point();
21261
21262        /**
21263         * Used to track which View originated a requestLayout() call, used when
21264         * requestLayout() is called during layout.
21265         */
21266        View mViewRequestingLayout;
21267
21268        /**
21269         * Creates a new set of attachment information with the specified
21270         * events handler and thread.
21271         *
21272         * @param handler the events handler the view must use
21273         */
21274        AttachInfo(IWindowSession session, IWindow window, Display display,
21275                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
21276            mSession = session;
21277            mWindow = window;
21278            mWindowToken = window.asBinder();
21279            mDisplay = display;
21280            mViewRootImpl = viewRootImpl;
21281            mHandler = handler;
21282            mRootCallbacks = effectPlayer;
21283        }
21284    }
21285
21286    /**
21287     * <p>ScrollabilityCache holds various fields used by a View when scrolling
21288     * is supported. This avoids keeping too many unused fields in most
21289     * instances of View.</p>
21290     */
21291    private static class ScrollabilityCache implements Runnable {
21292
21293        /**
21294         * Scrollbars are not visible
21295         */
21296        public static final int OFF = 0;
21297
21298        /**
21299         * Scrollbars are visible
21300         */
21301        public static final int ON = 1;
21302
21303        /**
21304         * Scrollbars are fading away
21305         */
21306        public static final int FADING = 2;
21307
21308        public boolean fadeScrollBars;
21309
21310        public int fadingEdgeLength;
21311        public int scrollBarDefaultDelayBeforeFade;
21312        public int scrollBarFadeDuration;
21313
21314        public int scrollBarSize;
21315        public ScrollBarDrawable scrollBar;
21316        public float[] interpolatorValues;
21317        public View host;
21318
21319        public final Paint paint;
21320        public final Matrix matrix;
21321        public Shader shader;
21322
21323        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
21324
21325        private static final float[] OPAQUE = { 255 };
21326        private static final float[] TRANSPARENT = { 0.0f };
21327
21328        /**
21329         * When fading should start. This time moves into the future every time
21330         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
21331         */
21332        public long fadeStartTime;
21333
21334
21335        /**
21336         * The current state of the scrollbars: ON, OFF, or FADING
21337         */
21338        public int state = OFF;
21339
21340        private int mLastColor;
21341
21342        public ScrollabilityCache(ViewConfiguration configuration, View host) {
21343            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
21344            scrollBarSize = configuration.getScaledScrollBarSize();
21345            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
21346            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
21347
21348            paint = new Paint();
21349            matrix = new Matrix();
21350            // use use a height of 1, and then wack the matrix each time we
21351            // actually use it.
21352            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21353            paint.setShader(shader);
21354            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21355
21356            this.host = host;
21357        }
21358
21359        public void setFadeColor(int color) {
21360            if (color != mLastColor) {
21361                mLastColor = color;
21362
21363                if (color != 0) {
21364                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
21365                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
21366                    paint.setShader(shader);
21367                    // Restore the default transfer mode (src_over)
21368                    paint.setXfermode(null);
21369                } else {
21370                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21371                    paint.setShader(shader);
21372                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21373                }
21374            }
21375        }
21376
21377        public void run() {
21378            long now = AnimationUtils.currentAnimationTimeMillis();
21379            if (now >= fadeStartTime) {
21380
21381                // the animation fades the scrollbars out by changing
21382                // the opacity (alpha) from fully opaque to fully
21383                // transparent
21384                int nextFrame = (int) now;
21385                int framesCount = 0;
21386
21387                Interpolator interpolator = scrollBarInterpolator;
21388
21389                // Start opaque
21390                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
21391
21392                // End transparent
21393                nextFrame += scrollBarFadeDuration;
21394                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
21395
21396                state = FADING;
21397
21398                // Kick off the fade animation
21399                host.invalidate(true);
21400            }
21401        }
21402    }
21403
21404    /**
21405     * Resuable callback for sending
21406     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
21407     */
21408    private class SendViewScrolledAccessibilityEvent implements Runnable {
21409        public volatile boolean mIsPending;
21410
21411        public void run() {
21412            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
21413            mIsPending = false;
21414        }
21415    }
21416
21417    /**
21418     * <p>
21419     * This class represents a delegate that can be registered in a {@link View}
21420     * to enhance accessibility support via composition rather via inheritance.
21421     * It is specifically targeted to widget developers that extend basic View
21422     * classes i.e. classes in package android.view, that would like their
21423     * applications to be backwards compatible.
21424     * </p>
21425     * <div class="special reference">
21426     * <h3>Developer Guides</h3>
21427     * <p>For more information about making applications accessible, read the
21428     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
21429     * developer guide.</p>
21430     * </div>
21431     * <p>
21432     * A scenario in which a developer would like to use an accessibility delegate
21433     * is overriding a method introduced in a later API version then the minimal API
21434     * version supported by the application. For example, the method
21435     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
21436     * in API version 4 when the accessibility APIs were first introduced. If a
21437     * developer would like his application to run on API version 4 devices (assuming
21438     * all other APIs used by the application are version 4 or lower) and take advantage
21439     * of this method, instead of overriding the method which would break the application's
21440     * backwards compatibility, he can override the corresponding method in this
21441     * delegate and register the delegate in the target View if the API version of
21442     * the system is high enough i.e. the API version is same or higher to the API
21443     * version that introduced
21444     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
21445     * </p>
21446     * <p>
21447     * Here is an example implementation:
21448     * </p>
21449     * <code><pre><p>
21450     * if (Build.VERSION.SDK_INT >= 14) {
21451     *     // If the API version is equal of higher than the version in
21452     *     // which onInitializeAccessibilityNodeInfo was introduced we
21453     *     // register a delegate with a customized implementation.
21454     *     View view = findViewById(R.id.view_id);
21455     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
21456     *         public void onInitializeAccessibilityNodeInfo(View host,
21457     *                 AccessibilityNodeInfo info) {
21458     *             // Let the default implementation populate the info.
21459     *             super.onInitializeAccessibilityNodeInfo(host, info);
21460     *             // Set some other information.
21461     *             info.setEnabled(host.isEnabled());
21462     *         }
21463     *     });
21464     * }
21465     * </code></pre></p>
21466     * <p>
21467     * This delegate contains methods that correspond to the accessibility methods
21468     * in View. If a delegate has been specified the implementation in View hands
21469     * off handling to the corresponding method in this delegate. The default
21470     * implementation the delegate methods behaves exactly as the corresponding
21471     * method in View for the case of no accessibility delegate been set. Hence,
21472     * to customize the behavior of a View method, clients can override only the
21473     * corresponding delegate method without altering the behavior of the rest
21474     * accessibility related methods of the host view.
21475     * </p>
21476     */
21477    public static class AccessibilityDelegate {
21478
21479        /**
21480         * Sends an accessibility event of the given type. If accessibility is not
21481         * enabled this method has no effect.
21482         * <p>
21483         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
21484         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
21485         * been set.
21486         * </p>
21487         *
21488         * @param host The View hosting the delegate.
21489         * @param eventType The type of the event to send.
21490         *
21491         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
21492         */
21493        public void sendAccessibilityEvent(View host, int eventType) {
21494            host.sendAccessibilityEventInternal(eventType);
21495        }
21496
21497        /**
21498         * Performs the specified accessibility action on the view. For
21499         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
21500         * <p>
21501         * The default implementation behaves as
21502         * {@link View#performAccessibilityAction(int, Bundle)
21503         *  View#performAccessibilityAction(int, Bundle)} for the case of
21504         *  no accessibility delegate been set.
21505         * </p>
21506         *
21507         * @param action The action to perform.
21508         * @return Whether the action was performed.
21509         *
21510         * @see View#performAccessibilityAction(int, Bundle)
21511         *      View#performAccessibilityAction(int, Bundle)
21512         */
21513        public boolean performAccessibilityAction(View host, int action, Bundle args) {
21514            return host.performAccessibilityActionInternal(action, args);
21515        }
21516
21517        /**
21518         * Sends an accessibility event. This method behaves exactly as
21519         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
21520         * empty {@link AccessibilityEvent} and does not perform a check whether
21521         * accessibility is enabled.
21522         * <p>
21523         * The default implementation behaves as
21524         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21525         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
21526         * the case of no accessibility delegate been set.
21527         * </p>
21528         *
21529         * @param host The View hosting the delegate.
21530         * @param event The event to send.
21531         *
21532         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21533         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21534         */
21535        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
21536            host.sendAccessibilityEventUncheckedInternal(event);
21537        }
21538
21539        /**
21540         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
21541         * to its children for adding their text content to the event.
21542         * <p>
21543         * The default implementation behaves as
21544         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21545         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
21546         * the case of no accessibility delegate been set.
21547         * </p>
21548         *
21549         * @param host The View hosting the delegate.
21550         * @param event The event.
21551         * @return True if the event population was completed.
21552         *
21553         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21554         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21555         */
21556        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
21557            return host.dispatchPopulateAccessibilityEventInternal(event);
21558        }
21559
21560        /**
21561         * Gives a chance to the host View to populate the accessibility event with its
21562         * text content.
21563         * <p>
21564         * The default implementation behaves as
21565         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
21566         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
21567         * the case of no accessibility delegate been set.
21568         * </p>
21569         *
21570         * @param host The View hosting the delegate.
21571         * @param event The accessibility event which to populate.
21572         *
21573         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
21574         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
21575         */
21576        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
21577            host.onPopulateAccessibilityEventInternal(event);
21578        }
21579
21580        /**
21581         * Initializes an {@link AccessibilityEvent} with information about the
21582         * the host View which is the event source.
21583         * <p>
21584         * The default implementation behaves as
21585         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
21586         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
21587         * the case of no accessibility delegate been set.
21588         * </p>
21589         *
21590         * @param host The View hosting the delegate.
21591         * @param event The event to initialize.
21592         *
21593         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
21594         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
21595         */
21596        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
21597            host.onInitializeAccessibilityEventInternal(event);
21598        }
21599
21600        /**
21601         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
21602         * <p>
21603         * The default implementation behaves as
21604         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21605         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
21606         * the case of no accessibility delegate been set.
21607         * </p>
21608         *
21609         * @param host The View hosting the delegate.
21610         * @param info The instance to initialize.
21611         *
21612         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21613         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21614         */
21615        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
21616            host.onInitializeAccessibilityNodeInfoInternal(info);
21617        }
21618
21619        /**
21620         * Called when a child of the host View has requested sending an
21621         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
21622         * to augment the event.
21623         * <p>
21624         * The default implementation behaves as
21625         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21626         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
21627         * the case of no accessibility delegate been set.
21628         * </p>
21629         *
21630         * @param host The View hosting the delegate.
21631         * @param child The child which requests sending the event.
21632         * @param event The event to be sent.
21633         * @return True if the event should be sent
21634         *
21635         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21636         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21637         */
21638        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
21639                AccessibilityEvent event) {
21640            return host.onRequestSendAccessibilityEventInternal(child, event);
21641        }
21642
21643        /**
21644         * Gets the provider for managing a virtual view hierarchy rooted at this View
21645         * and reported to {@link android.accessibilityservice.AccessibilityService}s
21646         * that explore the window content.
21647         * <p>
21648         * The default implementation behaves as
21649         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
21650         * the case of no accessibility delegate been set.
21651         * </p>
21652         *
21653         * @return The provider.
21654         *
21655         * @see AccessibilityNodeProvider
21656         */
21657        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
21658            return null;
21659        }
21660
21661        /**
21662         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
21663         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
21664         * This method is responsible for obtaining an accessibility node info from a
21665         * pool of reusable instances and calling
21666         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
21667         * view to initialize the former.
21668         * <p>
21669         * <strong>Note:</strong> The client is responsible for recycling the obtained
21670         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
21671         * creation.
21672         * </p>
21673         * <p>
21674         * The default implementation behaves as
21675         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
21676         * the case of no accessibility delegate been set.
21677         * </p>
21678         * @return A populated {@link AccessibilityNodeInfo}.
21679         *
21680         * @see AccessibilityNodeInfo
21681         *
21682         * @hide
21683         */
21684        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
21685            return host.createAccessibilityNodeInfoInternal();
21686        }
21687    }
21688
21689    private class MatchIdPredicate implements Predicate<View> {
21690        public int mId;
21691
21692        @Override
21693        public boolean apply(View view) {
21694            return (view.mID == mId);
21695        }
21696    }
21697
21698    private class MatchLabelForPredicate implements Predicate<View> {
21699        private int mLabeledId;
21700
21701        @Override
21702        public boolean apply(View view) {
21703            return (view.mLabelForId == mLabeledId);
21704        }
21705    }
21706
21707    private class SendViewStateChangedAccessibilityEvent implements Runnable {
21708        private int mChangeTypes = 0;
21709        private boolean mPosted;
21710        private boolean mPostedWithDelay;
21711        private long mLastEventTimeMillis;
21712
21713        @Override
21714        public void run() {
21715            mPosted = false;
21716            mPostedWithDelay = false;
21717            mLastEventTimeMillis = SystemClock.uptimeMillis();
21718            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
21719                final AccessibilityEvent event = AccessibilityEvent.obtain();
21720                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
21721                event.setContentChangeTypes(mChangeTypes);
21722                sendAccessibilityEventUnchecked(event);
21723            }
21724            mChangeTypes = 0;
21725        }
21726
21727        public void runOrPost(int changeType) {
21728            mChangeTypes |= changeType;
21729
21730            // If this is a live region or the child of a live region, collect
21731            // all events from this frame and send them on the next frame.
21732            if (inLiveRegion()) {
21733                // If we're already posted with a delay, remove that.
21734                if (mPostedWithDelay) {
21735                    removeCallbacks(this);
21736                    mPostedWithDelay = false;
21737                }
21738                // Only post if we're not already posted.
21739                if (!mPosted) {
21740                    post(this);
21741                    mPosted = true;
21742                }
21743                return;
21744            }
21745
21746            if (mPosted) {
21747                return;
21748            }
21749
21750            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
21751            final long minEventIntevalMillis =
21752                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
21753            if (timeSinceLastMillis >= minEventIntevalMillis) {
21754                removeCallbacks(this);
21755                run();
21756            } else {
21757                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
21758                mPostedWithDelay = true;
21759            }
21760        }
21761    }
21762
21763    private boolean inLiveRegion() {
21764        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21765            return true;
21766        }
21767
21768        ViewParent parent = getParent();
21769        while (parent instanceof View) {
21770            if (((View) parent).getAccessibilityLiveRegion()
21771                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21772                return true;
21773            }
21774            parent = parent.getParent();
21775        }
21776
21777        return false;
21778    }
21779
21780    /**
21781     * Dump all private flags in readable format, useful for documentation and
21782     * sanity checking.
21783     */
21784    private static void dumpFlags() {
21785        final HashMap<String, String> found = Maps.newHashMap();
21786        try {
21787            for (Field field : View.class.getDeclaredFields()) {
21788                final int modifiers = field.getModifiers();
21789                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
21790                    if (field.getType().equals(int.class)) {
21791                        final int value = field.getInt(null);
21792                        dumpFlag(found, field.getName(), value);
21793                    } else if (field.getType().equals(int[].class)) {
21794                        final int[] values = (int[]) field.get(null);
21795                        for (int i = 0; i < values.length; i++) {
21796                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
21797                        }
21798                    }
21799                }
21800            }
21801        } catch (IllegalAccessException e) {
21802            throw new RuntimeException(e);
21803        }
21804
21805        final ArrayList<String> keys = Lists.newArrayList();
21806        keys.addAll(found.keySet());
21807        Collections.sort(keys);
21808        for (String key : keys) {
21809            Log.d(VIEW_LOG_TAG, found.get(key));
21810        }
21811    }
21812
21813    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
21814        // Sort flags by prefix, then by bits, always keeping unique keys
21815        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
21816        final int prefix = name.indexOf('_');
21817        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
21818        final String output = bits + " " + name;
21819        found.put(key, output);
21820    }
21821}
21822