View.java revision 7b552516aee86cadae2721f51c6087c0dfbdd937
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 static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
20import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
21import static android.os.Build.VERSION_CODES.KITKAT;
22import static android.os.Build.VERSION_CODES.M;
23import static android.os.Build.VERSION_CODES.N;
24
25import static java.lang.Math.max;
26
27import android.animation.AnimatorInflater;
28import android.animation.StateListAnimator;
29import android.annotation.CallSuper;
30import android.annotation.ColorInt;
31import android.annotation.DrawableRes;
32import android.annotation.FloatRange;
33import android.annotation.IdRes;
34import android.annotation.IntDef;
35import android.annotation.IntRange;
36import android.annotation.LayoutRes;
37import android.annotation.NonNull;
38import android.annotation.Nullable;
39import android.annotation.Size;
40import android.annotation.TestApi;
41import android.annotation.UiThread;
42import android.app.Application.OnProvideAssistDataListener;
43import android.content.ClipData;
44import android.content.Context;
45import android.content.ContextWrapper;
46import android.content.Intent;
47import android.content.res.ColorStateList;
48import android.content.res.Configuration;
49import android.content.res.Resources;
50import android.content.res.TypedArray;
51import android.graphics.Bitmap;
52import android.graphics.Canvas;
53import android.graphics.Color;
54import android.graphics.Insets;
55import android.graphics.Interpolator;
56import android.graphics.LinearGradient;
57import android.graphics.Matrix;
58import android.graphics.Outline;
59import android.graphics.Paint;
60import android.graphics.PixelFormat;
61import android.graphics.Point;
62import android.graphics.PorterDuff;
63import android.graphics.PorterDuffXfermode;
64import android.graphics.Rect;
65import android.graphics.RectF;
66import android.graphics.Region;
67import android.graphics.Shader;
68import android.graphics.drawable.ColorDrawable;
69import android.graphics.drawable.Drawable;
70import android.hardware.display.DisplayManagerGlobal;
71import android.os.Build.VERSION_CODES;
72import android.os.Bundle;
73import android.os.Handler;
74import android.os.IBinder;
75import android.os.Parcel;
76import android.os.Parcelable;
77import android.os.RemoteException;
78import android.os.SystemClock;
79import android.os.SystemProperties;
80import android.os.Trace;
81import android.text.TextUtils;
82import android.util.AttributeSet;
83import android.util.FloatProperty;
84import android.util.LayoutDirection;
85import android.util.Log;
86import android.util.LongSparseLongArray;
87import android.util.Pools.SynchronizedPool;
88import android.util.Property;
89import android.util.SparseArray;
90import android.util.StateSet;
91import android.util.SuperNotCalledException;
92import android.util.TypedValue;
93import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
94import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
95import android.view.AccessibilityIterators.TextSegmentIterator;
96import android.view.AccessibilityIterators.WordTextSegmentIterator;
97import android.view.ContextMenu.ContextMenuInfo;
98import android.view.accessibility.AccessibilityEvent;
99import android.view.accessibility.AccessibilityEventSource;
100import android.view.accessibility.AccessibilityManager;
101import android.view.accessibility.AccessibilityNodeInfo;
102import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
103import android.view.accessibility.AccessibilityNodeProvider;
104import android.view.animation.Animation;
105import android.view.animation.AnimationUtils;
106import android.view.animation.Transformation;
107import android.view.autofill.AutoFillManager;
108import android.view.autofill.AutoFillType;
109import android.view.autofill.AutoFillValue;
110import android.view.autofill.VirtualViewDelegate;
111import android.view.inputmethod.EditorInfo;
112import android.view.inputmethod.InputConnection;
113import android.view.inputmethod.InputMethodManager;
114import android.widget.Checkable;
115import android.widget.FrameLayout;
116import android.widget.ScrollBarDrawable;
117
118import com.android.internal.R;
119import com.android.internal.util.Predicate;
120import com.android.internal.view.TooltipPopup;
121import com.android.internal.view.menu.MenuBuilder;
122import com.android.internal.widget.ScrollBarUtils;
123
124import com.google.android.collect.Lists;
125import com.google.android.collect.Maps;
126
127import java.lang.annotation.Retention;
128import java.lang.annotation.RetentionPolicy;
129import java.lang.ref.WeakReference;
130import java.lang.reflect.Field;
131import java.lang.reflect.InvocationTargetException;
132import java.lang.reflect.Method;
133import java.lang.reflect.Modifier;
134import java.util.ArrayList;
135import java.util.Arrays;
136import java.util.Collection;
137import java.util.Collections;
138import java.util.HashMap;
139import java.util.List;
140import java.util.Locale;
141import java.util.Map;
142import java.util.concurrent.CopyOnWriteArrayList;
143import java.util.concurrent.atomic.AtomicInteger;
144
145/**
146 * <p>
147 * This class represents the basic building block for user interface components. A View
148 * occupies a rectangular area on the screen and is responsible for drawing and
149 * event handling. View is the base class for <em>widgets</em>, which are
150 * used to create interactive UI components (buttons, text fields, etc.). The
151 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
152 * are invisible containers that hold other Views (or other ViewGroups) and define
153 * their layout properties.
154 * </p>
155 *
156 * <div class="special reference">
157 * <h3>Developer Guides</h3>
158 * <p>For information about using this class to develop your application's user interface,
159 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
160 * </div>
161 *
162 * <a name="Using"></a>
163 * <h3>Using Views</h3>
164 * <p>
165 * All of the views in a window are arranged in a single tree. You can add views
166 * either from code or by specifying a tree of views in one or more XML layout
167 * files. There are many specialized subclasses of views that act as controls or
168 * are capable of displaying text, images, or other content.
169 * </p>
170 * <p>
171 * Once you have created a tree of views, there are typically a few types of
172 * common operations you may wish to perform:
173 * <ul>
174 * <li><strong>Set properties:</strong> for example setting the text of a
175 * {@link android.widget.TextView}. The available properties and the methods
176 * that set them will vary among the different subclasses of views. Note that
177 * properties that are known at build time can be set in the XML layout
178 * files.</li>
179 * <li><strong>Set focus:</strong> The framework will handle moving focus in
180 * response to user input. To force focus to a specific view, call
181 * {@link #requestFocus}.</li>
182 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
183 * that will be notified when something interesting happens to the view. For
184 * example, all views will let you set a listener to be notified when the view
185 * gains or loses focus. You can register such a listener using
186 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
187 * Other view subclasses offer more specialized listeners. For example, a Button
188 * exposes a listener to notify clients when the button is clicked.</li>
189 * <li><strong>Set visibility:</strong> You can hide or show views using
190 * {@link #setVisibility(int)}.</li>
191 * </ul>
192 * </p>
193 * <p><em>
194 * Note: The Android framework is responsible for measuring, laying out and
195 * drawing views. You should not call methods that perform these actions on
196 * views yourself unless you are actually implementing a
197 * {@link android.view.ViewGroup}.
198 * </em></p>
199 *
200 * <a name="Lifecycle"></a>
201 * <h3>Implementing a Custom View</h3>
202 *
203 * <p>
204 * To implement a custom view, you will usually begin by providing overrides for
205 * some of the standard methods that the framework calls on all views. You do
206 * not need to override all of these methods. In fact, you can start by just
207 * overriding {@link #onDraw(android.graphics.Canvas)}.
208 * <table border="2" width="85%" align="center" cellpadding="5">
209 *     <thead>
210 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
211 *     </thead>
212 *
213 *     <tbody>
214 *     <tr>
215 *         <td rowspan="2">Creation</td>
216 *         <td>Constructors</td>
217 *         <td>There is a form of the constructor that are called when the view
218 *         is created from code and a form that is called when the view is
219 *         inflated from a layout file. The second form should parse and apply
220 *         any attributes defined in the layout file.
221 *         </td>
222 *     </tr>
223 *     <tr>
224 *         <td><code>{@link #onFinishInflate()}</code></td>
225 *         <td>Called after a view and all of its children has been inflated
226 *         from XML.</td>
227 *     </tr>
228 *
229 *     <tr>
230 *         <td rowspan="3">Layout</td>
231 *         <td><code>{@link #onMeasure(int, int)}</code></td>
232 *         <td>Called to determine the size requirements for this view and all
233 *         of its children.
234 *         </td>
235 *     </tr>
236 *     <tr>
237 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
238 *         <td>Called when this view should assign a size and position to all
239 *         of its children.
240 *         </td>
241 *     </tr>
242 *     <tr>
243 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
244 *         <td>Called when the size of this view has changed.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td>Drawing</td>
250 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
251 *         <td>Called when the view should render its content.
252 *         </td>
253 *     </tr>
254 *
255 *     <tr>
256 *         <td rowspan="4">Event processing</td>
257 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
258 *         <td>Called when a new hardware key event occurs.
259 *         </td>
260 *     </tr>
261 *     <tr>
262 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
263 *         <td>Called when a hardware key up event occurs.
264 *         </td>
265 *     </tr>
266 *     <tr>
267 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
268 *         <td>Called when a trackball motion event occurs.
269 *         </td>
270 *     </tr>
271 *     <tr>
272 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
273 *         <td>Called when a touch screen motion event occurs.
274 *         </td>
275 *     </tr>
276 *
277 *     <tr>
278 *         <td rowspan="2">Focus</td>
279 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
280 *         <td>Called when the view gains or loses focus.
281 *         </td>
282 *     </tr>
283 *
284 *     <tr>
285 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
286 *         <td>Called when the window containing the view gains or loses focus.
287 *         </td>
288 *     </tr>
289 *
290 *     <tr>
291 *         <td rowspan="3">Attaching</td>
292 *         <td><code>{@link #onAttachedToWindow()}</code></td>
293 *         <td>Called when the view is attached to a window.
294 *         </td>
295 *     </tr>
296 *
297 *     <tr>
298 *         <td><code>{@link #onDetachedFromWindow}</code></td>
299 *         <td>Called when the view is detached from its window.
300 *         </td>
301 *     </tr>
302 *
303 *     <tr>
304 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
305 *         <td>Called when the visibility of the window containing the view
306 *         has changed.
307 *         </td>
308 *     </tr>
309 *     </tbody>
310 *
311 * </table>
312 * </p>
313 *
314 * <a name="IDs"></a>
315 * <h3>IDs</h3>
316 * Views may have an integer id associated with them. These ids are typically
317 * assigned in the layout XML files, and are used to find specific views within
318 * the view tree. A common pattern is to:
319 * <ul>
320 * <li>Define a Button in the layout file and assign it a unique ID.
321 * <pre>
322 * &lt;Button
323 *     android:id="@+id/my_button"
324 *     android:layout_width="wrap_content"
325 *     android:layout_height="wrap_content"
326 *     android:text="@string/my_button_text"/&gt;
327 * </pre></li>
328 * <li>From the onCreate method of an Activity, find the Button
329 * <pre class="prettyprint">
330 *      Button myButton = (Button) findViewById(R.id.my_button);
331 * </pre></li>
332 * </ul>
333 * <p>
334 * View IDs need not be unique throughout the tree, but it is good practice to
335 * ensure that they are at least unique within the part of the tree you are
336 * searching.
337 * </p>
338 *
339 * <a name="Position"></a>
340 * <h3>Position</h3>
341 * <p>
342 * The geometry of a view is that of a rectangle. A view has a location,
343 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
344 * two dimensions, expressed as a width and a height. The unit for location
345 * and dimensions is the pixel.
346 * </p>
347 *
348 * <p>
349 * It is possible to retrieve the location of a view by invoking the methods
350 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
351 * coordinate of the rectangle representing the view. The latter returns the
352 * top, or Y, coordinate of the rectangle representing the view. These methods
353 * both return the location of the view relative to its parent. For instance,
354 * when getLeft() returns 20, that means the view is located 20 pixels to the
355 * right of the left edge of its direct parent.
356 * </p>
357 *
358 * <p>
359 * In addition, several convenience methods are offered to avoid unnecessary
360 * computations, namely {@link #getRight()} and {@link #getBottom()}.
361 * These methods return the coordinates of the right and bottom edges of the
362 * rectangle representing the view. For instance, calling {@link #getRight()}
363 * is similar to the following computation: <code>getLeft() + getWidth()</code>
364 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
365 * </p>
366 *
367 * <a name="SizePaddingMargins"></a>
368 * <h3>Size, padding and margins</h3>
369 * <p>
370 * The size of a view is expressed with a width and a height. A view actually
371 * possess two pairs of width and height values.
372 * </p>
373 *
374 * <p>
375 * The first pair is known as <em>measured width</em> and
376 * <em>measured height</em>. These dimensions define how big a view wants to be
377 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
378 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
379 * and {@link #getMeasuredHeight()}.
380 * </p>
381 *
382 * <p>
383 * The second pair is simply known as <em>width</em> and <em>height</em>, or
384 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
385 * dimensions define the actual size of the view on screen, at drawing time and
386 * after layout. These values may, but do not have to, be different from the
387 * measured width and height. The width and height can be obtained by calling
388 * {@link #getWidth()} and {@link #getHeight()}.
389 * </p>
390 *
391 * <p>
392 * To measure its dimensions, a view takes into account its padding. The padding
393 * is expressed in pixels for the left, top, right and bottom parts of the view.
394 * Padding can be used to offset the content of the view by a specific amount of
395 * pixels. For instance, a left padding of 2 will push the view's content by
396 * 2 pixels to the right of the left edge. Padding can be set using the
397 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
398 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
399 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
400 * {@link #getPaddingEnd()}.
401 * </p>
402 *
403 * <p>
404 * Even though a view can define a padding, it does not provide any support for
405 * margins. However, view groups provide such a support. Refer to
406 * {@link android.view.ViewGroup} and
407 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
408 * </p>
409 *
410 * <a name="Layout"></a>
411 * <h3>Layout</h3>
412 * <p>
413 * Layout is a two pass process: a measure pass and a layout pass. The measuring
414 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
415 * of the view tree. Each view pushes dimension specifications down the tree
416 * during the recursion. At the end of the measure pass, every view has stored
417 * its measurements. The second pass happens in
418 * {@link #layout(int,int,int,int)} and is also top-down. During
419 * this pass each parent is responsible for positioning all of its children
420 * using the sizes computed in the measure pass.
421 * </p>
422 *
423 * <p>
424 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
425 * {@link #getMeasuredHeight()} values must be set, along with those for all of
426 * that view's descendants. A view's measured width and measured height values
427 * must respect the constraints imposed by the view's parents. This guarantees
428 * that at the end of the measure pass, all parents accept all of their
429 * children's measurements. A parent view may call measure() more than once on
430 * its children. For example, the parent may measure each child once with
431 * unspecified dimensions to find out how big they want to be, then call
432 * measure() on them again with actual numbers if the sum of all the children's
433 * unconstrained sizes is too big or too small.
434 * </p>
435 *
436 * <p>
437 * The measure pass uses two classes to communicate dimensions. The
438 * {@link MeasureSpec} class is used by views to tell their parents how they
439 * want to be measured and positioned. The base LayoutParams class just
440 * describes how big the view wants to be for both width and height. For each
441 * dimension, it can specify one of:
442 * <ul>
443 * <li> an exact number
444 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
445 * (minus padding)
446 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
447 * enclose its content (plus padding).
448 * </ul>
449 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
450 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
451 * an X and Y value.
452 * </p>
453 *
454 * <p>
455 * MeasureSpecs are used to push requirements down the tree from parent to
456 * child. A MeasureSpec can be in one of three modes:
457 * <ul>
458 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
459 * of a child view. For example, a LinearLayout may call measure() on its child
460 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
461 * tall the child view wants to be given a width of 240 pixels.
462 * <li>EXACTLY: This is used by the parent to impose an exact size on the
463 * child. The child must use this size, and guarantee that all of its
464 * descendants will fit within this size.
465 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
466 * child. The child must guarantee that it and all of its descendants will fit
467 * within this size.
468 * </ul>
469 * </p>
470 *
471 * <p>
472 * To initiate a layout, call {@link #requestLayout}. This method is typically
473 * called by a view on itself when it believes that is can no longer fit within
474 * its current bounds.
475 * </p>
476 *
477 * <a name="Drawing"></a>
478 * <h3>Drawing</h3>
479 * <p>
480 * Drawing is handled by walking the tree and recording the drawing commands of
481 * any View that needs to update. After this, the drawing commands of the
482 * entire tree are issued to screen, clipped to the newly damaged area.
483 * </p>
484 *
485 * <p>
486 * The tree is largely recorded and drawn in order, with parents drawn before
487 * (i.e., behind) their children, with siblings drawn in the order they appear
488 * in the tree. If you set a background drawable for a View, then the View will
489 * draw it before calling back to its <code>onDraw()</code> method. The child
490 * drawing order can be overridden with
491 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
492 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
493 * </p>
494 *
495 * <p>
496 * To force a view to draw, call {@link #invalidate()}.
497 * </p>
498 *
499 * <a name="EventHandlingThreading"></a>
500 * <h3>Event Handling and Threading</h3>
501 * <p>
502 * The basic cycle of a view is as follows:
503 * <ol>
504 * <li>An event comes in and is dispatched to the appropriate view. The view
505 * handles the event and notifies any listeners.</li>
506 * <li>If in the course of processing the event, the view's bounds may need
507 * to be changed, the view will call {@link #requestLayout()}.</li>
508 * <li>Similarly, if in the course of processing the event the view's appearance
509 * may need to be changed, the view will call {@link #invalidate()}.</li>
510 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
511 * the framework will take care of measuring, laying out, and drawing the tree
512 * as appropriate.</li>
513 * </ol>
514 * </p>
515 *
516 * <p><em>Note: The entire view tree is single threaded. You must always be on
517 * the UI thread when calling any method on any view.</em>
518 * If you are doing work on other threads and want to update the state of a view
519 * from that thread, you should use a {@link Handler}.
520 * </p>
521 *
522 * <a name="FocusHandling"></a>
523 * <h3>Focus Handling</h3>
524 * <p>
525 * The framework will handle routine focus movement in response to user input.
526 * This includes changing the focus as views are removed or hidden, or as new
527 * views become available. Views indicate their willingness to take focus
528 * through the {@link #isFocusable} method. To change whether a view can take
529 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
530 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
531 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
532 * </p>
533 * <p>
534 * Focus movement is based on an algorithm which finds the nearest neighbor in a
535 * given direction. In rare cases, the default algorithm may not match the
536 * intended behavior of the developer. In these situations, you can provide
537 * explicit overrides by using these XML attributes in the layout file:
538 * <pre>
539 * nextFocusDown
540 * nextFocusLeft
541 * nextFocusRight
542 * nextFocusUp
543 * </pre>
544 * </p>
545 *
546 *
547 * <p>
548 * To get a particular view to take focus, call {@link #requestFocus()}.
549 * </p>
550 *
551 * <a name="TouchMode"></a>
552 * <h3>Touch Mode</h3>
553 * <p>
554 * When a user is navigating a user interface via directional keys such as a D-pad, it is
555 * necessary to give focus to actionable items such as buttons so the user can see
556 * what will take input.  If the device has touch capabilities, however, and the user
557 * begins interacting with the interface by touching it, it is no longer necessary to
558 * always highlight, or give focus to, a particular view.  This motivates a mode
559 * for interaction named 'touch mode'.
560 * </p>
561 * <p>
562 * For a touch capable device, once the user touches the screen, the device
563 * will enter touch mode.  From this point onward, only views for which
564 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
565 * Other views that are touchable, like buttons, will not take focus when touched; they will
566 * only fire the on click listeners.
567 * </p>
568 * <p>
569 * Any time a user hits a directional key, such as a D-pad direction, the view device will
570 * exit touch mode, and find a view to take focus, so that the user may resume interacting
571 * with the user interface without touching the screen again.
572 * </p>
573 * <p>
574 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
575 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
576 * </p>
577 *
578 * <a name="Scrolling"></a>
579 * <h3>Scrolling</h3>
580 * <p>
581 * The framework provides basic support for views that wish to internally
582 * scroll their content. This includes keeping track of the X and Y scroll
583 * offset as well as mechanisms for drawing scrollbars. See
584 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
585 * {@link #awakenScrollBars()} for more details.
586 * </p>
587 *
588 * <a name="Tags"></a>
589 * <h3>Tags</h3>
590 * <p>
591 * Unlike IDs, tags are not used to identify views. Tags are essentially an
592 * extra piece of information that can be associated with a view. They are most
593 * often used as a convenience to store data related to views in the views
594 * themselves rather than by putting them in a separate structure.
595 * </p>
596 * <p>
597 * Tags may be specified with character sequence values in layout XML as either
598 * a single tag using the {@link android.R.styleable#View_tag android:tag}
599 * attribute or multiple tags using the {@code <tag>} child element:
600 * <pre>
601 *     &ltView ...
602 *           android:tag="@string/mytag_value" /&gt;
603 *     &ltView ...&gt;
604 *         &lttag android:id="@+id/mytag"
605 *              android:value="@string/mytag_value" /&gt;
606 *     &lt/View>
607 * </pre>
608 * </p>
609 * <p>
610 * Tags may also be specified with arbitrary objects from code using
611 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
612 * </p>
613 *
614 * <a name="Themes"></a>
615 * <h3>Themes</h3>
616 * <p>
617 * By default, Views are created using the theme of the Context object supplied
618 * to their constructor; however, a different theme may be specified by using
619 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
620 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
621 * code.
622 * </p>
623 * <p>
624 * When the {@link android.R.styleable#View_theme android:theme} attribute is
625 * used in XML, the specified theme is applied on top of the inflation
626 * context's theme (see {@link LayoutInflater}) and used for the view itself as
627 * well as any child elements.
628 * </p>
629 * <p>
630 * In the following example, both views will be created using the Material dark
631 * color scheme; however, because an overlay theme is used which only defines a
632 * subset of attributes, the value of
633 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
634 * the inflation context's theme (e.g. the Activity theme) will be preserved.
635 * <pre>
636 *     &ltLinearLayout
637 *             ...
638 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
639 *         &ltView ...&gt;
640 *     &lt/LinearLayout&gt;
641 * </pre>
642 * </p>
643 *
644 * <a name="Properties"></a>
645 * <h3>Properties</h3>
646 * <p>
647 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
648 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
649 * available both in the {@link Property} form as well as in similarly-named setter/getter
650 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
651 * be used to set persistent state associated with these rendering-related properties on the view.
652 * The properties and methods can also be used in conjunction with
653 * {@link android.animation.Animator Animator}-based animations, described more in the
654 * <a href="#Animation">Animation</a> section.
655 * </p>
656 *
657 * <a name="Animation"></a>
658 * <h3>Animation</h3>
659 * <p>
660 * Starting with Android 3.0, the preferred way of animating views is to use the
661 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
662 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
663 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
664 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
665 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
666 * makes animating these View properties particularly easy and efficient.
667 * </p>
668 * <p>
669 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
670 * You can attach an {@link Animation} object to a view using
671 * {@link #setAnimation(Animation)} or
672 * {@link #startAnimation(Animation)}. The animation can alter the scale,
673 * rotation, translation and alpha of a view over time. If the animation is
674 * attached to a view that has children, the animation will affect the entire
675 * subtree rooted by that node. When an animation is started, the framework will
676 * take care of redrawing the appropriate views until the animation completes.
677 * </p>
678 *
679 * <a name="Security"></a>
680 * <h3>Security</h3>
681 * <p>
682 * Sometimes it is essential that an application be able to verify that an action
683 * is being performed with the full knowledge and consent of the user, such as
684 * granting a permission request, making a purchase or clicking on an advertisement.
685 * Unfortunately, a malicious application could try to spoof the user into
686 * performing these actions, unaware, by concealing the intended purpose of the view.
687 * As a remedy, the framework offers a touch filtering mechanism that can be used to
688 * improve the security of views that provide access to sensitive functionality.
689 * </p><p>
690 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
691 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
692 * will discard touches that are received whenever the view's window is obscured by
693 * another visible window.  As a result, the view will not receive touches whenever a
694 * toast, dialog or other window appears above the view's window.
695 * </p><p>
696 * For more fine-grained control over security, consider overriding the
697 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
698 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
699 * </p>
700 *
701 * @attr ref android.R.styleable#View_alpha
702 * @attr ref android.R.styleable#View_background
703 * @attr ref android.R.styleable#View_clickable
704 * @attr ref android.R.styleable#View_contentDescription
705 * @attr ref android.R.styleable#View_drawingCacheQuality
706 * @attr ref android.R.styleable#View_duplicateParentState
707 * @attr ref android.R.styleable#View_id
708 * @attr ref android.R.styleable#View_requiresFadingEdge
709 * @attr ref android.R.styleable#View_fadeScrollbars
710 * @attr ref android.R.styleable#View_fadingEdgeLength
711 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
712 * @attr ref android.R.styleable#View_fitsSystemWindows
713 * @attr ref android.R.styleable#View_isScrollContainer
714 * @attr ref android.R.styleable#View_focusable
715 * @attr ref android.R.styleable#View_focusableInTouchMode
716 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
717 * @attr ref android.R.styleable#View_keepScreenOn
718 * @attr ref android.R.styleable#View_layerType
719 * @attr ref android.R.styleable#View_layoutDirection
720 * @attr ref android.R.styleable#View_longClickable
721 * @attr ref android.R.styleable#View_minHeight
722 * @attr ref android.R.styleable#View_minWidth
723 * @attr ref android.R.styleable#View_nextFocusDown
724 * @attr ref android.R.styleable#View_nextFocusLeft
725 * @attr ref android.R.styleable#View_nextFocusRight
726 * @attr ref android.R.styleable#View_nextFocusUp
727 * @attr ref android.R.styleable#View_onClick
728 * @attr ref android.R.styleable#View_padding
729 * @attr ref android.R.styleable#View_paddingBottom
730 * @attr ref android.R.styleable#View_paddingLeft
731 * @attr ref android.R.styleable#View_paddingRight
732 * @attr ref android.R.styleable#View_paddingTop
733 * @attr ref android.R.styleable#View_paddingStart
734 * @attr ref android.R.styleable#View_paddingEnd
735 * @attr ref android.R.styleable#View_saveEnabled
736 * @attr ref android.R.styleable#View_rotation
737 * @attr ref android.R.styleable#View_rotationX
738 * @attr ref android.R.styleable#View_rotationY
739 * @attr ref android.R.styleable#View_scaleX
740 * @attr ref android.R.styleable#View_scaleY
741 * @attr ref android.R.styleable#View_scrollX
742 * @attr ref android.R.styleable#View_scrollY
743 * @attr ref android.R.styleable#View_scrollbarSize
744 * @attr ref android.R.styleable#View_scrollbarStyle
745 * @attr ref android.R.styleable#View_scrollbars
746 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
747 * @attr ref android.R.styleable#View_scrollbarFadeDuration
748 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
749 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
750 * @attr ref android.R.styleable#View_scrollbarThumbVertical
751 * @attr ref android.R.styleable#View_scrollbarTrackVertical
752 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
753 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
754 * @attr ref android.R.styleable#View_stateListAnimator
755 * @attr ref android.R.styleable#View_transitionName
756 * @attr ref android.R.styleable#View_soundEffectsEnabled
757 * @attr ref android.R.styleable#View_tag
758 * @attr ref android.R.styleable#View_textAlignment
759 * @attr ref android.R.styleable#View_textDirection
760 * @attr ref android.R.styleable#View_transformPivotX
761 * @attr ref android.R.styleable#View_transformPivotY
762 * @attr ref android.R.styleable#View_translationX
763 * @attr ref android.R.styleable#View_translationY
764 * @attr ref android.R.styleable#View_translationZ
765 * @attr ref android.R.styleable#View_visibility
766 * @attr ref android.R.styleable#View_theme
767 *
768 * @see android.view.ViewGroup
769 */
770@UiThread
771public class View implements Drawable.Callback, KeyEvent.Callback,
772        AccessibilityEventSource {
773    private static final boolean DBG = false;
774
775    /** @hide */
776    public static boolean DEBUG_DRAW = false;
777
778    /**
779     * The logging tag used by this class with android.util.Log.
780     */
781    protected static final String VIEW_LOG_TAG = "View";
782
783    /**
784     * When set to true, apps will draw debugging information about their layouts.
785     *
786     * @hide
787     */
788    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
789
790    /**
791     * When set to true, this view will save its attribute data.
792     *
793     * @hide
794     */
795    public static boolean mDebugViewAttributes = false;
796
797    /**
798     * Used to mark a View that has no ID.
799     */
800    public static final int NO_ID = -1;
801
802    /**
803     * Signals that compatibility booleans have been initialized according to
804     * target SDK versions.
805     */
806    private static boolean sCompatibilityDone = false;
807
808    /**
809     * Use the old (broken) way of building MeasureSpecs.
810     */
811    private static boolean sUseBrokenMakeMeasureSpec = false;
812
813    /**
814     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
815     */
816    static boolean sUseZeroUnspecifiedMeasureSpec = false;
817
818    /**
819     * Ignore any optimizations using the measure cache.
820     */
821    private static boolean sIgnoreMeasureCache = false;
822
823    /**
824     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
825     */
826    private static boolean sAlwaysRemeasureExactly = false;
827
828    /**
829     * Relax constraints around whether setLayoutParams() must be called after
830     * modifying the layout params.
831     */
832    private static boolean sLayoutParamsAlwaysChanged = false;
833
834    /**
835     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
836     * without throwing
837     */
838    static boolean sTextureViewIgnoresDrawableSetters = false;
839
840    /**
841     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
842     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
843     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
844     * check is implemented for backwards compatibility.
845     *
846     * {@hide}
847     */
848    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
849
850    /**
851     * Prior to N, when drag enters into child of a view that has already received an
852     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
853     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
854     * false from its event handler for these events.
855     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
856     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
857     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
858     */
859    static boolean sCascadedDragDrop;
860
861    /** @hide */
862    @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO})
863    @Retention(RetentionPolicy.SOURCE)
864    public @interface Focusable {}
865
866    /**
867     * This view does not want keystrokes.
868     * <p>
869     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
870     * android:focusable}.
871     */
872    public static final int NOT_FOCUSABLE = 0x00000000;
873
874    /**
875     * This view wants keystrokes.
876     * <p>
877     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
878     * android:focusable}.
879     */
880    public static final int FOCUSABLE = 0x00000001;
881
882    /**
883     * This view determines focusability automatically. This is the default.
884     * <p>
885     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
886     * android:focusable}.
887     */
888    public static final int FOCUSABLE_AUTO = 0x00000010;
889
890    /**
891     * Mask for use with setFlags indicating bits used for focus.
892     */
893    private static final int FOCUSABLE_MASK = 0x00000011;
894
895    /**
896     * This view will adjust its padding to fit sytem windows (e.g. status bar)
897     */
898    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
899
900    /** @hide */
901    @IntDef({VISIBLE, INVISIBLE, GONE})
902    @Retention(RetentionPolicy.SOURCE)
903    public @interface Visibility {}
904
905    /**
906     * This view is visible.
907     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
908     * android:visibility}.
909     */
910    public static final int VISIBLE = 0x00000000;
911
912    /**
913     * This view is invisible, but it still takes up space for layout purposes.
914     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
915     * android:visibility}.
916     */
917    public static final int INVISIBLE = 0x00000004;
918
919    /**
920     * This view is invisible, and it doesn't take any space for layout
921     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
922     * android:visibility}.
923     */
924    public static final int GONE = 0x00000008;
925
926    /**
927     * Mask for use with setFlags indicating bits used for visibility.
928     * {@hide}
929     */
930    static final int VISIBILITY_MASK = 0x0000000C;
931
932    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
933
934    /**
935     * This view is enabled. Interpretation varies by subclass.
936     * Use with ENABLED_MASK when calling setFlags.
937     * {@hide}
938     */
939    static final int ENABLED = 0x00000000;
940
941    /**
942     * This view is disabled. Interpretation varies by subclass.
943     * Use with ENABLED_MASK when calling setFlags.
944     * {@hide}
945     */
946    static final int DISABLED = 0x00000020;
947
948   /**
949    * Mask for use with setFlags indicating bits used for indicating whether
950    * this view is enabled
951    * {@hide}
952    */
953    static final int ENABLED_MASK = 0x00000020;
954
955    /**
956     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
957     * called and further optimizations will be performed. It is okay to have
958     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
959     * {@hide}
960     */
961    static final int WILL_NOT_DRAW = 0x00000080;
962
963    /**
964     * Mask for use with setFlags indicating bits used for indicating whether
965     * this view is will draw
966     * {@hide}
967     */
968    static final int DRAW_MASK = 0x00000080;
969
970    /**
971     * <p>This view doesn't show scrollbars.</p>
972     * {@hide}
973     */
974    static final int SCROLLBARS_NONE = 0x00000000;
975
976    /**
977     * <p>This view shows horizontal scrollbars.</p>
978     * {@hide}
979     */
980    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
981
982    /**
983     * <p>This view shows vertical scrollbars.</p>
984     * {@hide}
985     */
986    static final int SCROLLBARS_VERTICAL = 0x00000200;
987
988    /**
989     * <p>Mask for use with setFlags indicating bits used for indicating which
990     * scrollbars are enabled.</p>
991     * {@hide}
992     */
993    static final int SCROLLBARS_MASK = 0x00000300;
994
995    /**
996     * Indicates that the view should filter touches when its window is obscured.
997     * Refer to the class comments for more information about this security feature.
998     * {@hide}
999     */
1000    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
1001
1002    /**
1003     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
1004     * that they are optional and should be skipped if the window has
1005     * requested system UI flags that ignore those insets for layout.
1006     */
1007    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
1008
1009    /**
1010     * <p>This view doesn't show fading edges.</p>
1011     * {@hide}
1012     */
1013    static final int FADING_EDGE_NONE = 0x00000000;
1014
1015    /**
1016     * <p>This view shows horizontal fading edges.</p>
1017     * {@hide}
1018     */
1019    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1020
1021    /**
1022     * <p>This view shows vertical fading edges.</p>
1023     * {@hide}
1024     */
1025    static final int FADING_EDGE_VERTICAL = 0x00002000;
1026
1027    /**
1028     * <p>Mask for use with setFlags indicating bits used for indicating which
1029     * fading edges are enabled.</p>
1030     * {@hide}
1031     */
1032    static final int FADING_EDGE_MASK = 0x00003000;
1033
1034    /**
1035     * <p>Indicates this view can be clicked. When clickable, a View reacts
1036     * to clicks by notifying the OnClickListener.<p>
1037     * {@hide}
1038     */
1039    static final int CLICKABLE = 0x00004000;
1040
1041    /**
1042     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1043     * {@hide}
1044     */
1045    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1046
1047    /**
1048     * <p>Indicates that no icicle should be saved for this view.<p>
1049     * {@hide}
1050     */
1051    static final int SAVE_DISABLED = 0x000010000;
1052
1053    /**
1054     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1055     * property.</p>
1056     * {@hide}
1057     */
1058    static final int SAVE_DISABLED_MASK = 0x000010000;
1059
1060    /**
1061     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1062     * {@hide}
1063     */
1064    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1065
1066    /**
1067     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1068     * {@hide}
1069     */
1070    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1071
1072    /** @hide */
1073    @Retention(RetentionPolicy.SOURCE)
1074    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1075    public @interface DrawingCacheQuality {}
1076
1077    /**
1078     * <p>Enables low quality mode for the drawing cache.</p>
1079     */
1080    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1081
1082    /**
1083     * <p>Enables high quality mode for the drawing cache.</p>
1084     */
1085    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1086
1087    /**
1088     * <p>Enables automatic quality mode for the drawing cache.</p>
1089     */
1090    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1091
1092    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1093            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1094    };
1095
1096    /**
1097     * <p>Mask for use with setFlags indicating bits used for the cache
1098     * quality property.</p>
1099     * {@hide}
1100     */
1101    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1102
1103    /**
1104     * <p>
1105     * Indicates this view can be long clicked. When long clickable, a View
1106     * reacts to long clicks by notifying the OnLongClickListener or showing a
1107     * context menu.
1108     * </p>
1109     * {@hide}
1110     */
1111    static final int LONG_CLICKABLE = 0x00200000;
1112
1113    /**
1114     * <p>Indicates that this view gets its drawable states from its direct parent
1115     * and ignores its original internal states.</p>
1116     *
1117     * @hide
1118     */
1119    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1120
1121    /**
1122     * <p>
1123     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1124     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1125     * OnContextClickListener.
1126     * </p>
1127     * {@hide}
1128     */
1129    static final int CONTEXT_CLICKABLE = 0x00800000;
1130
1131
1132    /** @hide */
1133    @IntDef({
1134        SCROLLBARS_INSIDE_OVERLAY,
1135        SCROLLBARS_INSIDE_INSET,
1136        SCROLLBARS_OUTSIDE_OVERLAY,
1137        SCROLLBARS_OUTSIDE_INSET
1138    })
1139    @Retention(RetentionPolicy.SOURCE)
1140    public @interface ScrollBarStyle {}
1141
1142    /**
1143     * The scrollbar style to display the scrollbars inside the content area,
1144     * without increasing the padding. The scrollbars will be overlaid with
1145     * translucency on the view's content.
1146     */
1147    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1148
1149    /**
1150     * The scrollbar style to display the scrollbars inside the padded area,
1151     * increasing the padding of the view. The scrollbars will not overlap the
1152     * content area of the view.
1153     */
1154    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1155
1156    /**
1157     * The scrollbar style to display the scrollbars at the edge of the view,
1158     * without increasing the padding. The scrollbars will be overlaid with
1159     * translucency.
1160     */
1161    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1162
1163    /**
1164     * The scrollbar style to display the scrollbars at the edge of the view,
1165     * increasing the padding of the view. The scrollbars will only overlap the
1166     * background, if any.
1167     */
1168    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1169
1170    /**
1171     * Mask to check if the scrollbar style is overlay or inset.
1172     * {@hide}
1173     */
1174    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1175
1176    /**
1177     * Mask to check if the scrollbar style is inside or outside.
1178     * {@hide}
1179     */
1180    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1181
1182    /**
1183     * Mask for scrollbar style.
1184     * {@hide}
1185     */
1186    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1187
1188    /**
1189     * View flag indicating that the screen should remain on while the
1190     * window containing this view is visible to the user.  This effectively
1191     * takes care of automatically setting the WindowManager's
1192     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1193     */
1194    public static final int KEEP_SCREEN_ON = 0x04000000;
1195
1196    /**
1197     * View flag indicating whether this view should have sound effects enabled
1198     * for events such as clicking and touching.
1199     */
1200    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1201
1202    /**
1203     * View flag indicating whether this view should have haptic feedback
1204     * enabled for events such as long presses.
1205     */
1206    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1207
1208    /**
1209     * <p>Indicates that the view hierarchy should stop saving state when
1210     * it reaches this view.  If state saving is initiated immediately at
1211     * the view, it will be allowed.
1212     * {@hide}
1213     */
1214    static final int PARENT_SAVE_DISABLED = 0x20000000;
1215
1216    /**
1217     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1218     * {@hide}
1219     */
1220    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1221
1222    private static Paint sDebugPaint;
1223
1224    /**
1225     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1226     * {@hide}
1227     */
1228    static final int TOOLTIP = 0x40000000;
1229
1230    /** @hide */
1231    @IntDef(flag = true,
1232            value = {
1233                FOCUSABLES_ALL,
1234                FOCUSABLES_TOUCH_MODE
1235            })
1236    @Retention(RetentionPolicy.SOURCE)
1237    public @interface FocusableMode {}
1238
1239    /**
1240     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1241     * should add all focusable Views regardless if they are focusable in touch mode.
1242     */
1243    public static final int FOCUSABLES_ALL = 0x00000000;
1244
1245    /**
1246     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1247     * should add only Views focusable in touch mode.
1248     */
1249    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1250
1251    /** @hide */
1252    @IntDef({
1253            FOCUS_BACKWARD,
1254            FOCUS_FORWARD,
1255            FOCUS_LEFT,
1256            FOCUS_UP,
1257            FOCUS_RIGHT,
1258            FOCUS_DOWN
1259    })
1260    @Retention(RetentionPolicy.SOURCE)
1261    public @interface FocusDirection {}
1262
1263    /** @hide */
1264    @IntDef({
1265            FOCUS_LEFT,
1266            FOCUS_UP,
1267            FOCUS_RIGHT,
1268            FOCUS_DOWN
1269    })
1270    @Retention(RetentionPolicy.SOURCE)
1271    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1272
1273    /**
1274     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1275     * item.
1276     */
1277    public static final int FOCUS_BACKWARD = 0x00000001;
1278
1279    /**
1280     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1281     * item.
1282     */
1283    public static final int FOCUS_FORWARD = 0x00000002;
1284
1285    /**
1286     * Use with {@link #focusSearch(int)}. Move focus to the left.
1287     */
1288    public static final int FOCUS_LEFT = 0x00000011;
1289
1290    /**
1291     * Use with {@link #focusSearch(int)}. Move focus up.
1292     */
1293    public static final int FOCUS_UP = 0x00000021;
1294
1295    /**
1296     * Use with {@link #focusSearch(int)}. Move focus to the right.
1297     */
1298    public static final int FOCUS_RIGHT = 0x00000042;
1299
1300    /**
1301     * Use with {@link #focusSearch(int)}. Move focus down.
1302     */
1303    public static final int FOCUS_DOWN = 0x00000082;
1304
1305    /**
1306     * Bits of {@link #getMeasuredWidthAndState()} and
1307     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1308     */
1309    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1310
1311    /**
1312     * Bits of {@link #getMeasuredWidthAndState()} and
1313     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1314     */
1315    public static final int MEASURED_STATE_MASK = 0xff000000;
1316
1317    /**
1318     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1319     * for functions that combine both width and height into a single int,
1320     * such as {@link #getMeasuredState()} and the childState argument of
1321     * {@link #resolveSizeAndState(int, int, int)}.
1322     */
1323    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1324
1325    /**
1326     * Bit of {@link #getMeasuredWidthAndState()} and
1327     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1328     * is smaller that the space the view would like to have.
1329     */
1330    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1331
1332    /**
1333     * Base View state sets
1334     */
1335    // Singles
1336    /**
1337     * Indicates the view has no states set. States are used with
1338     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1339     * view depending on its state.
1340     *
1341     * @see android.graphics.drawable.Drawable
1342     * @see #getDrawableState()
1343     */
1344    protected static final int[] EMPTY_STATE_SET;
1345    /**
1346     * Indicates the view is enabled. States are used with
1347     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1348     * view depending on its state.
1349     *
1350     * @see android.graphics.drawable.Drawable
1351     * @see #getDrawableState()
1352     */
1353    protected static final int[] ENABLED_STATE_SET;
1354    /**
1355     * Indicates the view is focused. States are used with
1356     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1357     * view depending on its state.
1358     *
1359     * @see android.graphics.drawable.Drawable
1360     * @see #getDrawableState()
1361     */
1362    protected static final int[] FOCUSED_STATE_SET;
1363    /**
1364     * Indicates the view is selected. States are used with
1365     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1366     * view depending on its state.
1367     *
1368     * @see android.graphics.drawable.Drawable
1369     * @see #getDrawableState()
1370     */
1371    protected static final int[] SELECTED_STATE_SET;
1372    /**
1373     * Indicates the view is pressed. States are used with
1374     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1375     * view depending on its state.
1376     *
1377     * @see android.graphics.drawable.Drawable
1378     * @see #getDrawableState()
1379     */
1380    protected static final int[] PRESSED_STATE_SET;
1381    /**
1382     * Indicates the view's window has focus. States are used with
1383     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1384     * view depending on its state.
1385     *
1386     * @see android.graphics.drawable.Drawable
1387     * @see #getDrawableState()
1388     */
1389    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1390    // Doubles
1391    /**
1392     * Indicates the view is enabled and has the focus.
1393     *
1394     * @see #ENABLED_STATE_SET
1395     * @see #FOCUSED_STATE_SET
1396     */
1397    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1398    /**
1399     * Indicates the view is enabled and selected.
1400     *
1401     * @see #ENABLED_STATE_SET
1402     * @see #SELECTED_STATE_SET
1403     */
1404    protected static final int[] ENABLED_SELECTED_STATE_SET;
1405    /**
1406     * Indicates the view is enabled and that its window has focus.
1407     *
1408     * @see #ENABLED_STATE_SET
1409     * @see #WINDOW_FOCUSED_STATE_SET
1410     */
1411    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1412    /**
1413     * Indicates the view is focused and selected.
1414     *
1415     * @see #FOCUSED_STATE_SET
1416     * @see #SELECTED_STATE_SET
1417     */
1418    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1419    /**
1420     * Indicates the view has the focus and that its window has the focus.
1421     *
1422     * @see #FOCUSED_STATE_SET
1423     * @see #WINDOW_FOCUSED_STATE_SET
1424     */
1425    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1426    /**
1427     * Indicates the view is selected and that its window has the focus.
1428     *
1429     * @see #SELECTED_STATE_SET
1430     * @see #WINDOW_FOCUSED_STATE_SET
1431     */
1432    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1433    // Triples
1434    /**
1435     * Indicates the view is enabled, focused and selected.
1436     *
1437     * @see #ENABLED_STATE_SET
1438     * @see #FOCUSED_STATE_SET
1439     * @see #SELECTED_STATE_SET
1440     */
1441    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1442    /**
1443     * Indicates the view is enabled, focused and its window has the focus.
1444     *
1445     * @see #ENABLED_STATE_SET
1446     * @see #FOCUSED_STATE_SET
1447     * @see #WINDOW_FOCUSED_STATE_SET
1448     */
1449    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1450    /**
1451     * Indicates the view is enabled, selected and its window has the focus.
1452     *
1453     * @see #ENABLED_STATE_SET
1454     * @see #SELECTED_STATE_SET
1455     * @see #WINDOW_FOCUSED_STATE_SET
1456     */
1457    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1458    /**
1459     * Indicates the view is focused, selected and its window has the focus.
1460     *
1461     * @see #FOCUSED_STATE_SET
1462     * @see #SELECTED_STATE_SET
1463     * @see #WINDOW_FOCUSED_STATE_SET
1464     */
1465    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1466    /**
1467     * Indicates the view is enabled, focused, selected and its window
1468     * has the focus.
1469     *
1470     * @see #ENABLED_STATE_SET
1471     * @see #FOCUSED_STATE_SET
1472     * @see #SELECTED_STATE_SET
1473     * @see #WINDOW_FOCUSED_STATE_SET
1474     */
1475    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1476    /**
1477     * Indicates the view is pressed and its window has the focus.
1478     *
1479     * @see #PRESSED_STATE_SET
1480     * @see #WINDOW_FOCUSED_STATE_SET
1481     */
1482    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1483    /**
1484     * Indicates the view is pressed and selected.
1485     *
1486     * @see #PRESSED_STATE_SET
1487     * @see #SELECTED_STATE_SET
1488     */
1489    protected static final int[] PRESSED_SELECTED_STATE_SET;
1490    /**
1491     * Indicates the view is pressed, selected and its window has the focus.
1492     *
1493     * @see #PRESSED_STATE_SET
1494     * @see #SELECTED_STATE_SET
1495     * @see #WINDOW_FOCUSED_STATE_SET
1496     */
1497    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1498    /**
1499     * Indicates the view is pressed and focused.
1500     *
1501     * @see #PRESSED_STATE_SET
1502     * @see #FOCUSED_STATE_SET
1503     */
1504    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1505    /**
1506     * Indicates the view is pressed, focused and its window has the focus.
1507     *
1508     * @see #PRESSED_STATE_SET
1509     * @see #FOCUSED_STATE_SET
1510     * @see #WINDOW_FOCUSED_STATE_SET
1511     */
1512    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1513    /**
1514     * Indicates the view is pressed, focused and selected.
1515     *
1516     * @see #PRESSED_STATE_SET
1517     * @see #SELECTED_STATE_SET
1518     * @see #FOCUSED_STATE_SET
1519     */
1520    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1521    /**
1522     * Indicates the view is pressed, focused, selected and its window has the focus.
1523     *
1524     * @see #PRESSED_STATE_SET
1525     * @see #FOCUSED_STATE_SET
1526     * @see #SELECTED_STATE_SET
1527     * @see #WINDOW_FOCUSED_STATE_SET
1528     */
1529    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1530    /**
1531     * Indicates the view is pressed and enabled.
1532     *
1533     * @see #PRESSED_STATE_SET
1534     * @see #ENABLED_STATE_SET
1535     */
1536    protected static final int[] PRESSED_ENABLED_STATE_SET;
1537    /**
1538     * Indicates the view is pressed, enabled and its window has the focus.
1539     *
1540     * @see #PRESSED_STATE_SET
1541     * @see #ENABLED_STATE_SET
1542     * @see #WINDOW_FOCUSED_STATE_SET
1543     */
1544    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1545    /**
1546     * Indicates the view is pressed, enabled and selected.
1547     *
1548     * @see #PRESSED_STATE_SET
1549     * @see #ENABLED_STATE_SET
1550     * @see #SELECTED_STATE_SET
1551     */
1552    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1553    /**
1554     * Indicates the view is pressed, enabled, selected and its window has the
1555     * focus.
1556     *
1557     * @see #PRESSED_STATE_SET
1558     * @see #ENABLED_STATE_SET
1559     * @see #SELECTED_STATE_SET
1560     * @see #WINDOW_FOCUSED_STATE_SET
1561     */
1562    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1563    /**
1564     * Indicates the view is pressed, enabled and focused.
1565     *
1566     * @see #PRESSED_STATE_SET
1567     * @see #ENABLED_STATE_SET
1568     * @see #FOCUSED_STATE_SET
1569     */
1570    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1571    /**
1572     * Indicates the view is pressed, enabled, focused and its window has the
1573     * focus.
1574     *
1575     * @see #PRESSED_STATE_SET
1576     * @see #ENABLED_STATE_SET
1577     * @see #FOCUSED_STATE_SET
1578     * @see #WINDOW_FOCUSED_STATE_SET
1579     */
1580    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1581    /**
1582     * Indicates the view is pressed, enabled, focused and selected.
1583     *
1584     * @see #PRESSED_STATE_SET
1585     * @see #ENABLED_STATE_SET
1586     * @see #SELECTED_STATE_SET
1587     * @see #FOCUSED_STATE_SET
1588     */
1589    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1590    /**
1591     * Indicates the view is pressed, enabled, focused, selected and its window
1592     * has the focus.
1593     *
1594     * @see #PRESSED_STATE_SET
1595     * @see #ENABLED_STATE_SET
1596     * @see #SELECTED_STATE_SET
1597     * @see #FOCUSED_STATE_SET
1598     * @see #WINDOW_FOCUSED_STATE_SET
1599     */
1600    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1601
1602    static {
1603        EMPTY_STATE_SET = StateSet.get(0);
1604
1605        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1606
1607        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1608        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1609                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1610
1611        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1612        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1613                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1614        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1615                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1616        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1617                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1618                        | StateSet.VIEW_STATE_FOCUSED);
1619
1620        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1621        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1622                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1623        ENABLED_SELECTED_STATE_SET = StateSet.get(
1624                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1625        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1626                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1627                        | StateSet.VIEW_STATE_ENABLED);
1628        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1629                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1630        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1631                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1632                        | StateSet.VIEW_STATE_ENABLED);
1633        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1634                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1635                        | StateSet.VIEW_STATE_ENABLED);
1636        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1637                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1638                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1639
1640        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1641        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1642                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1643        PRESSED_SELECTED_STATE_SET = StateSet.get(
1644                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1645        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1646                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1647                        | StateSet.VIEW_STATE_PRESSED);
1648        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1649                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1650        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1651                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1652                        | StateSet.VIEW_STATE_PRESSED);
1653        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1654                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1655                        | StateSet.VIEW_STATE_PRESSED);
1656        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1657                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1658                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1659        PRESSED_ENABLED_STATE_SET = StateSet.get(
1660                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1661        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1662                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1663                        | StateSet.VIEW_STATE_PRESSED);
1664        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1665                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1666                        | StateSet.VIEW_STATE_PRESSED);
1667        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1668                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1669                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1670        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1671                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1672                        | StateSet.VIEW_STATE_PRESSED);
1673        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1674                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1675                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1676        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1677                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1678                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1679        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1680                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1681                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1682                        | StateSet.VIEW_STATE_PRESSED);
1683    }
1684
1685    /**
1686     * Accessibility event types that are dispatched for text population.
1687     */
1688    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1689            AccessibilityEvent.TYPE_VIEW_CLICKED
1690            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1691            | AccessibilityEvent.TYPE_VIEW_SELECTED
1692            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1693            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1694            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1695            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1696            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1697            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1698            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1699            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1700
1701    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
1702
1703    static final int DEBUG_CORNERS_SIZE_DIP = 8;
1704
1705    /**
1706     * Temporary Rect currently for use in setBackground().  This will probably
1707     * be extended in the future to hold our own class with more than just
1708     * a Rect. :)
1709     */
1710    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1711
1712    /**
1713     * Map used to store views' tags.
1714     */
1715    private SparseArray<Object> mKeyedTags;
1716
1717    /**
1718     * The next available accessibility id.
1719     */
1720    private static int sNextAccessibilityViewId;
1721
1722    /**
1723     * The animation currently associated with this view.
1724     * @hide
1725     */
1726    protected Animation mCurrentAnimation = null;
1727
1728    /**
1729     * Width as measured during measure pass.
1730     * {@hide}
1731     */
1732    @ViewDebug.ExportedProperty(category = "measurement")
1733    int mMeasuredWidth;
1734
1735    /**
1736     * Height as measured during measure pass.
1737     * {@hide}
1738     */
1739    @ViewDebug.ExportedProperty(category = "measurement")
1740    int mMeasuredHeight;
1741
1742    /**
1743     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1744     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1745     * its display list. This flag, used only when hw accelerated, allows us to clear the
1746     * flag while retaining this information until it's needed (at getDisplayList() time and
1747     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1748     *
1749     * {@hide}
1750     */
1751    boolean mRecreateDisplayList = false;
1752
1753    /**
1754     * The view's identifier.
1755     * {@hide}
1756     *
1757     * @see #setId(int)
1758     * @see #getId()
1759     */
1760    @IdRes
1761    @ViewDebug.ExportedProperty(resolveId = true)
1762    int mID = NO_ID;
1763
1764    /**
1765     * The stable ID of this view for accessibility purposes.
1766     */
1767    int mAccessibilityViewId = NO_ID;
1768
1769    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1770
1771    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1772
1773    /**
1774     * The view's tag.
1775     * {@hide}
1776     *
1777     * @see #setTag(Object)
1778     * @see #getTag()
1779     */
1780    protected Object mTag = null;
1781
1782    // for mPrivateFlags:
1783    /** {@hide} */
1784    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1785    /** {@hide} */
1786    static final int PFLAG_FOCUSED                     = 0x00000002;
1787    /** {@hide} */
1788    static final int PFLAG_SELECTED                    = 0x00000004;
1789    /** {@hide} */
1790    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1791    /** {@hide} */
1792    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1793    /** {@hide} */
1794    static final int PFLAG_DRAWN                       = 0x00000020;
1795    /**
1796     * When this flag is set, this view is running an animation on behalf of its
1797     * children and should therefore not cancel invalidate requests, even if they
1798     * lie outside of this view's bounds.
1799     *
1800     * {@hide}
1801     */
1802    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1803    /** {@hide} */
1804    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1805    /** {@hide} */
1806    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1807    /** {@hide} */
1808    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1809    /** {@hide} */
1810    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1811    /** {@hide} */
1812    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1813    /** {@hide} */
1814    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1815
1816    private static final int PFLAG_PRESSED             = 0x00004000;
1817
1818    /** {@hide} */
1819    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1820    /**
1821     * Flag used to indicate that this view should be drawn once more (and only once
1822     * more) after its animation has completed.
1823     * {@hide}
1824     */
1825    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1826
1827    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1828
1829    /**
1830     * Indicates that the View returned true when onSetAlpha() was called and that
1831     * the alpha must be restored.
1832     * {@hide}
1833     */
1834    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1835
1836    /**
1837     * Set by {@link #setScrollContainer(boolean)}.
1838     */
1839    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1840
1841    /**
1842     * Set by {@link #setScrollContainer(boolean)}.
1843     */
1844    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1845
1846    /**
1847     * View flag indicating whether this view was invalidated (fully or partially.)
1848     *
1849     * @hide
1850     */
1851    static final int PFLAG_DIRTY                       = 0x00200000;
1852
1853    /**
1854     * View flag indicating whether this view was invalidated by an opaque
1855     * invalidate request.
1856     *
1857     * @hide
1858     */
1859    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1860
1861    /**
1862     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1863     *
1864     * @hide
1865     */
1866    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1867
1868    /**
1869     * Indicates whether the background is opaque.
1870     *
1871     * @hide
1872     */
1873    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1874
1875    /**
1876     * Indicates whether the scrollbars are opaque.
1877     *
1878     * @hide
1879     */
1880    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1881
1882    /**
1883     * Indicates whether the view is opaque.
1884     *
1885     * @hide
1886     */
1887    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1888
1889    /**
1890     * Indicates a prepressed state;
1891     * the short time between ACTION_DOWN and recognizing
1892     * a 'real' press. Prepressed is used to recognize quick taps
1893     * even when they are shorter than ViewConfiguration.getTapTimeout().
1894     *
1895     * @hide
1896     */
1897    private static final int PFLAG_PREPRESSED          = 0x02000000;
1898
1899    /**
1900     * Indicates whether the view is temporarily detached.
1901     *
1902     * @hide
1903     */
1904    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1905
1906    /**
1907     * Indicates that we should awaken scroll bars once attached
1908     *
1909     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1910     * during window attachment and it is no longer needed. Feel free to repurpose it.
1911     *
1912     * @hide
1913     */
1914    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1915
1916    /**
1917     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1918     * @hide
1919     */
1920    private static final int PFLAG_HOVERED             = 0x10000000;
1921
1922    /**
1923     * no longer needed, should be reused
1924     */
1925    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1926
1927    /** {@hide} */
1928    static final int PFLAG_ACTIVATED                   = 0x40000000;
1929
1930    /**
1931     * Indicates that this view was specifically invalidated, not just dirtied because some
1932     * child view was invalidated. The flag is used to determine when we need to recreate
1933     * a view's display list (as opposed to just returning a reference to its existing
1934     * display list).
1935     *
1936     * @hide
1937     */
1938    static final int PFLAG_INVALIDATED                 = 0x80000000;
1939
1940    /**
1941     * Masks for mPrivateFlags2, as generated by dumpFlags():
1942     *
1943     * |-------|-------|-------|-------|
1944     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1945     *                                1  PFLAG2_DRAG_HOVERED
1946     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1947     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1948     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1949     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1950     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1951     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1952     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1953     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1954     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1955     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1956     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1957     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1958     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1959     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1960     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1961     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1962     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1963     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1964     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1965     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1966     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1967     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1968     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1969     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1970     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1971     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1972     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1973     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1974     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1975     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1976     *    1                              PFLAG2_PADDING_RESOLVED
1977     *   1                               PFLAG2_DRAWABLE_RESOLVED
1978     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1979     * |-------|-------|-------|-------|
1980     */
1981
1982    /**
1983     * Indicates that this view has reported that it can accept the current drag's content.
1984     * Cleared when the drag operation concludes.
1985     * @hide
1986     */
1987    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1988
1989    /**
1990     * Indicates that this view is currently directly under the drag location in a
1991     * drag-and-drop operation involving content that it can accept.  Cleared when
1992     * the drag exits the view, or when the drag operation concludes.
1993     * @hide
1994     */
1995    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1996
1997    /** @hide */
1998    @IntDef({
1999        LAYOUT_DIRECTION_LTR,
2000        LAYOUT_DIRECTION_RTL,
2001        LAYOUT_DIRECTION_INHERIT,
2002        LAYOUT_DIRECTION_LOCALE
2003    })
2004    @Retention(RetentionPolicy.SOURCE)
2005    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2006    public @interface LayoutDir {}
2007
2008    /** @hide */
2009    @IntDef({
2010        LAYOUT_DIRECTION_LTR,
2011        LAYOUT_DIRECTION_RTL
2012    })
2013    @Retention(RetentionPolicy.SOURCE)
2014    public @interface ResolvedLayoutDir {}
2015
2016    /**
2017     * A flag to indicate that the layout direction of this view has not been defined yet.
2018     * @hide
2019     */
2020    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2021
2022    /**
2023     * Horizontal layout direction of this view is from Left to Right.
2024     * Use with {@link #setLayoutDirection}.
2025     */
2026    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2027
2028    /**
2029     * Horizontal layout direction of this view is from Right to Left.
2030     * Use with {@link #setLayoutDirection}.
2031     */
2032    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2033
2034    /**
2035     * Horizontal layout direction of this view is inherited from its parent.
2036     * Use with {@link #setLayoutDirection}.
2037     */
2038    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2039
2040    /**
2041     * Horizontal layout direction of this view is from deduced from the default language
2042     * script for the locale. Use with {@link #setLayoutDirection}.
2043     */
2044    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2045
2046    /**
2047     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2048     * @hide
2049     */
2050    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2051
2052    /**
2053     * Mask for use with private flags indicating bits used for horizontal layout direction.
2054     * @hide
2055     */
2056    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2057
2058    /**
2059     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2060     * right-to-left direction.
2061     * @hide
2062     */
2063    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2064
2065    /**
2066     * Indicates whether the view horizontal layout direction has been resolved.
2067     * @hide
2068     */
2069    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2070
2071    /**
2072     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2073     * @hide
2074     */
2075    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2076            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2077
2078    /*
2079     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2080     * flag value.
2081     * @hide
2082     */
2083    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2084            LAYOUT_DIRECTION_LTR,
2085            LAYOUT_DIRECTION_RTL,
2086            LAYOUT_DIRECTION_INHERIT,
2087            LAYOUT_DIRECTION_LOCALE
2088    };
2089
2090    /**
2091     * Default horizontal layout direction.
2092     */
2093    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2094
2095    /**
2096     * Default horizontal layout direction.
2097     * @hide
2098     */
2099    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2100
2101    /**
2102     * Text direction is inherited through {@link ViewGroup}
2103     */
2104    public static final int TEXT_DIRECTION_INHERIT = 0;
2105
2106    /**
2107     * Text direction is using "first strong algorithm". The first strong directional character
2108     * determines the paragraph direction. If there is no strong directional character, the
2109     * paragraph direction is the view's resolved layout direction.
2110     */
2111    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2112
2113    /**
2114     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2115     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2116     * If there are neither, the paragraph direction is the view's resolved layout direction.
2117     */
2118    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2119
2120    /**
2121     * Text direction is forced to LTR.
2122     */
2123    public static final int TEXT_DIRECTION_LTR = 3;
2124
2125    /**
2126     * Text direction is forced to RTL.
2127     */
2128    public static final int TEXT_DIRECTION_RTL = 4;
2129
2130    /**
2131     * Text direction is coming from the system Locale.
2132     */
2133    public static final int TEXT_DIRECTION_LOCALE = 5;
2134
2135    /**
2136     * Text direction is using "first strong algorithm". The first strong directional character
2137     * determines the paragraph direction. If there is no strong directional character, the
2138     * paragraph direction is LTR.
2139     */
2140    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2141
2142    /**
2143     * Text direction is using "first strong algorithm". The first strong directional character
2144     * determines the paragraph direction. If there is no strong directional character, the
2145     * paragraph direction is RTL.
2146     */
2147    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2148
2149    /**
2150     * Default text direction is inherited
2151     */
2152    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2153
2154    /**
2155     * Default resolved text direction
2156     * @hide
2157     */
2158    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2159
2160    /**
2161     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2162     * @hide
2163     */
2164    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2165
2166    /**
2167     * Mask for use with private flags indicating bits used for text direction.
2168     * @hide
2169     */
2170    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2171            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2172
2173    /**
2174     * Array of text direction flags for mapping attribute "textDirection" to correct
2175     * flag value.
2176     * @hide
2177     */
2178    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2179            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2180            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2181            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2182            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2183            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2184            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2185            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2186            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2187    };
2188
2189    /**
2190     * Indicates whether the view text direction has been resolved.
2191     * @hide
2192     */
2193    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2194            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2195
2196    /**
2197     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2198     * @hide
2199     */
2200    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2201
2202    /**
2203     * Mask for use with private flags indicating bits used for resolved text direction.
2204     * @hide
2205     */
2206    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2207            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2208
2209    /**
2210     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2211     * @hide
2212     */
2213    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2214            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2215
2216    /** @hide */
2217    @IntDef({
2218        TEXT_ALIGNMENT_INHERIT,
2219        TEXT_ALIGNMENT_GRAVITY,
2220        TEXT_ALIGNMENT_CENTER,
2221        TEXT_ALIGNMENT_TEXT_START,
2222        TEXT_ALIGNMENT_TEXT_END,
2223        TEXT_ALIGNMENT_VIEW_START,
2224        TEXT_ALIGNMENT_VIEW_END
2225    })
2226    @Retention(RetentionPolicy.SOURCE)
2227    public @interface TextAlignment {}
2228
2229    /**
2230     * Default text alignment. The text alignment of this View is inherited from its parent.
2231     * Use with {@link #setTextAlignment(int)}
2232     */
2233    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2234
2235    /**
2236     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2237     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2238     *
2239     * Use with {@link #setTextAlignment(int)}
2240     */
2241    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2242
2243    /**
2244     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2245     *
2246     * Use with {@link #setTextAlignment(int)}
2247     */
2248    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2249
2250    /**
2251     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2252     *
2253     * Use with {@link #setTextAlignment(int)}
2254     */
2255    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2256
2257    /**
2258     * Center the paragraph, e.g. ALIGN_CENTER.
2259     *
2260     * Use with {@link #setTextAlignment(int)}
2261     */
2262    public static final int TEXT_ALIGNMENT_CENTER = 4;
2263
2264    /**
2265     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2266     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2267     *
2268     * Use with {@link #setTextAlignment(int)}
2269     */
2270    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2271
2272    /**
2273     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2274     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2275     *
2276     * Use with {@link #setTextAlignment(int)}
2277     */
2278    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2279
2280    /**
2281     * Default text alignment is inherited
2282     */
2283    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2284
2285    /**
2286     * Default resolved text alignment
2287     * @hide
2288     */
2289    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2290
2291    /**
2292      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2293      * @hide
2294      */
2295    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2296
2297    /**
2298      * Mask for use with private flags indicating bits used for text alignment.
2299      * @hide
2300      */
2301    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2302
2303    /**
2304     * Array of text direction flags for mapping attribute "textAlignment" to correct
2305     * flag value.
2306     * @hide
2307     */
2308    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2309            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2310            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2311            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2312            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2313            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2314            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2315            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2316    };
2317
2318    /**
2319     * Indicates whether the view text alignment has been resolved.
2320     * @hide
2321     */
2322    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2323
2324    /**
2325     * Bit shift to get the resolved text alignment.
2326     * @hide
2327     */
2328    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2329
2330    /**
2331     * Mask for use with private flags indicating bits used for text alignment.
2332     * @hide
2333     */
2334    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2335            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2336
2337    /**
2338     * Indicates whether if the view text alignment has been resolved to gravity
2339     */
2340    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2341            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2342
2343    // Accessiblity constants for mPrivateFlags2
2344
2345    /**
2346     * Shift for the bits in {@link #mPrivateFlags2} related to the
2347     * "importantForAccessibility" attribute.
2348     */
2349    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2350
2351    /**
2352     * Automatically determine whether a view is important for accessibility.
2353     */
2354    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2355
2356    /**
2357     * The view is important for accessibility.
2358     */
2359    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2360
2361    /**
2362     * The view is not important for accessibility.
2363     */
2364    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2365
2366    /**
2367     * The view is not important for accessibility, nor are any of its
2368     * descendant views.
2369     */
2370    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2371
2372    /**
2373     * The default whether the view is important for accessibility.
2374     */
2375    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2376
2377    /**
2378     * Mask for obtaining the bits which specify how to determine
2379     * whether a view is important for accessibility.
2380     */
2381    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2382        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2383        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2384        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2385
2386    /**
2387     * Shift for the bits in {@link #mPrivateFlags2} related to the
2388     * "accessibilityLiveRegion" attribute.
2389     */
2390    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2391
2392    /**
2393     * Live region mode specifying that accessibility services should not
2394     * automatically announce changes to this view. This is the default live
2395     * region mode for most views.
2396     * <p>
2397     * Use with {@link #setAccessibilityLiveRegion(int)}.
2398     */
2399    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2400
2401    /**
2402     * Live region mode specifying that accessibility services should announce
2403     * changes to this view.
2404     * <p>
2405     * Use with {@link #setAccessibilityLiveRegion(int)}.
2406     */
2407    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2408
2409    /**
2410     * Live region mode specifying that accessibility services should interrupt
2411     * ongoing speech to immediately announce changes to this view.
2412     * <p>
2413     * Use with {@link #setAccessibilityLiveRegion(int)}.
2414     */
2415    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2416
2417    /**
2418     * The default whether the view is important for accessibility.
2419     */
2420    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2421
2422    /**
2423     * Mask for obtaining the bits which specify a view's accessibility live
2424     * region mode.
2425     */
2426    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2427            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2428            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2429
2430    /**
2431     * Flag indicating whether a view has accessibility focus.
2432     */
2433    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2434
2435    /**
2436     * Flag whether the accessibility state of the subtree rooted at this view changed.
2437     */
2438    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2439
2440    /**
2441     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2442     * is used to check whether later changes to the view's transform should invalidate the
2443     * view to force the quickReject test to run again.
2444     */
2445    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2446
2447    /**
2448     * Flag indicating that start/end padding has been resolved into left/right padding
2449     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2450     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2451     * during measurement. In some special cases this is required such as when an adapter-based
2452     * view measures prospective children without attaching them to a window.
2453     */
2454    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2455
2456    /**
2457     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2458     */
2459    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2460
2461    /**
2462     * Indicates that the view is tracking some sort of transient state
2463     * that the app should not need to be aware of, but that the framework
2464     * should take special care to preserve.
2465     */
2466    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2467
2468    /**
2469     * Group of bits indicating that RTL properties resolution is done.
2470     */
2471    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2472            PFLAG2_TEXT_DIRECTION_RESOLVED |
2473            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2474            PFLAG2_PADDING_RESOLVED |
2475            PFLAG2_DRAWABLE_RESOLVED;
2476
2477    // There are a couple of flags left in mPrivateFlags2
2478
2479    /* End of masks for mPrivateFlags2 */
2480
2481    /**
2482     * Masks for mPrivateFlags3, as generated by dumpFlags():
2483     *
2484     * |-------|-------|-------|-------|
2485     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2486     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2487     *                               1   PFLAG3_IS_LAID_OUT
2488     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2489     *                             1     PFLAG3_CALLED_SUPER
2490     *                            1      PFLAG3_APPLYING_INSETS
2491     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2492     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2493     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2494     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2495     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2496     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2497     *                     1             PFLAG3_SCROLL_INDICATOR_START
2498     *                    1              PFLAG3_SCROLL_INDICATOR_END
2499     *                   1               PFLAG3_ASSIST_BLOCKED
2500     *                  1                PFLAG3_CLUSTER
2501     *                 x                 * NO LONGER NEEDED, SHOULD BE REUSED *
2502     *                1                  PFLAG3_FINGER_DOWN
2503     *               1                   PFLAG3_FOCUSED_BY_DEFAULT
2504     *           xxxx                    * NO LONGER NEEDED, SHOULD BE REUSED *
2505     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2506     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2507     *        1                          PFLAG3_TEMPORARY_DETACH
2508     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2509     * |-------|-------|-------|-------|
2510     */
2511
2512    /**
2513     * Flag indicating that view has a transform animation set on it. This is used to track whether
2514     * an animation is cleared between successive frames, in order to tell the associated
2515     * DisplayList to clear its animation matrix.
2516     */
2517    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2518
2519    /**
2520     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2521     * animation is cleared between successive frames, in order to tell the associated
2522     * DisplayList to restore its alpha value.
2523     */
2524    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2525
2526    /**
2527     * Flag indicating that the view has been through at least one layout since it
2528     * was last attached to a window.
2529     */
2530    static final int PFLAG3_IS_LAID_OUT = 0x4;
2531
2532    /**
2533     * Flag indicating that a call to measure() was skipped and should be done
2534     * instead when layout() is invoked.
2535     */
2536    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2537
2538    /**
2539     * Flag indicating that an overridden method correctly called down to
2540     * the superclass implementation as required by the API spec.
2541     */
2542    static final int PFLAG3_CALLED_SUPER = 0x10;
2543
2544    /**
2545     * Flag indicating that we're in the process of applying window insets.
2546     */
2547    static final int PFLAG3_APPLYING_INSETS = 0x20;
2548
2549    /**
2550     * Flag indicating that we're in the process of fitting system windows using the old method.
2551     */
2552    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2553
2554    /**
2555     * Flag indicating that nested scrolling is enabled for this view.
2556     * The view will optionally cooperate with views up its parent chain to allow for
2557     * integrated nested scrolling along the same axis.
2558     */
2559    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2560
2561    /**
2562     * Flag indicating that the bottom scroll indicator should be displayed
2563     * when this view can scroll up.
2564     */
2565    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2566
2567    /**
2568     * Flag indicating that the bottom scroll indicator should be displayed
2569     * when this view can scroll down.
2570     */
2571    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2572
2573    /**
2574     * Flag indicating that the left scroll indicator should be displayed
2575     * when this view can scroll left.
2576     */
2577    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2578
2579    /**
2580     * Flag indicating that the right scroll indicator should be displayed
2581     * when this view can scroll right.
2582     */
2583    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2584
2585    /**
2586     * Flag indicating that the start scroll indicator should be displayed
2587     * when this view can scroll in the start direction.
2588     */
2589    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2590
2591    /**
2592     * Flag indicating that the end scroll indicator should be displayed
2593     * when this view can scroll in the end direction.
2594     */
2595    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2596
2597    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2598
2599    static final int SCROLL_INDICATORS_NONE = 0x0000;
2600
2601    /**
2602     * Mask for use with setFlags indicating bits used for indicating which
2603     * scroll indicators are enabled.
2604     */
2605    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2606            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2607            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2608            | PFLAG3_SCROLL_INDICATOR_END;
2609
2610    /**
2611     * Left-shift required to translate between public scroll indicator flags
2612     * and internal PFLAGS3 flags. When used as a right-shift, translates
2613     * PFLAGS3 flags to public flags.
2614     */
2615    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2616
2617    /** @hide */
2618    @Retention(RetentionPolicy.SOURCE)
2619    @IntDef(flag = true,
2620            value = {
2621                    SCROLL_INDICATOR_TOP,
2622                    SCROLL_INDICATOR_BOTTOM,
2623                    SCROLL_INDICATOR_LEFT,
2624                    SCROLL_INDICATOR_RIGHT,
2625                    SCROLL_INDICATOR_START,
2626                    SCROLL_INDICATOR_END,
2627            })
2628    public @interface ScrollIndicators {}
2629
2630    /**
2631     * Scroll indicator direction for the top edge of the view.
2632     *
2633     * @see #setScrollIndicators(int)
2634     * @see #setScrollIndicators(int, int)
2635     * @see #getScrollIndicators()
2636     */
2637    public static final int SCROLL_INDICATOR_TOP =
2638            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2639
2640    /**
2641     * Scroll indicator direction for the bottom edge of the view.
2642     *
2643     * @see #setScrollIndicators(int)
2644     * @see #setScrollIndicators(int, int)
2645     * @see #getScrollIndicators()
2646     */
2647    public static final int SCROLL_INDICATOR_BOTTOM =
2648            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2649
2650    /**
2651     * Scroll indicator direction for the left edge of the view.
2652     *
2653     * @see #setScrollIndicators(int)
2654     * @see #setScrollIndicators(int, int)
2655     * @see #getScrollIndicators()
2656     */
2657    public static final int SCROLL_INDICATOR_LEFT =
2658            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2659
2660    /**
2661     * Scroll indicator direction for the right edge of the view.
2662     *
2663     * @see #setScrollIndicators(int)
2664     * @see #setScrollIndicators(int, int)
2665     * @see #getScrollIndicators()
2666     */
2667    public static final int SCROLL_INDICATOR_RIGHT =
2668            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2669
2670    /**
2671     * Scroll indicator direction for the starting edge of the view.
2672     * <p>
2673     * Resolved according to the view's layout direction, see
2674     * {@link #getLayoutDirection()} for more information.
2675     *
2676     * @see #setScrollIndicators(int)
2677     * @see #setScrollIndicators(int, int)
2678     * @see #getScrollIndicators()
2679     */
2680    public static final int SCROLL_INDICATOR_START =
2681            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2682
2683    /**
2684     * Scroll indicator direction for the ending edge of the view.
2685     * <p>
2686     * Resolved according to the view's layout direction, see
2687     * {@link #getLayoutDirection()} for more information.
2688     *
2689     * @see #setScrollIndicators(int)
2690     * @see #setScrollIndicators(int, int)
2691     * @see #getScrollIndicators()
2692     */
2693    public static final int SCROLL_INDICATOR_END =
2694            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2695
2696    /**
2697     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2698     * into this view.<p>
2699     */
2700    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2701
2702    /**
2703     * Flag indicating that the view is a root of a keyboard navigation cluster.
2704     *
2705     * @see #isKeyboardNavigationCluster()
2706     * @see #setKeyboardNavigationCluster(boolean)
2707     */
2708    private static final int PFLAG3_CLUSTER = 0x8000;
2709
2710    /**
2711     * Indicates that the user is currently touching the screen.
2712     * Currently used for the tooltip positioning only.
2713     */
2714    private static final int PFLAG3_FINGER_DOWN = 0x20000;
2715
2716    /**
2717     * Flag indicating that this view is the default-focus view.
2718     *
2719     * @see #isFocusedByDefault()
2720     * @see #setFocusedByDefault(boolean)
2721     */
2722    private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
2723
2724    /**
2725     * Whether this view has rendered elements that overlap (see {@link
2726     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2727     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2728     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2729     * determined by whatever {@link #hasOverlappingRendering()} returns.
2730     */
2731    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2732
2733    /**
2734     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2735     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2736     */
2737    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2738
2739    /**
2740     * Flag indicating that the view is temporarily detached from the parent view.
2741     *
2742     * @see #onStartTemporaryDetach()
2743     * @see #onFinishTemporaryDetach()
2744     */
2745    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2746
2747    /**
2748     * Flag indicating that the view does not wish to be revealed within its parent
2749     * hierarchy when it gains focus. Expressed in the negative since the historical
2750     * default behavior is to reveal on focus; this flag suppresses that behavior.
2751     *
2752     * @see #setRevealOnFocusHint(boolean)
2753     * @see #getRevealOnFocusHint()
2754     */
2755    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
2756
2757    /* End of masks for mPrivateFlags3 */
2758
2759    /**
2760     * Always allow a user to over-scroll this view, provided it is a
2761     * view that can scroll.
2762     *
2763     * @see #getOverScrollMode()
2764     * @see #setOverScrollMode(int)
2765     */
2766    public static final int OVER_SCROLL_ALWAYS = 0;
2767
2768    /**
2769     * Allow a user to over-scroll this view only if the content is large
2770     * enough to meaningfully scroll, provided it is a view that can scroll.
2771     *
2772     * @see #getOverScrollMode()
2773     * @see #setOverScrollMode(int)
2774     */
2775    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2776
2777    /**
2778     * Never allow a user to over-scroll this view.
2779     *
2780     * @see #getOverScrollMode()
2781     * @see #setOverScrollMode(int)
2782     */
2783    public static final int OVER_SCROLL_NEVER = 2;
2784
2785    /**
2786     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2787     * requested the system UI (status bar) to be visible (the default).
2788     *
2789     * @see #setSystemUiVisibility(int)
2790     */
2791    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2792
2793    /**
2794     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2795     * system UI to enter an unobtrusive "low profile" mode.
2796     *
2797     * <p>This is for use in games, book readers, video players, or any other
2798     * "immersive" application where the usual system chrome is deemed too distracting.
2799     *
2800     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2801     *
2802     * @see #setSystemUiVisibility(int)
2803     */
2804    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2805
2806    /**
2807     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2808     * system navigation be temporarily hidden.
2809     *
2810     * <p>This is an even less obtrusive state than that called for by
2811     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2812     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2813     * those to disappear. This is useful (in conjunction with the
2814     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2815     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2816     * window flags) for displaying content using every last pixel on the display.
2817     *
2818     * <p>There is a limitation: because navigation controls are so important, the least user
2819     * interaction will cause them to reappear immediately.  When this happens, both
2820     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2821     * so that both elements reappear at the same time.
2822     *
2823     * @see #setSystemUiVisibility(int)
2824     */
2825    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2826
2827    /**
2828     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2829     * into the normal fullscreen mode so that its content can take over the screen
2830     * while still allowing the user to interact with the application.
2831     *
2832     * <p>This has the same visual effect as
2833     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2834     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2835     * meaning that non-critical screen decorations (such as the status bar) will be
2836     * hidden while the user is in the View's window, focusing the experience on
2837     * that content.  Unlike the window flag, if you are using ActionBar in
2838     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2839     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2840     * hide the action bar.
2841     *
2842     * <p>This approach to going fullscreen is best used over the window flag when
2843     * it is a transient state -- that is, the application does this at certain
2844     * points in its user interaction where it wants to allow the user to focus
2845     * on content, but not as a continuous state.  For situations where the application
2846     * would like to simply stay full screen the entire time (such as a game that
2847     * wants to take over the screen), the
2848     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2849     * is usually a better approach.  The state set here will be removed by the system
2850     * in various situations (such as the user moving to another application) like
2851     * the other system UI states.
2852     *
2853     * <p>When using this flag, the application should provide some easy facility
2854     * for the user to go out of it.  A common example would be in an e-book
2855     * reader, where tapping on the screen brings back whatever screen and UI
2856     * decorations that had been hidden while the user was immersed in reading
2857     * the book.
2858     *
2859     * @see #setSystemUiVisibility(int)
2860     */
2861    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2862
2863    /**
2864     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2865     * flags, we would like a stable view of the content insets given to
2866     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2867     * will always represent the worst case that the application can expect
2868     * as a continuous state.  In the stock Android UI this is the space for
2869     * the system bar, nav bar, and status bar, but not more transient elements
2870     * such as an input method.
2871     *
2872     * The stable layout your UI sees is based on the system UI modes you can
2873     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2874     * then you will get a stable layout for changes of the
2875     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2876     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2877     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2878     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2879     * with a stable layout.  (Note that you should avoid using
2880     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2881     *
2882     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2883     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2884     * then a hidden status bar will be considered a "stable" state for purposes
2885     * here.  This allows your UI to continually hide the status bar, while still
2886     * using the system UI flags to hide the action bar while still retaining
2887     * a stable layout.  Note that changing the window fullscreen flag will never
2888     * provide a stable layout for a clean transition.
2889     *
2890     * <p>If you are using ActionBar in
2891     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2892     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2893     * insets it adds to those given to the application.
2894     */
2895    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2896
2897    /**
2898     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2899     * to be laid out as if it has requested
2900     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2901     * allows it to avoid artifacts when switching in and out of that mode, at
2902     * the expense that some of its user interface may be covered by screen
2903     * decorations when they are shown.  You can perform layout of your inner
2904     * UI elements to account for the navigation system UI through the
2905     * {@link #fitSystemWindows(Rect)} method.
2906     */
2907    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2908
2909    /**
2910     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2911     * to be laid out as if it has requested
2912     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2913     * allows it to avoid artifacts when switching in and out of that mode, at
2914     * the expense that some of its user interface may be covered by screen
2915     * decorations when they are shown.  You can perform layout of your inner
2916     * UI elements to account for non-fullscreen system UI through the
2917     * {@link #fitSystemWindows(Rect)} method.
2918     */
2919    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2920
2921    /**
2922     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2923     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2924     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2925     * user interaction.
2926     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2927     * has an effect when used in combination with that flag.</p>
2928     */
2929    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2930
2931    /**
2932     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2933     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2934     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2935     * experience while also hiding the system bars.  If this flag is not set,
2936     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2937     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2938     * if the user swipes from the top of the screen.
2939     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2940     * system gestures, such as swiping from the top of the screen.  These transient system bars
2941     * will overlay app’s content, may have some degree of transparency, and will automatically
2942     * hide after a short timeout.
2943     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2944     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2945     * with one or both of those flags.</p>
2946     */
2947    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2948
2949    /**
2950     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2951     * is compatible with light status bar backgrounds.
2952     *
2953     * <p>For this to take effect, the window must request
2954     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2955     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2956     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2957     *         FLAG_TRANSLUCENT_STATUS}.
2958     *
2959     * @see android.R.attr#windowLightStatusBar
2960     */
2961    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2962
2963    /**
2964     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
2965     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
2966     */
2967    private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
2968
2969    /**
2970     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
2971     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
2972     */
2973    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
2974
2975    /**
2976     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
2977     * that is compatible with light navigation bar backgrounds.
2978     *
2979     * <p>For this to take effect, the window must request
2980     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2981     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2982     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
2983     *         FLAG_TRANSLUCENT_NAVIGATION}.
2984     */
2985    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
2986
2987    /**
2988     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2989     */
2990    @Deprecated
2991    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2992
2993    /**
2994     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2995     */
2996    @Deprecated
2997    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2998
2999    /**
3000     * @hide
3001     *
3002     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3003     * out of the public fields to keep the undefined bits out of the developer's way.
3004     *
3005     * Flag to make the status bar not expandable.  Unless you also
3006     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3007     */
3008    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3009
3010    /**
3011     * @hide
3012     *
3013     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3014     * out of the public fields to keep the undefined bits out of the developer's way.
3015     *
3016     * Flag to hide notification icons and scrolling ticker text.
3017     */
3018    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3019
3020    /**
3021     * @hide
3022     *
3023     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3024     * out of the public fields to keep the undefined bits out of the developer's way.
3025     *
3026     * Flag to disable incoming notification alerts.  This will not block
3027     * icons, but it will block sound, vibrating and other visual or aural notifications.
3028     */
3029    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3030
3031    /**
3032     * @hide
3033     *
3034     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3035     * out of the public fields to keep the undefined bits out of the developer's way.
3036     *
3037     * Flag to hide only the scrolling ticker.  Note that
3038     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3039     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3040     */
3041    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3042
3043    /**
3044     * @hide
3045     *
3046     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3047     * out of the public fields to keep the undefined bits out of the developer's way.
3048     *
3049     * Flag to hide the center system info area.
3050     */
3051    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3052
3053    /**
3054     * @hide
3055     *
3056     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3057     * out of the public fields to keep the undefined bits out of the developer's way.
3058     *
3059     * Flag to hide only the home button.  Don't use this
3060     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3061     */
3062    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3063
3064    /**
3065     * @hide
3066     *
3067     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3068     * out of the public fields to keep the undefined bits out of the developer's way.
3069     *
3070     * Flag to hide only the back button. Don't use this
3071     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3072     */
3073    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3074
3075    /**
3076     * @hide
3077     *
3078     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3079     * out of the public fields to keep the undefined bits out of the developer's way.
3080     *
3081     * Flag to hide only the clock.  You might use this if your activity has
3082     * its own clock making the status bar's clock redundant.
3083     */
3084    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3085
3086    /**
3087     * @hide
3088     *
3089     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3090     * out of the public fields to keep the undefined bits out of the developer's way.
3091     *
3092     * Flag to hide only the recent apps button. Don't use this
3093     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3094     */
3095    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3096
3097    /**
3098     * @hide
3099     *
3100     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3101     * out of the public fields to keep the undefined bits out of the developer's way.
3102     *
3103     * Flag to disable the global search gesture. Don't use this
3104     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3105     */
3106    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3107
3108    /**
3109     * @hide
3110     *
3111     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3112     * out of the public fields to keep the undefined bits out of the developer's way.
3113     *
3114     * Flag to specify that the status bar is displayed in transient mode.
3115     */
3116    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3117
3118    /**
3119     * @hide
3120     *
3121     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3122     * out of the public fields to keep the undefined bits out of the developer's way.
3123     *
3124     * Flag to specify that the navigation bar is displayed in transient mode.
3125     */
3126    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3127
3128    /**
3129     * @hide
3130     *
3131     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3132     * out of the public fields to keep the undefined bits out of the developer's way.
3133     *
3134     * Flag to specify that the hidden status bar would like to be shown.
3135     */
3136    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3137
3138    /**
3139     * @hide
3140     *
3141     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3142     * out of the public fields to keep the undefined bits out of the developer's way.
3143     *
3144     * Flag to specify that the hidden navigation bar would like to be shown.
3145     */
3146    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3147
3148    /**
3149     * @hide
3150     *
3151     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3152     * out of the public fields to keep the undefined bits out of the developer's way.
3153     *
3154     * Flag to specify that the status bar is displayed in translucent mode.
3155     */
3156    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3157
3158    /**
3159     * @hide
3160     *
3161     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3162     * out of the public fields to keep the undefined bits out of the developer's way.
3163     *
3164     * Flag to specify that the navigation bar is displayed in translucent mode.
3165     */
3166    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3167
3168    /**
3169     * @hide
3170     *
3171     * Makes navigation bar transparent (but not the status bar).
3172     */
3173    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3174
3175    /**
3176     * @hide
3177     *
3178     * Makes status bar transparent (but not the navigation bar).
3179     */
3180    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3181
3182    /**
3183     * @hide
3184     *
3185     * Makes both status bar and navigation bar transparent.
3186     */
3187    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3188            | STATUS_BAR_TRANSPARENT;
3189
3190    /**
3191     * @hide
3192     */
3193    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3194
3195    /**
3196     * These are the system UI flags that can be cleared by events outside
3197     * of an application.  Currently this is just the ability to tap on the
3198     * screen while hiding the navigation bar to have it return.
3199     * @hide
3200     */
3201    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3202            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3203            | SYSTEM_UI_FLAG_FULLSCREEN;
3204
3205    /**
3206     * Flags that can impact the layout in relation to system UI.
3207     */
3208    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3209            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3210            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3211
3212    /** @hide */
3213    @IntDef(flag = true,
3214            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3215    @Retention(RetentionPolicy.SOURCE)
3216    public @interface FindViewFlags {}
3217
3218    /**
3219     * Find views that render the specified text.
3220     *
3221     * @see #findViewsWithText(ArrayList, CharSequence, int)
3222     */
3223    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3224
3225    /**
3226     * Find find views that contain the specified content description.
3227     *
3228     * @see #findViewsWithText(ArrayList, CharSequence, int)
3229     */
3230    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3231
3232    /**
3233     * Find views that contain {@link AccessibilityNodeProvider}. Such
3234     * a View is a root of virtual view hierarchy and may contain the searched
3235     * text. If this flag is set Views with providers are automatically
3236     * added and it is a responsibility of the client to call the APIs of
3237     * the provider to determine whether the virtual tree rooted at this View
3238     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3239     * representing the virtual views with this text.
3240     *
3241     * @see #findViewsWithText(ArrayList, CharSequence, int)
3242     *
3243     * @hide
3244     */
3245    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3246
3247    /**
3248     * The undefined cursor position.
3249     *
3250     * @hide
3251     */
3252    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3253
3254    /**
3255     * Indicates that the screen has changed state and is now off.
3256     *
3257     * @see #onScreenStateChanged(int)
3258     */
3259    public static final int SCREEN_STATE_OFF = 0x0;
3260
3261    /**
3262     * Indicates that the screen has changed state and is now on.
3263     *
3264     * @see #onScreenStateChanged(int)
3265     */
3266    public static final int SCREEN_STATE_ON = 0x1;
3267
3268    /**
3269     * Indicates no axis of view scrolling.
3270     */
3271    public static final int SCROLL_AXIS_NONE = 0;
3272
3273    /**
3274     * Indicates scrolling along the horizontal axis.
3275     */
3276    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3277
3278    /**
3279     * Indicates scrolling along the vertical axis.
3280     */
3281    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3282
3283    /**
3284     * Controls the over-scroll mode for this view.
3285     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3286     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3287     * and {@link #OVER_SCROLL_NEVER}.
3288     */
3289    private int mOverScrollMode;
3290
3291    /**
3292     * The parent this view is attached to.
3293     * {@hide}
3294     *
3295     * @see #getParent()
3296     */
3297    protected ViewParent mParent;
3298
3299    /**
3300     * {@hide}
3301     */
3302    AttachInfo mAttachInfo;
3303
3304    /**
3305     * {@hide}
3306     */
3307    @ViewDebug.ExportedProperty(flagMapping = {
3308        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3309                name = "FORCE_LAYOUT"),
3310        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3311                name = "LAYOUT_REQUIRED"),
3312        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3313            name = "DRAWING_CACHE_INVALID", outputIf = false),
3314        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3315        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3316        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3317        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3318    }, formatToHexString = true)
3319
3320    /* @hide */
3321    public int mPrivateFlags;
3322    int mPrivateFlags2;
3323    int mPrivateFlags3;
3324
3325    /**
3326     * This view's request for the visibility of the status bar.
3327     * @hide
3328     */
3329    @ViewDebug.ExportedProperty(flagMapping = {
3330        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3331                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3332                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3333        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3334                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3335                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3336        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3337                                equals = SYSTEM_UI_FLAG_VISIBLE,
3338                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3339    }, formatToHexString = true)
3340    int mSystemUiVisibility;
3341
3342    /**
3343     * Reference count for transient state.
3344     * @see #setHasTransientState(boolean)
3345     */
3346    int mTransientStateCount = 0;
3347
3348    /**
3349     * Count of how many windows this view has been attached to.
3350     */
3351    int mWindowAttachCount;
3352
3353    /**
3354     * The layout parameters associated with this view and used by the parent
3355     * {@link android.view.ViewGroup} to determine how this view should be
3356     * laid out.
3357     * {@hide}
3358     */
3359    protected ViewGroup.LayoutParams mLayoutParams;
3360
3361    /**
3362     * The view flags hold various views states.
3363     * {@hide}
3364     */
3365    @ViewDebug.ExportedProperty(formatToHexString = true)
3366    int mViewFlags;
3367
3368    static class TransformationInfo {
3369        /**
3370         * The transform matrix for the View. This transform is calculated internally
3371         * based on the translation, rotation, and scale properties.
3372         *
3373         * Do *not* use this variable directly; instead call getMatrix(), which will
3374         * load the value from the View's RenderNode.
3375         */
3376        private final Matrix mMatrix = new Matrix();
3377
3378        /**
3379         * The inverse transform matrix for the View. This transform is calculated
3380         * internally based on the translation, rotation, and scale properties.
3381         *
3382         * Do *not* use this variable directly; instead call getInverseMatrix(),
3383         * which will load the value from the View's RenderNode.
3384         */
3385        private Matrix mInverseMatrix;
3386
3387        /**
3388         * The opacity of the View. This is a value from 0 to 1, where 0 means
3389         * completely transparent and 1 means completely opaque.
3390         */
3391        @ViewDebug.ExportedProperty
3392        float mAlpha = 1f;
3393
3394        /**
3395         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3396         * property only used by transitions, which is composited with the other alpha
3397         * values to calculate the final visual alpha value.
3398         */
3399        float mTransitionAlpha = 1f;
3400    }
3401
3402    /** @hide */
3403    public TransformationInfo mTransformationInfo;
3404
3405    /**
3406     * Current clip bounds. to which all drawing of this view are constrained.
3407     */
3408    Rect mClipBounds = null;
3409
3410    private boolean mLastIsOpaque;
3411
3412    /**
3413     * The distance in pixels from the left edge of this view's parent
3414     * to the left edge of this view.
3415     * {@hide}
3416     */
3417    @ViewDebug.ExportedProperty(category = "layout")
3418    protected int mLeft;
3419    /**
3420     * The distance in pixels from the left edge of this view's parent
3421     * to the right edge of this view.
3422     * {@hide}
3423     */
3424    @ViewDebug.ExportedProperty(category = "layout")
3425    protected int mRight;
3426    /**
3427     * The distance in pixels from the top edge of this view's parent
3428     * to the top edge of this view.
3429     * {@hide}
3430     */
3431    @ViewDebug.ExportedProperty(category = "layout")
3432    protected int mTop;
3433    /**
3434     * The distance in pixels from the top edge of this view's parent
3435     * to the bottom edge of this view.
3436     * {@hide}
3437     */
3438    @ViewDebug.ExportedProperty(category = "layout")
3439    protected int mBottom;
3440
3441    /**
3442     * The offset, in pixels, by which the content of this view is scrolled
3443     * horizontally.
3444     * {@hide}
3445     */
3446    @ViewDebug.ExportedProperty(category = "scrolling")
3447    protected int mScrollX;
3448    /**
3449     * The offset, in pixels, by which the content of this view is scrolled
3450     * vertically.
3451     * {@hide}
3452     */
3453    @ViewDebug.ExportedProperty(category = "scrolling")
3454    protected int mScrollY;
3455
3456    /**
3457     * The left padding in pixels, that is the distance in pixels between the
3458     * left edge of this view and the left edge of its content.
3459     * {@hide}
3460     */
3461    @ViewDebug.ExportedProperty(category = "padding")
3462    protected int mPaddingLeft = 0;
3463    /**
3464     * The right padding in pixels, that is the distance in pixels between the
3465     * right edge of this view and the right edge of its content.
3466     * {@hide}
3467     */
3468    @ViewDebug.ExportedProperty(category = "padding")
3469    protected int mPaddingRight = 0;
3470    /**
3471     * The top padding in pixels, that is the distance in pixels between the
3472     * top edge of this view and the top edge of its content.
3473     * {@hide}
3474     */
3475    @ViewDebug.ExportedProperty(category = "padding")
3476    protected int mPaddingTop;
3477    /**
3478     * The bottom padding in pixels, that is the distance in pixels between the
3479     * bottom edge of this view and the bottom edge of its content.
3480     * {@hide}
3481     */
3482    @ViewDebug.ExportedProperty(category = "padding")
3483    protected int mPaddingBottom;
3484
3485    /**
3486     * The layout insets in pixels, that is the distance in pixels between the
3487     * visible edges of this view its bounds.
3488     */
3489    private Insets mLayoutInsets;
3490
3491    /**
3492     * Briefly describes the view and is primarily used for accessibility support.
3493     */
3494    private CharSequence mContentDescription;
3495
3496    /**
3497     * Specifies the id of a view for which this view serves as a label for
3498     * accessibility purposes.
3499     */
3500    private int mLabelForId = View.NO_ID;
3501
3502    /**
3503     * Predicate for matching labeled view id with its label for
3504     * accessibility purposes.
3505     */
3506    private MatchLabelForPredicate mMatchLabelForPredicate;
3507
3508    /**
3509     * Specifies a view before which this one is visited in accessibility traversal.
3510     */
3511    private int mAccessibilityTraversalBeforeId = NO_ID;
3512
3513    /**
3514     * Specifies a view after which this one is visited in accessibility traversal.
3515     */
3516    private int mAccessibilityTraversalAfterId = NO_ID;
3517
3518    /**
3519     * Predicate for matching a view by its id.
3520     */
3521    private MatchIdPredicate mMatchIdPredicate;
3522
3523    /**
3524     * Cache the paddingRight set by the user to append to the scrollbar's size.
3525     *
3526     * @hide
3527     */
3528    @ViewDebug.ExportedProperty(category = "padding")
3529    protected int mUserPaddingRight;
3530
3531    /**
3532     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3533     *
3534     * @hide
3535     */
3536    @ViewDebug.ExportedProperty(category = "padding")
3537    protected int mUserPaddingBottom;
3538
3539    /**
3540     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3541     *
3542     * @hide
3543     */
3544    @ViewDebug.ExportedProperty(category = "padding")
3545    protected int mUserPaddingLeft;
3546
3547    /**
3548     * Cache the paddingStart set by the user to append to the scrollbar's size.
3549     *
3550     */
3551    @ViewDebug.ExportedProperty(category = "padding")
3552    int mUserPaddingStart;
3553
3554    /**
3555     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3556     *
3557     */
3558    @ViewDebug.ExportedProperty(category = "padding")
3559    int mUserPaddingEnd;
3560
3561    /**
3562     * Cache initial left padding.
3563     *
3564     * @hide
3565     */
3566    int mUserPaddingLeftInitial;
3567
3568    /**
3569     * Cache initial right padding.
3570     *
3571     * @hide
3572     */
3573    int mUserPaddingRightInitial;
3574
3575    /**
3576     * Default undefined padding
3577     */
3578    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3579
3580    /**
3581     * Cache if a left padding has been defined
3582     */
3583    private boolean mLeftPaddingDefined = false;
3584
3585    /**
3586     * Cache if a right padding has been defined
3587     */
3588    private boolean mRightPaddingDefined = false;
3589
3590    /**
3591     * @hide
3592     */
3593    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3594    /**
3595     * @hide
3596     */
3597    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3598
3599    private LongSparseLongArray mMeasureCache;
3600
3601    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3602    private Drawable mBackground;
3603    private TintInfo mBackgroundTint;
3604
3605    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3606    private ForegroundInfo mForegroundInfo;
3607
3608    private Drawable mScrollIndicatorDrawable;
3609
3610    /**
3611     * RenderNode used for backgrounds.
3612     * <p>
3613     * When non-null and valid, this is expected to contain an up-to-date copy
3614     * of the background drawable. It is cleared on temporary detach, and reset
3615     * on cleanup.
3616     */
3617    private RenderNode mBackgroundRenderNode;
3618
3619    private int mBackgroundResource;
3620    private boolean mBackgroundSizeChanged;
3621
3622    private String mTransitionName;
3623
3624    static class TintInfo {
3625        ColorStateList mTintList;
3626        PorterDuff.Mode mTintMode;
3627        boolean mHasTintMode;
3628        boolean mHasTintList;
3629    }
3630
3631    private static class ForegroundInfo {
3632        private Drawable mDrawable;
3633        private TintInfo mTintInfo;
3634        private int mGravity = Gravity.FILL;
3635        private boolean mInsidePadding = true;
3636        private boolean mBoundsChanged = true;
3637        private final Rect mSelfBounds = new Rect();
3638        private final Rect mOverlayBounds = new Rect();
3639    }
3640
3641    static class ListenerInfo {
3642        /**
3643         * Listener used to dispatch focus change events.
3644         * This field should be made private, so it is hidden from the SDK.
3645         * {@hide}
3646         */
3647        protected OnFocusChangeListener mOnFocusChangeListener;
3648
3649        /**
3650         * Listeners for layout change events.
3651         */
3652        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3653
3654        protected OnScrollChangeListener mOnScrollChangeListener;
3655
3656        /**
3657         * Listeners for attach events.
3658         */
3659        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3660
3661        /**
3662         * Listener used to dispatch click events.
3663         * This field should be made private, so it is hidden from the SDK.
3664         * {@hide}
3665         */
3666        public OnClickListener mOnClickListener;
3667
3668        /**
3669         * Listener used to dispatch long click events.
3670         * This field should be made private, so it is hidden from the SDK.
3671         * {@hide}
3672         */
3673        protected OnLongClickListener mOnLongClickListener;
3674
3675        /**
3676         * Listener used to dispatch context click events. This field should be made private, so it
3677         * is hidden from the SDK.
3678         * {@hide}
3679         */
3680        protected OnContextClickListener mOnContextClickListener;
3681
3682        /**
3683         * Listener used to build the context menu.
3684         * This field should be made private, so it is hidden from the SDK.
3685         * {@hide}
3686         */
3687        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3688
3689        private OnKeyListener mOnKeyListener;
3690
3691        private OnTouchListener mOnTouchListener;
3692
3693        private OnHoverListener mOnHoverListener;
3694
3695        private OnGenericMotionListener mOnGenericMotionListener;
3696
3697        private OnDragListener mOnDragListener;
3698
3699        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3700
3701        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3702
3703        OnCapturedPointerListener mOnCapturedPointerListener;
3704    }
3705
3706    ListenerInfo mListenerInfo;
3707
3708    private static class TooltipInfo {
3709        /**
3710         * Text to be displayed in a tooltip popup.
3711         */
3712        @Nullable
3713        CharSequence mTooltipText;
3714
3715        /**
3716         * View-relative position of the tooltip anchor point.
3717         */
3718        int mAnchorX;
3719        int mAnchorY;
3720
3721        /**
3722         * The tooltip popup.
3723         */
3724        @Nullable
3725        TooltipPopup mTooltipPopup;
3726
3727        /**
3728         * Set to true if the tooltip was shown as a result of a long click.
3729         */
3730        boolean mTooltipFromLongClick;
3731
3732        /**
3733         * Keep these Runnables so that they can be used to reschedule.
3734         */
3735        Runnable mShowTooltipRunnable;
3736        Runnable mHideTooltipRunnable;
3737    }
3738
3739    TooltipInfo mTooltipInfo;
3740
3741    // Temporary values used to hold (x,y) coordinates when delegating from the
3742    // two-arg performLongClick() method to the legacy no-arg version.
3743    private float mLongClickX = Float.NaN;
3744    private float mLongClickY = Float.NaN;
3745
3746    /**
3747     * The application environment this view lives in.
3748     * This field should be made private, so it is hidden from the SDK.
3749     * {@hide}
3750     */
3751    @ViewDebug.ExportedProperty(deepExport = true)
3752    protected Context mContext;
3753
3754    private final Resources mResources;
3755
3756    private ScrollabilityCache mScrollCache;
3757
3758    private int[] mDrawableState = null;
3759
3760    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3761
3762    /**
3763     * Animator that automatically runs based on state changes.
3764     */
3765    private StateListAnimator mStateListAnimator;
3766
3767    /**
3768     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3769     * the user may specify which view to go to next.
3770     */
3771    private int mNextFocusLeftId = View.NO_ID;
3772
3773    /**
3774     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3775     * the user may specify which view to go to next.
3776     */
3777    private int mNextFocusRightId = View.NO_ID;
3778
3779    /**
3780     * When this view has focus and the next focus is {@link #FOCUS_UP},
3781     * the user may specify which view to go to next.
3782     */
3783    private int mNextFocusUpId = View.NO_ID;
3784
3785    /**
3786     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3787     * the user may specify which view to go to next.
3788     */
3789    private int mNextFocusDownId = View.NO_ID;
3790
3791    /**
3792     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3793     * the user may specify which view to go to next.
3794     */
3795    int mNextFocusForwardId = View.NO_ID;
3796
3797    /**
3798     * User-specified next keyboard navigation cluster.
3799     */
3800    int mNextClusterForwardId = View.NO_ID;
3801
3802    private CheckForLongPress mPendingCheckForLongPress;
3803    private CheckForTap mPendingCheckForTap = null;
3804    private PerformClick mPerformClick;
3805    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3806
3807    private UnsetPressedState mUnsetPressedState;
3808
3809    /**
3810     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3811     * up event while a long press is invoked as soon as the long press duration is reached, so
3812     * a long press could be performed before the tap is checked, in which case the tap's action
3813     * should not be invoked.
3814     */
3815    private boolean mHasPerformedLongPress;
3816
3817    /**
3818     * Whether a context click button is currently pressed down. This is true when the stylus is
3819     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3820     * pressed. This is false once the button is released or if the stylus has been lifted.
3821     */
3822    private boolean mInContextButtonPress;
3823
3824    /**
3825     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3826     * true after a stylus button press has occured, when the next up event should not be recognized
3827     * as a tap.
3828     */
3829    private boolean mIgnoreNextUpEvent;
3830
3831    /**
3832     * The minimum height of the view. We'll try our best to have the height
3833     * of this view to at least this amount.
3834     */
3835    @ViewDebug.ExportedProperty(category = "measurement")
3836    private int mMinHeight;
3837
3838    /**
3839     * The minimum width of the view. We'll try our best to have the width
3840     * of this view to at least this amount.
3841     */
3842    @ViewDebug.ExportedProperty(category = "measurement")
3843    private int mMinWidth;
3844
3845    /**
3846     * The delegate to handle touch events that are physically in this view
3847     * but should be handled by another view.
3848     */
3849    private TouchDelegate mTouchDelegate = null;
3850
3851    /**
3852     * Solid color to use as a background when creating the drawing cache. Enables
3853     * the cache to use 16 bit bitmaps instead of 32 bit.
3854     */
3855    private int mDrawingCacheBackgroundColor = 0;
3856
3857    /**
3858     * Special tree observer used when mAttachInfo is null.
3859     */
3860    private ViewTreeObserver mFloatingTreeObserver;
3861
3862    /**
3863     * Cache the touch slop from the context that created the view.
3864     */
3865    private int mTouchSlop;
3866
3867    /**
3868     * Object that handles automatic animation of view properties.
3869     */
3870    private ViewPropertyAnimator mAnimator = null;
3871
3872    /**
3873     * List of registered FrameMetricsObservers.
3874     */
3875    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3876
3877    /**
3878     * Flag indicating that a drag can cross window boundaries.  When
3879     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3880     * with this flag set, all visible applications with targetSdkVersion >=
3881     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3882     * in the drag operation and receive the dragged content.
3883     *
3884     * <p>If this is the only flag set, then the drag recipient will only have access to text data
3885     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3886     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
3887     */
3888    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3889
3890    /**
3891     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3892     * request read access to the content URI(s) contained in the {@link ClipData} object.
3893     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3894     */
3895    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3896
3897    /**
3898     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3899     * request write access to the content URI(s) contained in the {@link ClipData} object.
3900     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3901     */
3902    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3903
3904    /**
3905     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3906     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3907     * reboots until explicitly revoked with
3908     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3909     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3910     */
3911    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3912            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3913
3914    /**
3915     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3916     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3917     * match against the original granted URI.
3918     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3919     */
3920    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3921            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3922
3923    /**
3924     * Flag indicating that the drag shadow will be opaque.  When
3925     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3926     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3927     */
3928    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3929
3930    /**
3931     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3932     */
3933    private float mVerticalScrollFactor;
3934
3935    /**
3936     * Position of the vertical scroll bar.
3937     */
3938    private int mVerticalScrollbarPosition;
3939
3940    /**
3941     * Position the scroll bar at the default position as determined by the system.
3942     */
3943    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3944
3945    /**
3946     * Position the scroll bar along the left edge.
3947     */
3948    public static final int SCROLLBAR_POSITION_LEFT = 1;
3949
3950    /**
3951     * Position the scroll bar along the right edge.
3952     */
3953    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3954
3955    /**
3956     * Indicates that the view does not have a layer.
3957     *
3958     * @see #getLayerType()
3959     * @see #setLayerType(int, android.graphics.Paint)
3960     * @see #LAYER_TYPE_SOFTWARE
3961     * @see #LAYER_TYPE_HARDWARE
3962     */
3963    public static final int LAYER_TYPE_NONE = 0;
3964
3965    /**
3966     * <p>Indicates that the view has a software layer. A software layer is backed
3967     * by a bitmap and causes the view to be rendered using Android's software
3968     * rendering pipeline, even if hardware acceleration is enabled.</p>
3969     *
3970     * <p>Software layers have various usages:</p>
3971     * <p>When the application is not using hardware acceleration, a software layer
3972     * is useful to apply a specific color filter and/or blending mode and/or
3973     * translucency to a view and all its children.</p>
3974     * <p>When the application is using hardware acceleration, a software layer
3975     * is useful to render drawing primitives not supported by the hardware
3976     * accelerated pipeline. It can also be used to cache a complex view tree
3977     * into a texture and reduce the complexity of drawing operations. For instance,
3978     * when animating a complex view tree with a translation, a software layer can
3979     * be used to render the view tree only once.</p>
3980     * <p>Software layers should be avoided when the affected view tree updates
3981     * often. Every update will require to re-render the software layer, which can
3982     * potentially be slow (particularly when hardware acceleration is turned on
3983     * since the layer will have to be uploaded into a hardware texture after every
3984     * update.)</p>
3985     *
3986     * @see #getLayerType()
3987     * @see #setLayerType(int, android.graphics.Paint)
3988     * @see #LAYER_TYPE_NONE
3989     * @see #LAYER_TYPE_HARDWARE
3990     */
3991    public static final int LAYER_TYPE_SOFTWARE = 1;
3992
3993    /**
3994     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3995     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3996     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3997     * rendering pipeline, but only if hardware acceleration is turned on for the
3998     * view hierarchy. When hardware acceleration is turned off, hardware layers
3999     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
4000     *
4001     * <p>A hardware layer is useful to apply a specific color filter and/or
4002     * blending mode and/or translucency to a view and all its children.</p>
4003     * <p>A hardware layer can be used to cache a complex view tree into a
4004     * texture and reduce the complexity of drawing operations. For instance,
4005     * when animating a complex view tree with a translation, a hardware layer can
4006     * be used to render the view tree only once.</p>
4007     * <p>A hardware layer can also be used to increase the rendering quality when
4008     * rotation transformations are applied on a view. It can also be used to
4009     * prevent potential clipping issues when applying 3D transforms on a view.</p>
4010     *
4011     * @see #getLayerType()
4012     * @see #setLayerType(int, android.graphics.Paint)
4013     * @see #LAYER_TYPE_NONE
4014     * @see #LAYER_TYPE_SOFTWARE
4015     */
4016    public static final int LAYER_TYPE_HARDWARE = 2;
4017
4018    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4019            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
4020            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
4021            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
4022    })
4023    int mLayerType = LAYER_TYPE_NONE;
4024    Paint mLayerPaint;
4025
4026
4027    /**
4028     * Set when a request was made to decide if views in an {@link android.app.Activity} can be
4029     * auto-filled by an {@link android.service.autofill.AutoFillService}.
4030     *
4031     * <p>Since this request is made without a explicit user consent, the resulting
4032     * {@link android.app.assist.AssistStructure} should not contain any PII
4033     * (Personally Identifiable Information).
4034     *
4035     * <p>Examples:
4036     * <ul>
4037     * <li>{@link android.widget.TextView} texts should only be included when they were set by
4038     * static resources.
4039     * <li>{@link android.webkit.WebView} virtual children should be restricted to a subset of
4040     * input fields and tags (like {@code id}).
4041     * </ul>
4042     */
4043    // TODO(b/33197203): cannot conflict with flags defined on AutoFillManager until they're removed
4044    // (when save is refactored).
4045    public static final int AUTO_FILL_FLAG_TYPE_FILL = 0x10000000;
4046
4047    /**
4048     * Set when the user explicitly asked a {@link android.service.autofill.AutoFillService} to save
4049     * the value of the {@link View}s in an {@link android.app.Activity}.
4050     *
4051     * <p>The resulting {@link android.app.assist.AssistStructure} can contain any kind of PII
4052     * (Personally Identifiable Information). For example, the text of password fields should be
4053     * included since that's what's typically saved.
4054     */
4055    // TODO(b/33197203): cannot conflict with flags defined on AutoFillManager until they're removed
4056    // (when save is refactored).
4057    public static final int AUTO_FILL_FLAG_TYPE_SAVE = 0x20000000;
4058
4059    /**
4060     * Set to true when drawing cache is enabled and cannot be created.
4061     *
4062     * @hide
4063     */
4064    public boolean mCachingFailed;
4065    private Bitmap mDrawingCache;
4066    private Bitmap mUnscaledDrawingCache;
4067
4068    /**
4069     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4070     * <p>
4071     * When non-null and valid, this is expected to contain an up-to-date copy
4072     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4073     * cleanup.
4074     */
4075    final RenderNode mRenderNode;
4076
4077    /**
4078     * Set to true when the view is sending hover accessibility events because it
4079     * is the innermost hovered view.
4080     */
4081    private boolean mSendingHoverAccessibilityEvents;
4082
4083    /**
4084     * Delegate for injecting accessibility functionality.
4085     */
4086    AccessibilityDelegate mAccessibilityDelegate;
4087
4088    /**
4089     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4090     * and add/remove objects to/from the overlay directly through the Overlay methods.
4091     */
4092    ViewOverlay mOverlay;
4093
4094    /**
4095     * The currently active parent view for receiving delegated nested scrolling events.
4096     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4097     * by {@link #stopNestedScroll()} at the same point where we clear
4098     * requestDisallowInterceptTouchEvent.
4099     */
4100    private ViewParent mNestedScrollingParent;
4101
4102    /**
4103     * Consistency verifier for debugging purposes.
4104     * @hide
4105     */
4106    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4107            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4108                    new InputEventConsistencyVerifier(this, 0) : null;
4109
4110    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4111
4112    private int[] mTempNestedScrollConsumed;
4113
4114    /**
4115     * An overlay is going to draw this View instead of being drawn as part of this
4116     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4117     * when this view is invalidated.
4118     */
4119    GhostView mGhostView;
4120
4121    /**
4122     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4123     * @hide
4124     */
4125    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4126    public String[] mAttributes;
4127
4128    /**
4129     * Maps a Resource id to its name.
4130     */
4131    private static SparseArray<String> mAttributeMap;
4132
4133    /**
4134     * Queue of pending runnables. Used to postpone calls to post() until this
4135     * view is attached and has a handler.
4136     */
4137    private HandlerActionQueue mRunQueue;
4138
4139    /**
4140     * The pointer icon when the mouse hovers on this view. The default is null.
4141     */
4142    private PointerIcon mPointerIcon;
4143
4144    /**
4145     * @hide
4146     */
4147    String mStartActivityRequestWho;
4148
4149    @Nullable
4150    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4151
4152    /**
4153     * Simple constructor to use when creating a view from code.
4154     *
4155     * @param context The Context the view is running in, through which it can
4156     *        access the current theme, resources, etc.
4157     */
4158    public View(Context context) {
4159        mContext = context;
4160        mResources = context != null ? context.getResources() : null;
4161        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO;
4162        // Set some flags defaults
4163        mPrivateFlags2 =
4164                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4165                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4166                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4167                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4168                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4169                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4170        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4171        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4172        mUserPaddingStart = UNDEFINED_PADDING;
4173        mUserPaddingEnd = UNDEFINED_PADDING;
4174        mRenderNode = RenderNode.create(getClass().getName(), this);
4175
4176        if (!sCompatibilityDone && context != null) {
4177            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4178
4179            // Older apps may need this compatibility hack for measurement.
4180            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4181
4182            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4183            // of whether a layout was requested on that View.
4184            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4185
4186            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4187
4188            // In M and newer, our widgets can pass a "hint" value in the size
4189            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4190            // know what the expected parent size is going to be, so e.g. list items can size
4191            // themselves at 1/3 the size of their container. It breaks older apps though,
4192            // specifically apps that use some popular open source libraries.
4193            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4194
4195            // Old versions of the platform would give different results from
4196            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4197            // modes, so we always need to run an additional EXACTLY pass.
4198            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4199
4200            // Prior to N, layout params could change without requiring a
4201            // subsequent call to setLayoutParams() and they would usually
4202            // work. Partial layout breaks this assumption.
4203            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4204
4205            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4206            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4207            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4208
4209            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4210            // in apps so we target check it to avoid breaking existing apps.
4211            sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N;
4212
4213            sCascadedDragDrop = targetSdkVersion < N;
4214
4215            sCompatibilityDone = true;
4216        }
4217    }
4218
4219    /**
4220     * Constructor that is called when inflating a view from XML. This is called
4221     * when a view is being constructed from an XML file, supplying attributes
4222     * that were specified in the XML file. This version uses a default style of
4223     * 0, so the only attribute values applied are those in the Context's Theme
4224     * and the given AttributeSet.
4225     *
4226     * <p>
4227     * The method onFinishInflate() will be called after all children have been
4228     * added.
4229     *
4230     * @param context The Context the view is running in, through which it can
4231     *        access the current theme, resources, etc.
4232     * @param attrs The attributes of the XML tag that is inflating the view.
4233     * @see #View(Context, AttributeSet, int)
4234     */
4235    public View(Context context, @Nullable AttributeSet attrs) {
4236        this(context, attrs, 0);
4237    }
4238
4239    /**
4240     * Perform inflation from XML and apply a class-specific base style from a
4241     * theme attribute. This constructor of View allows subclasses to use their
4242     * own base style when they are inflating. For example, a Button class's
4243     * constructor would call this version of the super class constructor and
4244     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4245     * allows the theme's button style to modify all of the base view attributes
4246     * (in particular its background) as well as the Button class's attributes.
4247     *
4248     * @param context The Context the view is running in, through which it can
4249     *        access the current theme, resources, etc.
4250     * @param attrs The attributes of the XML tag that is inflating the view.
4251     * @param defStyleAttr An attribute in the current theme that contains a
4252     *        reference to a style resource that supplies default values for
4253     *        the view. Can be 0 to not look for defaults.
4254     * @see #View(Context, AttributeSet)
4255     */
4256    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4257        this(context, attrs, defStyleAttr, 0);
4258    }
4259
4260    /**
4261     * Perform inflation from XML and apply a class-specific base style from a
4262     * theme attribute or style resource. This constructor of View allows
4263     * subclasses to use their own base style when they are inflating.
4264     * <p>
4265     * When determining the final value of a particular attribute, there are
4266     * four inputs that come into play:
4267     * <ol>
4268     * <li>Any attribute values in the given AttributeSet.
4269     * <li>The style resource specified in the AttributeSet (named "style").
4270     * <li>The default style specified by <var>defStyleAttr</var>.
4271     * <li>The default style specified by <var>defStyleRes</var>.
4272     * <li>The base values in this theme.
4273     * </ol>
4274     * <p>
4275     * Each of these inputs is considered in-order, with the first listed taking
4276     * precedence over the following ones. In other words, if in the
4277     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4278     * , then the button's text will <em>always</em> be black, regardless of
4279     * what is specified in any of the styles.
4280     *
4281     * @param context The Context the view is running in, through which it can
4282     *        access the current theme, resources, etc.
4283     * @param attrs The attributes of the XML tag that is inflating the view.
4284     * @param defStyleAttr An attribute in the current theme that contains a
4285     *        reference to a style resource that supplies default values for
4286     *        the view. Can be 0 to not look for defaults.
4287     * @param defStyleRes A resource identifier of a style resource that
4288     *        supplies default values for the view, used only if
4289     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4290     *        to not look for defaults.
4291     * @see #View(Context, AttributeSet, int)
4292     */
4293    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4294        this(context);
4295
4296        final TypedArray a = context.obtainStyledAttributes(
4297                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4298
4299        if (mDebugViewAttributes) {
4300            saveAttributeData(attrs, a);
4301        }
4302
4303        Drawable background = null;
4304
4305        int leftPadding = -1;
4306        int topPadding = -1;
4307        int rightPadding = -1;
4308        int bottomPadding = -1;
4309        int startPadding = UNDEFINED_PADDING;
4310        int endPadding = UNDEFINED_PADDING;
4311
4312        int padding = -1;
4313        int paddingHorizontal = -1;
4314        int paddingVertical = -1;
4315
4316        int viewFlagValues = 0;
4317        int viewFlagMasks = 0;
4318
4319        boolean setScrollContainer = false;
4320
4321        int x = 0;
4322        int y = 0;
4323
4324        float tx = 0;
4325        float ty = 0;
4326        float tz = 0;
4327        float elevation = 0;
4328        float rotation = 0;
4329        float rotationX = 0;
4330        float rotationY = 0;
4331        float sx = 1f;
4332        float sy = 1f;
4333        boolean transformSet = false;
4334
4335        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4336        int overScrollMode = mOverScrollMode;
4337        boolean initializeScrollbars = false;
4338        boolean initializeScrollIndicators = false;
4339
4340        boolean startPaddingDefined = false;
4341        boolean endPaddingDefined = false;
4342        boolean leftPaddingDefined = false;
4343        boolean rightPaddingDefined = false;
4344
4345        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4346
4347        // Set default values.
4348        viewFlagValues |= FOCUSABLE_AUTO;
4349        viewFlagMasks |= FOCUSABLE_AUTO;
4350
4351        final int N = a.getIndexCount();
4352        for (int i = 0; i < N; i++) {
4353            int attr = a.getIndex(i);
4354            switch (attr) {
4355                case com.android.internal.R.styleable.View_background:
4356                    background = a.getDrawable(attr);
4357                    break;
4358                case com.android.internal.R.styleable.View_padding:
4359                    padding = a.getDimensionPixelSize(attr, -1);
4360                    mUserPaddingLeftInitial = padding;
4361                    mUserPaddingRightInitial = padding;
4362                    leftPaddingDefined = true;
4363                    rightPaddingDefined = true;
4364                    break;
4365                case com.android.internal.R.styleable.View_paddingHorizontal:
4366                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
4367                    mUserPaddingLeftInitial = paddingHorizontal;
4368                    mUserPaddingRightInitial = paddingHorizontal;
4369                    leftPaddingDefined = true;
4370                    rightPaddingDefined = true;
4371                    break;
4372                case com.android.internal.R.styleable.View_paddingVertical:
4373                    paddingVertical = a.getDimensionPixelSize(attr, -1);
4374                    break;
4375                 case com.android.internal.R.styleable.View_paddingLeft:
4376                    leftPadding = a.getDimensionPixelSize(attr, -1);
4377                    mUserPaddingLeftInitial = leftPadding;
4378                    leftPaddingDefined = true;
4379                    break;
4380                case com.android.internal.R.styleable.View_paddingTop:
4381                    topPadding = a.getDimensionPixelSize(attr, -1);
4382                    break;
4383                case com.android.internal.R.styleable.View_paddingRight:
4384                    rightPadding = a.getDimensionPixelSize(attr, -1);
4385                    mUserPaddingRightInitial = rightPadding;
4386                    rightPaddingDefined = true;
4387                    break;
4388                case com.android.internal.R.styleable.View_paddingBottom:
4389                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4390                    break;
4391                case com.android.internal.R.styleable.View_paddingStart:
4392                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4393                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4394                    break;
4395                case com.android.internal.R.styleable.View_paddingEnd:
4396                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4397                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4398                    break;
4399                case com.android.internal.R.styleable.View_scrollX:
4400                    x = a.getDimensionPixelOffset(attr, 0);
4401                    break;
4402                case com.android.internal.R.styleable.View_scrollY:
4403                    y = a.getDimensionPixelOffset(attr, 0);
4404                    break;
4405                case com.android.internal.R.styleable.View_alpha:
4406                    setAlpha(a.getFloat(attr, 1f));
4407                    break;
4408                case com.android.internal.R.styleable.View_transformPivotX:
4409                    setPivotX(a.getDimension(attr, 0));
4410                    break;
4411                case com.android.internal.R.styleable.View_transformPivotY:
4412                    setPivotY(a.getDimension(attr, 0));
4413                    break;
4414                case com.android.internal.R.styleable.View_translationX:
4415                    tx = a.getDimension(attr, 0);
4416                    transformSet = true;
4417                    break;
4418                case com.android.internal.R.styleable.View_translationY:
4419                    ty = a.getDimension(attr, 0);
4420                    transformSet = true;
4421                    break;
4422                case com.android.internal.R.styleable.View_translationZ:
4423                    tz = a.getDimension(attr, 0);
4424                    transformSet = true;
4425                    break;
4426                case com.android.internal.R.styleable.View_elevation:
4427                    elevation = a.getDimension(attr, 0);
4428                    transformSet = true;
4429                    break;
4430                case com.android.internal.R.styleable.View_rotation:
4431                    rotation = a.getFloat(attr, 0);
4432                    transformSet = true;
4433                    break;
4434                case com.android.internal.R.styleable.View_rotationX:
4435                    rotationX = a.getFloat(attr, 0);
4436                    transformSet = true;
4437                    break;
4438                case com.android.internal.R.styleable.View_rotationY:
4439                    rotationY = a.getFloat(attr, 0);
4440                    transformSet = true;
4441                    break;
4442                case com.android.internal.R.styleable.View_scaleX:
4443                    sx = a.getFloat(attr, 1f);
4444                    transformSet = true;
4445                    break;
4446                case com.android.internal.R.styleable.View_scaleY:
4447                    sy = a.getFloat(attr, 1f);
4448                    transformSet = true;
4449                    break;
4450                case com.android.internal.R.styleable.View_id:
4451                    mID = a.getResourceId(attr, NO_ID);
4452                    break;
4453                case com.android.internal.R.styleable.View_tag:
4454                    mTag = a.getText(attr);
4455                    break;
4456                case com.android.internal.R.styleable.View_fitsSystemWindows:
4457                    if (a.getBoolean(attr, false)) {
4458                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4459                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4460                    }
4461                    break;
4462                case com.android.internal.R.styleable.View_focusable:
4463                    viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
4464                    if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
4465                        viewFlagMasks |= FOCUSABLE_MASK;
4466                    }
4467                    break;
4468                case com.android.internal.R.styleable.View_focusableInTouchMode:
4469                    if (a.getBoolean(attr, false)) {
4470                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4471                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4472                    }
4473                    break;
4474                case com.android.internal.R.styleable.View_clickable:
4475                    if (a.getBoolean(attr, false)) {
4476                        viewFlagValues |= CLICKABLE;
4477                        viewFlagMasks |= CLICKABLE;
4478                    }
4479                    break;
4480                case com.android.internal.R.styleable.View_longClickable:
4481                    if (a.getBoolean(attr, false)) {
4482                        viewFlagValues |= LONG_CLICKABLE;
4483                        viewFlagMasks |= LONG_CLICKABLE;
4484                    }
4485                    break;
4486                case com.android.internal.R.styleable.View_contextClickable:
4487                    if (a.getBoolean(attr, false)) {
4488                        viewFlagValues |= CONTEXT_CLICKABLE;
4489                        viewFlagMasks |= CONTEXT_CLICKABLE;
4490                    }
4491                    break;
4492                case com.android.internal.R.styleable.View_saveEnabled:
4493                    if (!a.getBoolean(attr, true)) {
4494                        viewFlagValues |= SAVE_DISABLED;
4495                        viewFlagMasks |= SAVE_DISABLED_MASK;
4496                    }
4497                    break;
4498                case com.android.internal.R.styleable.View_duplicateParentState:
4499                    if (a.getBoolean(attr, false)) {
4500                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4501                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4502                    }
4503                    break;
4504                case com.android.internal.R.styleable.View_visibility:
4505                    final int visibility = a.getInt(attr, 0);
4506                    if (visibility != 0) {
4507                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4508                        viewFlagMasks |= VISIBILITY_MASK;
4509                    }
4510                    break;
4511                case com.android.internal.R.styleable.View_layoutDirection:
4512                    // Clear any layout direction flags (included resolved bits) already set
4513                    mPrivateFlags2 &=
4514                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4515                    // Set the layout direction flags depending on the value of the attribute
4516                    final int layoutDirection = a.getInt(attr, -1);
4517                    final int value = (layoutDirection != -1) ?
4518                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4519                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4520                    break;
4521                case com.android.internal.R.styleable.View_drawingCacheQuality:
4522                    final int cacheQuality = a.getInt(attr, 0);
4523                    if (cacheQuality != 0) {
4524                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4525                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4526                    }
4527                    break;
4528                case com.android.internal.R.styleable.View_contentDescription:
4529                    setContentDescription(a.getString(attr));
4530                    break;
4531                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4532                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4533                    break;
4534                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4535                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4536                    break;
4537                case com.android.internal.R.styleable.View_labelFor:
4538                    setLabelFor(a.getResourceId(attr, NO_ID));
4539                    break;
4540                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4541                    if (!a.getBoolean(attr, true)) {
4542                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4543                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4544                    }
4545                    break;
4546                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4547                    if (!a.getBoolean(attr, true)) {
4548                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4549                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4550                    }
4551                    break;
4552                case R.styleable.View_scrollbars:
4553                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4554                    if (scrollbars != SCROLLBARS_NONE) {
4555                        viewFlagValues |= scrollbars;
4556                        viewFlagMasks |= SCROLLBARS_MASK;
4557                        initializeScrollbars = true;
4558                    }
4559                    break;
4560                //noinspection deprecation
4561                case R.styleable.View_fadingEdge:
4562                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4563                        // Ignore the attribute starting with ICS
4564                        break;
4565                    }
4566                    // With builds < ICS, fall through and apply fading edges
4567                case R.styleable.View_requiresFadingEdge:
4568                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4569                    if (fadingEdge != FADING_EDGE_NONE) {
4570                        viewFlagValues |= fadingEdge;
4571                        viewFlagMasks |= FADING_EDGE_MASK;
4572                        initializeFadingEdgeInternal(a);
4573                    }
4574                    break;
4575                case R.styleable.View_scrollbarStyle:
4576                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4577                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4578                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4579                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4580                    }
4581                    break;
4582                case R.styleable.View_isScrollContainer:
4583                    setScrollContainer = true;
4584                    if (a.getBoolean(attr, false)) {
4585                        setScrollContainer(true);
4586                    }
4587                    break;
4588                case com.android.internal.R.styleable.View_keepScreenOn:
4589                    if (a.getBoolean(attr, false)) {
4590                        viewFlagValues |= KEEP_SCREEN_ON;
4591                        viewFlagMasks |= KEEP_SCREEN_ON;
4592                    }
4593                    break;
4594                case R.styleable.View_filterTouchesWhenObscured:
4595                    if (a.getBoolean(attr, false)) {
4596                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4597                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4598                    }
4599                    break;
4600                case R.styleable.View_nextFocusLeft:
4601                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4602                    break;
4603                case R.styleable.View_nextFocusRight:
4604                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4605                    break;
4606                case R.styleable.View_nextFocusUp:
4607                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4608                    break;
4609                case R.styleable.View_nextFocusDown:
4610                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4611                    break;
4612                case R.styleable.View_nextFocusForward:
4613                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4614                    break;
4615                case R.styleable.View_nextClusterForward:
4616                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
4617                    break;
4618                case R.styleable.View_minWidth:
4619                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4620                    break;
4621                case R.styleable.View_minHeight:
4622                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4623                    break;
4624                case R.styleable.View_onClick:
4625                    if (context.isRestricted()) {
4626                        throw new IllegalStateException("The android:onClick attribute cannot "
4627                                + "be used within a restricted context");
4628                    }
4629
4630                    final String handlerName = a.getString(attr);
4631                    if (handlerName != null) {
4632                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4633                    }
4634                    break;
4635                case R.styleable.View_overScrollMode:
4636                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4637                    break;
4638                case R.styleable.View_verticalScrollbarPosition:
4639                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4640                    break;
4641                case R.styleable.View_layerType:
4642                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4643                    break;
4644                case R.styleable.View_textDirection:
4645                    // Clear any text direction flag already set
4646                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4647                    // Set the text direction flags depending on the value of the attribute
4648                    final int textDirection = a.getInt(attr, -1);
4649                    if (textDirection != -1) {
4650                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4651                    }
4652                    break;
4653                case R.styleable.View_textAlignment:
4654                    // Clear any text alignment flag already set
4655                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4656                    // Set the text alignment flag depending on the value of the attribute
4657                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4658                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4659                    break;
4660                case R.styleable.View_importantForAccessibility:
4661                    setImportantForAccessibility(a.getInt(attr,
4662                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4663                    break;
4664                case R.styleable.View_accessibilityLiveRegion:
4665                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4666                    break;
4667                case R.styleable.View_transitionName:
4668                    setTransitionName(a.getString(attr));
4669                    break;
4670                case R.styleable.View_nestedScrollingEnabled:
4671                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4672                    break;
4673                case R.styleable.View_stateListAnimator:
4674                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4675                            a.getResourceId(attr, 0)));
4676                    break;
4677                case R.styleable.View_backgroundTint:
4678                    // This will get applied later during setBackground().
4679                    if (mBackgroundTint == null) {
4680                        mBackgroundTint = new TintInfo();
4681                    }
4682                    mBackgroundTint.mTintList = a.getColorStateList(
4683                            R.styleable.View_backgroundTint);
4684                    mBackgroundTint.mHasTintList = true;
4685                    break;
4686                case R.styleable.View_backgroundTintMode:
4687                    // This will get applied later during setBackground().
4688                    if (mBackgroundTint == null) {
4689                        mBackgroundTint = new TintInfo();
4690                    }
4691                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4692                            R.styleable.View_backgroundTintMode, -1), null);
4693                    mBackgroundTint.mHasTintMode = true;
4694                    break;
4695                case R.styleable.View_outlineProvider:
4696                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4697                            PROVIDER_BACKGROUND));
4698                    break;
4699                case R.styleable.View_foreground:
4700                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4701                        setForeground(a.getDrawable(attr));
4702                    }
4703                    break;
4704                case R.styleable.View_foregroundGravity:
4705                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4706                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4707                    }
4708                    break;
4709                case R.styleable.View_foregroundTintMode:
4710                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4711                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4712                    }
4713                    break;
4714                case R.styleable.View_foregroundTint:
4715                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4716                        setForegroundTintList(a.getColorStateList(attr));
4717                    }
4718                    break;
4719                case R.styleable.View_foregroundInsidePadding:
4720                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4721                        if (mForegroundInfo == null) {
4722                            mForegroundInfo = new ForegroundInfo();
4723                        }
4724                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4725                                mForegroundInfo.mInsidePadding);
4726                    }
4727                    break;
4728                case R.styleable.View_scrollIndicators:
4729                    final int scrollIndicators =
4730                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4731                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4732                    if (scrollIndicators != 0) {
4733                        mPrivateFlags3 |= scrollIndicators;
4734                        initializeScrollIndicators = true;
4735                    }
4736                    break;
4737                case R.styleable.View_pointerIcon:
4738                    final int resourceId = a.getResourceId(attr, 0);
4739                    if (resourceId != 0) {
4740                        setPointerIcon(PointerIcon.load(
4741                                context.getResources(), resourceId));
4742                    } else {
4743                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4744                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4745                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4746                        }
4747                    }
4748                    break;
4749                case R.styleable.View_forceHasOverlappingRendering:
4750                    if (a.peekValue(attr) != null) {
4751                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4752                    }
4753                    break;
4754                case R.styleable.View_tooltipText:
4755                    setTooltipText(a.getText(attr));
4756                    break;
4757                case R.styleable.View_keyboardNavigationCluster:
4758                    if (a.peekValue(attr) != null) {
4759                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
4760                    }
4761                    break;
4762                case R.styleable.View_focusedByDefault:
4763                    if (a.peekValue(attr) != null) {
4764                        setFocusedByDefault(a.getBoolean(attr, true));
4765                    }
4766                    break;
4767            }
4768        }
4769
4770        setOverScrollMode(overScrollMode);
4771
4772        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4773        // the resolved layout direction). Those cached values will be used later during padding
4774        // resolution.
4775        mUserPaddingStart = startPadding;
4776        mUserPaddingEnd = endPadding;
4777
4778        if (background != null) {
4779            setBackground(background);
4780        }
4781
4782        // setBackground above will record that padding is currently provided by the background.
4783        // If we have padding specified via xml, record that here instead and use it.
4784        mLeftPaddingDefined = leftPaddingDefined;
4785        mRightPaddingDefined = rightPaddingDefined;
4786
4787        if (padding >= 0) {
4788            leftPadding = padding;
4789            topPadding = padding;
4790            rightPadding = padding;
4791            bottomPadding = padding;
4792            mUserPaddingLeftInitial = padding;
4793            mUserPaddingRightInitial = padding;
4794        } else {
4795            if (paddingHorizontal >= 0) {
4796                leftPadding = paddingHorizontal;
4797                rightPadding = paddingHorizontal;
4798                mUserPaddingLeftInitial = paddingHorizontal;
4799                mUserPaddingRightInitial = paddingHorizontal;
4800            }
4801            if (paddingVertical >= 0) {
4802                topPadding = paddingVertical;
4803                bottomPadding = paddingVertical;
4804            }
4805        }
4806
4807        if (isRtlCompatibilityMode()) {
4808            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4809            // left / right padding are used if defined (meaning here nothing to do). If they are not
4810            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4811            // start / end and resolve them as left / right (layout direction is not taken into account).
4812            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4813            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4814            // defined.
4815            if (!mLeftPaddingDefined && startPaddingDefined) {
4816                leftPadding = startPadding;
4817            }
4818            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4819            if (!mRightPaddingDefined && endPaddingDefined) {
4820                rightPadding = endPadding;
4821            }
4822            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4823        } else {
4824            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4825            // values defined. Otherwise, left /right values are used.
4826            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4827            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4828            // defined.
4829            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4830
4831            if (mLeftPaddingDefined && !hasRelativePadding) {
4832                mUserPaddingLeftInitial = leftPadding;
4833            }
4834            if (mRightPaddingDefined && !hasRelativePadding) {
4835                mUserPaddingRightInitial = rightPadding;
4836            }
4837        }
4838
4839        internalSetPadding(
4840                mUserPaddingLeftInitial,
4841                topPadding >= 0 ? topPadding : mPaddingTop,
4842                mUserPaddingRightInitial,
4843                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4844
4845        if (viewFlagMasks != 0) {
4846            setFlags(viewFlagValues, viewFlagMasks);
4847        }
4848
4849        if (initializeScrollbars) {
4850            initializeScrollbarsInternal(a);
4851        }
4852
4853        if (initializeScrollIndicators) {
4854            initializeScrollIndicatorsInternal();
4855        }
4856
4857        a.recycle();
4858
4859        // Needs to be called after mViewFlags is set
4860        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4861            recomputePadding();
4862        }
4863
4864        if (x != 0 || y != 0) {
4865            scrollTo(x, y);
4866        }
4867
4868        if (transformSet) {
4869            setTranslationX(tx);
4870            setTranslationY(ty);
4871            setTranslationZ(tz);
4872            setElevation(elevation);
4873            setRotation(rotation);
4874            setRotationX(rotationX);
4875            setRotationY(rotationY);
4876            setScaleX(sx);
4877            setScaleY(sy);
4878        }
4879
4880        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4881            setScrollContainer(true);
4882        }
4883
4884        computeOpaqueFlags();
4885    }
4886
4887    /**
4888     * An implementation of OnClickListener that attempts to lazily load a
4889     * named click handling method from a parent or ancestor context.
4890     */
4891    private static class DeclaredOnClickListener implements OnClickListener {
4892        private final View mHostView;
4893        private final String mMethodName;
4894
4895        private Method mResolvedMethod;
4896        private Context mResolvedContext;
4897
4898        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4899            mHostView = hostView;
4900            mMethodName = methodName;
4901        }
4902
4903        @Override
4904        public void onClick(@NonNull View v) {
4905            if (mResolvedMethod == null) {
4906                resolveMethod(mHostView.getContext(), mMethodName);
4907            }
4908
4909            try {
4910                mResolvedMethod.invoke(mResolvedContext, v);
4911            } catch (IllegalAccessException e) {
4912                throw new IllegalStateException(
4913                        "Could not execute non-public method for android:onClick", e);
4914            } catch (InvocationTargetException e) {
4915                throw new IllegalStateException(
4916                        "Could not execute method for android:onClick", e);
4917            }
4918        }
4919
4920        @NonNull
4921        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4922            while (context != null) {
4923                try {
4924                    if (!context.isRestricted()) {
4925                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4926                        if (method != null) {
4927                            mResolvedMethod = method;
4928                            mResolvedContext = context;
4929                            return;
4930                        }
4931                    }
4932                } catch (NoSuchMethodException e) {
4933                    // Failed to find method, keep searching up the hierarchy.
4934                }
4935
4936                if (context instanceof ContextWrapper) {
4937                    context = ((ContextWrapper) context).getBaseContext();
4938                } else {
4939                    // Can't search up the hierarchy, null out and fail.
4940                    context = null;
4941                }
4942            }
4943
4944            final int id = mHostView.getId();
4945            final String idText = id == NO_ID ? "" : " with id '"
4946                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4947            throw new IllegalStateException("Could not find method " + mMethodName
4948                    + "(View) in a parent or ancestor Context for android:onClick "
4949                    + "attribute defined on view " + mHostView.getClass() + idText);
4950        }
4951    }
4952
4953    /**
4954     * Non-public constructor for use in testing
4955     */
4956    View() {
4957        mResources = null;
4958        mRenderNode = RenderNode.create(getClass().getName(), this);
4959    }
4960
4961    final boolean debugDraw() {
4962        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
4963    }
4964
4965    private static SparseArray<String> getAttributeMap() {
4966        if (mAttributeMap == null) {
4967            mAttributeMap = new SparseArray<>();
4968        }
4969        return mAttributeMap;
4970    }
4971
4972    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4973        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4974        final int indexCount = t.getIndexCount();
4975        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4976
4977        int i = 0;
4978
4979        // Store raw XML attributes.
4980        for (int j = 0; j < attrsCount; ++j) {
4981            attributes[i] = attrs.getAttributeName(j);
4982            attributes[i + 1] = attrs.getAttributeValue(j);
4983            i += 2;
4984        }
4985
4986        // Store resolved styleable attributes.
4987        final Resources res = t.getResources();
4988        final SparseArray<String> attributeMap = getAttributeMap();
4989        for (int j = 0; j < indexCount; ++j) {
4990            final int index = t.getIndex(j);
4991            if (!t.hasValueOrEmpty(index)) {
4992                // Value is undefined. Skip it.
4993                continue;
4994            }
4995
4996            final int resourceId = t.getResourceId(index, 0);
4997            if (resourceId == 0) {
4998                // Value is not a reference. Skip it.
4999                continue;
5000            }
5001
5002            String resourceName = attributeMap.get(resourceId);
5003            if (resourceName == null) {
5004                try {
5005                    resourceName = res.getResourceName(resourceId);
5006                } catch (Resources.NotFoundException e) {
5007                    resourceName = "0x" + Integer.toHexString(resourceId);
5008                }
5009                attributeMap.put(resourceId, resourceName);
5010            }
5011
5012            attributes[i] = resourceName;
5013            attributes[i + 1] = t.getString(index);
5014            i += 2;
5015        }
5016
5017        // Trim to fit contents.
5018        final String[] trimmed = new String[i];
5019        System.arraycopy(attributes, 0, trimmed, 0, i);
5020        mAttributes = trimmed;
5021    }
5022
5023    public String toString() {
5024        StringBuilder out = new StringBuilder(128);
5025        out.append(getClass().getName());
5026        out.append('{');
5027        out.append(Integer.toHexString(System.identityHashCode(this)));
5028        out.append(' ');
5029        switch (mViewFlags&VISIBILITY_MASK) {
5030            case VISIBLE: out.append('V'); break;
5031            case INVISIBLE: out.append('I'); break;
5032            case GONE: out.append('G'); break;
5033            default: out.append('.'); break;
5034        }
5035        out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.');
5036        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
5037        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
5038        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
5039        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
5040        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
5041        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
5042        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
5043        out.append(' ');
5044        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
5045        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
5046        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
5047        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
5048            out.append('p');
5049        } else {
5050            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5051        }
5052        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5053        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5054        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5055        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5056        out.append(' ');
5057        out.append(mLeft);
5058        out.append(',');
5059        out.append(mTop);
5060        out.append('-');
5061        out.append(mRight);
5062        out.append(',');
5063        out.append(mBottom);
5064        final int id = getId();
5065        if (id != NO_ID) {
5066            out.append(" #");
5067            out.append(Integer.toHexString(id));
5068            final Resources r = mResources;
5069            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5070                try {
5071                    String pkgname;
5072                    switch (id&0xff000000) {
5073                        case 0x7f000000:
5074                            pkgname="app";
5075                            break;
5076                        case 0x01000000:
5077                            pkgname="android";
5078                            break;
5079                        default:
5080                            pkgname = r.getResourcePackageName(id);
5081                            break;
5082                    }
5083                    String typename = r.getResourceTypeName(id);
5084                    String entryname = r.getResourceEntryName(id);
5085                    out.append(" ");
5086                    out.append(pkgname);
5087                    out.append(":");
5088                    out.append(typename);
5089                    out.append("/");
5090                    out.append(entryname);
5091                } catch (Resources.NotFoundException e) {
5092                }
5093            }
5094        }
5095        out.append("}");
5096        return out.toString();
5097    }
5098
5099    /**
5100     * <p>
5101     * Initializes the fading edges from a given set of styled attributes. This
5102     * method should be called by subclasses that need fading edges and when an
5103     * instance of these subclasses is created programmatically rather than
5104     * being inflated from XML. This method is automatically called when the XML
5105     * is inflated.
5106     * </p>
5107     *
5108     * @param a the styled attributes set to initialize the fading edges from
5109     *
5110     * @removed
5111     */
5112    protected void initializeFadingEdge(TypedArray a) {
5113        // This method probably shouldn't have been included in the SDK to begin with.
5114        // It relies on 'a' having been initialized using an attribute filter array that is
5115        // not publicly available to the SDK. The old method has been renamed
5116        // to initializeFadingEdgeInternal and hidden for framework use only;
5117        // this one initializes using defaults to make it safe to call for apps.
5118
5119        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5120
5121        initializeFadingEdgeInternal(arr);
5122
5123        arr.recycle();
5124    }
5125
5126    /**
5127     * <p>
5128     * Initializes the fading edges from a given set of styled attributes. This
5129     * method should be called by subclasses that need fading edges and when an
5130     * instance of these subclasses is created programmatically rather than
5131     * being inflated from XML. This method is automatically called when the XML
5132     * is inflated.
5133     * </p>
5134     *
5135     * @param a the styled attributes set to initialize the fading edges from
5136     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5137     */
5138    protected void initializeFadingEdgeInternal(TypedArray a) {
5139        initScrollCache();
5140
5141        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5142                R.styleable.View_fadingEdgeLength,
5143                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5144    }
5145
5146    /**
5147     * Returns the size of the vertical faded edges used to indicate that more
5148     * content in this view is visible.
5149     *
5150     * @return The size in pixels of the vertical faded edge or 0 if vertical
5151     *         faded edges are not enabled for this view.
5152     * @attr ref android.R.styleable#View_fadingEdgeLength
5153     */
5154    public int getVerticalFadingEdgeLength() {
5155        if (isVerticalFadingEdgeEnabled()) {
5156            ScrollabilityCache cache = mScrollCache;
5157            if (cache != null) {
5158                return cache.fadingEdgeLength;
5159            }
5160        }
5161        return 0;
5162    }
5163
5164    /**
5165     * Set the size of the faded edge used to indicate that more content in this
5166     * view is available.  Will not change whether the fading edge is enabled; use
5167     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5168     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5169     * for the vertical or horizontal fading edges.
5170     *
5171     * @param length The size in pixels of the faded edge used to indicate that more
5172     *        content in this view is visible.
5173     */
5174    public void setFadingEdgeLength(int length) {
5175        initScrollCache();
5176        mScrollCache.fadingEdgeLength = length;
5177    }
5178
5179    /**
5180     * Returns the size of the horizontal faded edges used to indicate that more
5181     * content in this view is visible.
5182     *
5183     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5184     *         faded edges are not enabled for this view.
5185     * @attr ref android.R.styleable#View_fadingEdgeLength
5186     */
5187    public int getHorizontalFadingEdgeLength() {
5188        if (isHorizontalFadingEdgeEnabled()) {
5189            ScrollabilityCache cache = mScrollCache;
5190            if (cache != null) {
5191                return cache.fadingEdgeLength;
5192            }
5193        }
5194        return 0;
5195    }
5196
5197    /**
5198     * Returns the width of the vertical scrollbar.
5199     *
5200     * @return The width in pixels of the vertical scrollbar or 0 if there
5201     *         is no vertical scrollbar.
5202     */
5203    public int getVerticalScrollbarWidth() {
5204        ScrollabilityCache cache = mScrollCache;
5205        if (cache != null) {
5206            ScrollBarDrawable scrollBar = cache.scrollBar;
5207            if (scrollBar != null) {
5208                int size = scrollBar.getSize(true);
5209                if (size <= 0) {
5210                    size = cache.scrollBarSize;
5211                }
5212                return size;
5213            }
5214            return 0;
5215        }
5216        return 0;
5217    }
5218
5219    /**
5220     * Returns the height of the horizontal scrollbar.
5221     *
5222     * @return The height in pixels of the horizontal scrollbar or 0 if
5223     *         there is no horizontal scrollbar.
5224     */
5225    protected int getHorizontalScrollbarHeight() {
5226        ScrollabilityCache cache = mScrollCache;
5227        if (cache != null) {
5228            ScrollBarDrawable scrollBar = cache.scrollBar;
5229            if (scrollBar != null) {
5230                int size = scrollBar.getSize(false);
5231                if (size <= 0) {
5232                    size = cache.scrollBarSize;
5233                }
5234                return size;
5235            }
5236            return 0;
5237        }
5238        return 0;
5239    }
5240
5241    /**
5242     * <p>
5243     * Initializes the scrollbars from a given set of styled attributes. This
5244     * method should be called by subclasses that need scrollbars and when an
5245     * instance of these subclasses is created programmatically rather than
5246     * being inflated from XML. This method is automatically called when the XML
5247     * is inflated.
5248     * </p>
5249     *
5250     * @param a the styled attributes set to initialize the scrollbars from
5251     *
5252     * @removed
5253     */
5254    protected void initializeScrollbars(TypedArray a) {
5255        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5256        // using the View filter array which is not available to the SDK. As such, internal
5257        // framework usage now uses initializeScrollbarsInternal and we grab a default
5258        // TypedArray with the right filter instead here.
5259        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5260
5261        initializeScrollbarsInternal(arr);
5262
5263        // We ignored the method parameter. Recycle the one we actually did use.
5264        arr.recycle();
5265    }
5266
5267    /**
5268     * <p>
5269     * Initializes the scrollbars from a given set of styled attributes. This
5270     * method should be called by subclasses that need scrollbars and when an
5271     * instance of these subclasses is created programmatically rather than
5272     * being inflated from XML. This method is automatically called when the XML
5273     * is inflated.
5274     * </p>
5275     *
5276     * @param a the styled attributes set to initialize the scrollbars from
5277     * @hide
5278     */
5279    protected void initializeScrollbarsInternal(TypedArray a) {
5280        initScrollCache();
5281
5282        final ScrollabilityCache scrollabilityCache = mScrollCache;
5283
5284        if (scrollabilityCache.scrollBar == null) {
5285            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5286            scrollabilityCache.scrollBar.setState(getDrawableState());
5287            scrollabilityCache.scrollBar.setCallback(this);
5288        }
5289
5290        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5291
5292        if (!fadeScrollbars) {
5293            scrollabilityCache.state = ScrollabilityCache.ON;
5294        }
5295        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5296
5297
5298        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5299                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5300                        .getScrollBarFadeDuration());
5301        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5302                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5303                ViewConfiguration.getScrollDefaultDelay());
5304
5305
5306        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5307                com.android.internal.R.styleable.View_scrollbarSize,
5308                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5309
5310        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5311        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5312
5313        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5314        if (thumb != null) {
5315            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5316        }
5317
5318        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5319                false);
5320        if (alwaysDraw) {
5321            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5322        }
5323
5324        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5325        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5326
5327        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5328        if (thumb != null) {
5329            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5330        }
5331
5332        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5333                false);
5334        if (alwaysDraw) {
5335            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5336        }
5337
5338        // Apply layout direction to the new Drawables if needed
5339        final int layoutDirection = getLayoutDirection();
5340        if (track != null) {
5341            track.setLayoutDirection(layoutDirection);
5342        }
5343        if (thumb != null) {
5344            thumb.setLayoutDirection(layoutDirection);
5345        }
5346
5347        // Re-apply user/background padding so that scrollbar(s) get added
5348        resolvePadding();
5349    }
5350
5351    private void initializeScrollIndicatorsInternal() {
5352        // Some day maybe we'll break this into top/left/start/etc. and let the
5353        // client control it. Until then, you can have any scroll indicator you
5354        // want as long as it's a 1dp foreground-colored rectangle.
5355        if (mScrollIndicatorDrawable == null) {
5356            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5357        }
5358    }
5359
5360    /**
5361     * <p>
5362     * Initalizes the scrollability cache if necessary.
5363     * </p>
5364     */
5365    private void initScrollCache() {
5366        if (mScrollCache == null) {
5367            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5368        }
5369    }
5370
5371    private ScrollabilityCache getScrollCache() {
5372        initScrollCache();
5373        return mScrollCache;
5374    }
5375
5376    /**
5377     * Set the position of the vertical scroll bar. Should be one of
5378     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5379     * {@link #SCROLLBAR_POSITION_RIGHT}.
5380     *
5381     * @param position Where the vertical scroll bar should be positioned.
5382     */
5383    public void setVerticalScrollbarPosition(int position) {
5384        if (mVerticalScrollbarPosition != position) {
5385            mVerticalScrollbarPosition = position;
5386            computeOpaqueFlags();
5387            resolvePadding();
5388        }
5389    }
5390
5391    /**
5392     * @return The position where the vertical scroll bar will show, if applicable.
5393     * @see #setVerticalScrollbarPosition(int)
5394     */
5395    public int getVerticalScrollbarPosition() {
5396        return mVerticalScrollbarPosition;
5397    }
5398
5399    boolean isOnScrollbar(float x, float y) {
5400        if (mScrollCache == null) {
5401            return false;
5402        }
5403        x += getScrollX();
5404        y += getScrollY();
5405        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5406            final Rect bounds = mScrollCache.mScrollBarBounds;
5407            getVerticalScrollBarBounds(bounds);
5408            if (bounds.contains((int)x, (int)y)) {
5409                return true;
5410            }
5411        }
5412        if (isHorizontalScrollBarEnabled()) {
5413            final Rect bounds = mScrollCache.mScrollBarBounds;
5414            getHorizontalScrollBarBounds(bounds);
5415            if (bounds.contains((int)x, (int)y)) {
5416                return true;
5417            }
5418        }
5419        return false;
5420    }
5421
5422    boolean isOnScrollbarThumb(float x, float y) {
5423        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5424    }
5425
5426    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5427        if (mScrollCache == null) {
5428            return false;
5429        }
5430        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5431            x += getScrollX();
5432            y += getScrollY();
5433            final Rect bounds = mScrollCache.mScrollBarBounds;
5434            getVerticalScrollBarBounds(bounds);
5435            final int range = computeVerticalScrollRange();
5436            final int offset = computeVerticalScrollOffset();
5437            final int extent = computeVerticalScrollExtent();
5438            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5439                    extent, range);
5440            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5441                    extent, range, offset);
5442            final int thumbTop = bounds.top + thumbOffset;
5443            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5444                    && y <= thumbTop + thumbLength) {
5445                return true;
5446            }
5447        }
5448        return false;
5449    }
5450
5451    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5452        if (mScrollCache == null) {
5453            return false;
5454        }
5455        if (isHorizontalScrollBarEnabled()) {
5456            x += getScrollX();
5457            y += getScrollY();
5458            final Rect bounds = mScrollCache.mScrollBarBounds;
5459            getHorizontalScrollBarBounds(bounds);
5460            final int range = computeHorizontalScrollRange();
5461            final int offset = computeHorizontalScrollOffset();
5462            final int extent = computeHorizontalScrollExtent();
5463            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5464                    extent, range);
5465            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5466                    extent, range, offset);
5467            final int thumbLeft = bounds.left + thumbOffset;
5468            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5469                    && y <= bounds.bottom) {
5470                return true;
5471            }
5472        }
5473        return false;
5474    }
5475
5476    boolean isDraggingScrollBar() {
5477        return mScrollCache != null
5478                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5479    }
5480
5481    /**
5482     * Sets the state of all scroll indicators.
5483     * <p>
5484     * See {@link #setScrollIndicators(int, int)} for usage information.
5485     *
5486     * @param indicators a bitmask of indicators that should be enabled, or
5487     *                   {@code 0} to disable all indicators
5488     * @see #setScrollIndicators(int, int)
5489     * @see #getScrollIndicators()
5490     * @attr ref android.R.styleable#View_scrollIndicators
5491     */
5492    public void setScrollIndicators(@ScrollIndicators int indicators) {
5493        setScrollIndicators(indicators,
5494                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5495    }
5496
5497    /**
5498     * Sets the state of the scroll indicators specified by the mask. To change
5499     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5500     * <p>
5501     * When a scroll indicator is enabled, it will be displayed if the view
5502     * can scroll in the direction of the indicator.
5503     * <p>
5504     * Multiple indicator types may be enabled or disabled by passing the
5505     * logical OR of the desired types. If multiple types are specified, they
5506     * will all be set to the same enabled state.
5507     * <p>
5508     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5509     *
5510     * @param indicators the indicator direction, or the logical OR of multiple
5511     *             indicator directions. One or more of:
5512     *             <ul>
5513     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5514     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5515     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5516     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5517     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5518     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5519     *             </ul>
5520     * @see #setScrollIndicators(int)
5521     * @see #getScrollIndicators()
5522     * @attr ref android.R.styleable#View_scrollIndicators
5523     */
5524    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5525        // Shift and sanitize mask.
5526        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5527        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5528
5529        // Shift and mask indicators.
5530        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5531        indicators &= mask;
5532
5533        // Merge with non-masked flags.
5534        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5535
5536        if (mPrivateFlags3 != updatedFlags) {
5537            mPrivateFlags3 = updatedFlags;
5538
5539            if (indicators != 0) {
5540                initializeScrollIndicatorsInternal();
5541            }
5542            invalidate();
5543        }
5544    }
5545
5546    /**
5547     * Returns a bitmask representing the enabled scroll indicators.
5548     * <p>
5549     * For example, if the top and left scroll indicators are enabled and all
5550     * other indicators are disabled, the return value will be
5551     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5552     * <p>
5553     * To check whether the bottom scroll indicator is enabled, use the value
5554     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5555     *
5556     * @return a bitmask representing the enabled scroll indicators
5557     */
5558    @ScrollIndicators
5559    public int getScrollIndicators() {
5560        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5561                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5562    }
5563
5564    ListenerInfo getListenerInfo() {
5565        if (mListenerInfo != null) {
5566            return mListenerInfo;
5567        }
5568        mListenerInfo = new ListenerInfo();
5569        return mListenerInfo;
5570    }
5571
5572    /**
5573     * Register a callback to be invoked when the scroll X or Y positions of
5574     * this view change.
5575     * <p>
5576     * <b>Note:</b> Some views handle scrolling independently from View and may
5577     * have their own separate listeners for scroll-type events. For example,
5578     * {@link android.widget.ListView ListView} allows clients to register an
5579     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5580     * to listen for changes in list scroll position.
5581     *
5582     * @param l The listener to notify when the scroll X or Y position changes.
5583     * @see android.view.View#getScrollX()
5584     * @see android.view.View#getScrollY()
5585     */
5586    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5587        getListenerInfo().mOnScrollChangeListener = l;
5588    }
5589
5590    /**
5591     * Register a callback to be invoked when focus of this view changed.
5592     *
5593     * @param l The callback that will run.
5594     */
5595    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5596        getListenerInfo().mOnFocusChangeListener = l;
5597    }
5598
5599    /**
5600     * Add a listener that will be called when the bounds of the view change due to
5601     * layout processing.
5602     *
5603     * @param listener The listener that will be called when layout bounds change.
5604     */
5605    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5606        ListenerInfo li = getListenerInfo();
5607        if (li.mOnLayoutChangeListeners == null) {
5608            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5609        }
5610        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5611            li.mOnLayoutChangeListeners.add(listener);
5612        }
5613    }
5614
5615    /**
5616     * Remove a listener for layout changes.
5617     *
5618     * @param listener The listener for layout bounds change.
5619     */
5620    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5621        ListenerInfo li = mListenerInfo;
5622        if (li == null || li.mOnLayoutChangeListeners == null) {
5623            return;
5624        }
5625        li.mOnLayoutChangeListeners.remove(listener);
5626    }
5627
5628    /**
5629     * Add a listener for attach state changes.
5630     *
5631     * This listener will be called whenever this view is attached or detached
5632     * from a window. Remove the listener using
5633     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5634     *
5635     * @param listener Listener to attach
5636     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5637     */
5638    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5639        ListenerInfo li = getListenerInfo();
5640        if (li.mOnAttachStateChangeListeners == null) {
5641            li.mOnAttachStateChangeListeners
5642                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5643        }
5644        li.mOnAttachStateChangeListeners.add(listener);
5645    }
5646
5647    /**
5648     * Remove a listener for attach state changes. The listener will receive no further
5649     * notification of window attach/detach events.
5650     *
5651     * @param listener Listener to remove
5652     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5653     */
5654    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5655        ListenerInfo li = mListenerInfo;
5656        if (li == null || li.mOnAttachStateChangeListeners == null) {
5657            return;
5658        }
5659        li.mOnAttachStateChangeListeners.remove(listener);
5660    }
5661
5662    /**
5663     * Returns the focus-change callback registered for this view.
5664     *
5665     * @return The callback, or null if one is not registered.
5666     */
5667    public OnFocusChangeListener getOnFocusChangeListener() {
5668        ListenerInfo li = mListenerInfo;
5669        return li != null ? li.mOnFocusChangeListener : null;
5670    }
5671
5672    /**
5673     * Register a callback to be invoked when this view is clicked. If this view is not
5674     * clickable, it becomes clickable.
5675     *
5676     * @param l The callback that will run
5677     *
5678     * @see #setClickable(boolean)
5679     */
5680    public void setOnClickListener(@Nullable OnClickListener l) {
5681        if (!isClickable()) {
5682            setClickable(true);
5683        }
5684        getListenerInfo().mOnClickListener = l;
5685    }
5686
5687    /**
5688     * Return whether this view has an attached OnClickListener.  Returns
5689     * true if there is a listener, false if there is none.
5690     */
5691    public boolean hasOnClickListeners() {
5692        ListenerInfo li = mListenerInfo;
5693        return (li != null && li.mOnClickListener != null);
5694    }
5695
5696    /**
5697     * Register a callback to be invoked when this view is clicked and held. If this view is not
5698     * long clickable, it becomes long clickable.
5699     *
5700     * @param l The callback that will run
5701     *
5702     * @see #setLongClickable(boolean)
5703     */
5704    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5705        if (!isLongClickable()) {
5706            setLongClickable(true);
5707        }
5708        getListenerInfo().mOnLongClickListener = l;
5709    }
5710
5711    /**
5712     * Register a callback to be invoked when this view is context clicked. If the view is not
5713     * context clickable, it becomes context clickable.
5714     *
5715     * @param l The callback that will run
5716     * @see #setContextClickable(boolean)
5717     */
5718    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5719        if (!isContextClickable()) {
5720            setContextClickable(true);
5721        }
5722        getListenerInfo().mOnContextClickListener = l;
5723    }
5724
5725    /**
5726     * Register a callback to be invoked when the context menu for this view is
5727     * being built. If this view is not long clickable, it becomes long clickable.
5728     *
5729     * @param l The callback that will run
5730     *
5731     */
5732    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5733        if (!isLongClickable()) {
5734            setLongClickable(true);
5735        }
5736        getListenerInfo().mOnCreateContextMenuListener = l;
5737    }
5738
5739    /**
5740     * Set an observer to collect stats for each frame rendered for this view.
5741     *
5742     * @hide
5743     */
5744    public void addFrameMetricsListener(Window window,
5745            Window.OnFrameMetricsAvailableListener listener,
5746            Handler handler) {
5747        if (mAttachInfo != null) {
5748            if (mAttachInfo.mThreadedRenderer != null) {
5749                if (mFrameMetricsObservers == null) {
5750                    mFrameMetricsObservers = new ArrayList<>();
5751                }
5752
5753                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5754                        handler.getLooper(), listener);
5755                mFrameMetricsObservers.add(fmo);
5756                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
5757            } else {
5758                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5759            }
5760        } else {
5761            if (mFrameMetricsObservers == null) {
5762                mFrameMetricsObservers = new ArrayList<>();
5763            }
5764
5765            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5766                    handler.getLooper(), listener);
5767            mFrameMetricsObservers.add(fmo);
5768        }
5769    }
5770
5771    /**
5772     * Remove observer configured to collect frame stats for this view.
5773     *
5774     * @hide
5775     */
5776    public void removeFrameMetricsListener(
5777            Window.OnFrameMetricsAvailableListener listener) {
5778        ThreadedRenderer renderer = getThreadedRenderer();
5779        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5780        if (fmo == null) {
5781            throw new IllegalArgumentException(
5782                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5783        }
5784
5785        if (mFrameMetricsObservers != null) {
5786            mFrameMetricsObservers.remove(fmo);
5787            if (renderer != null) {
5788                renderer.removeFrameMetricsObserver(fmo);
5789            }
5790        }
5791    }
5792
5793    private void registerPendingFrameMetricsObservers() {
5794        if (mFrameMetricsObservers != null) {
5795            ThreadedRenderer renderer = getThreadedRenderer();
5796            if (renderer != null) {
5797                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5798                    renderer.addFrameMetricsObserver(fmo);
5799                }
5800            } else {
5801                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5802            }
5803        }
5804    }
5805
5806    private FrameMetricsObserver findFrameMetricsObserver(
5807            Window.OnFrameMetricsAvailableListener listener) {
5808        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5809            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5810            if (observer.mListener == listener) {
5811                return observer;
5812            }
5813        }
5814
5815        return null;
5816    }
5817
5818    /**
5819     * Call this view's OnClickListener, if it is defined.  Performs all normal
5820     * actions associated with clicking: reporting accessibility event, playing
5821     * a sound, etc.
5822     *
5823     * @return True there was an assigned OnClickListener that was called, false
5824     *         otherwise is returned.
5825     */
5826    public boolean performClick() {
5827        final boolean result;
5828        final ListenerInfo li = mListenerInfo;
5829        if (li != null && li.mOnClickListener != null) {
5830            playSoundEffect(SoundEffectConstants.CLICK);
5831            li.mOnClickListener.onClick(this);
5832            result = true;
5833        } else {
5834            result = false;
5835        }
5836
5837        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5838        return result;
5839    }
5840
5841    /**
5842     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5843     * this only calls the listener, and does not do any associated clicking
5844     * actions like reporting an accessibility event.
5845     *
5846     * @return True there was an assigned OnClickListener that was called, false
5847     *         otherwise is returned.
5848     */
5849    public boolean callOnClick() {
5850        ListenerInfo li = mListenerInfo;
5851        if (li != null && li.mOnClickListener != null) {
5852            li.mOnClickListener.onClick(this);
5853            return true;
5854        }
5855        return false;
5856    }
5857
5858    /**
5859     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5860     * context menu if the OnLongClickListener did not consume the event.
5861     *
5862     * @return {@code true} if one of the above receivers consumed the event,
5863     *         {@code false} otherwise
5864     */
5865    public boolean performLongClick() {
5866        return performLongClickInternal(mLongClickX, mLongClickY);
5867    }
5868
5869    /**
5870     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5871     * context menu if the OnLongClickListener did not consume the event,
5872     * anchoring it to an (x,y) coordinate.
5873     *
5874     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5875     *          to disable anchoring
5876     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5877     *          to disable anchoring
5878     * @return {@code true} if one of the above receivers consumed the event,
5879     *         {@code false} otherwise
5880     */
5881    public boolean performLongClick(float x, float y) {
5882        mLongClickX = x;
5883        mLongClickY = y;
5884        final boolean handled = performLongClick();
5885        mLongClickX = Float.NaN;
5886        mLongClickY = Float.NaN;
5887        return handled;
5888    }
5889
5890    /**
5891     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5892     * context menu if the OnLongClickListener did not consume the event,
5893     * optionally anchoring it to an (x,y) coordinate.
5894     *
5895     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5896     *          to disable anchoring
5897     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5898     *          to disable anchoring
5899     * @return {@code true} if one of the above receivers consumed the event,
5900     *         {@code false} otherwise
5901     */
5902    private boolean performLongClickInternal(float x, float y) {
5903        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5904
5905        boolean handled = false;
5906        final ListenerInfo li = mListenerInfo;
5907        if (li != null && li.mOnLongClickListener != null) {
5908            handled = li.mOnLongClickListener.onLongClick(View.this);
5909        }
5910        if (!handled) {
5911            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5912            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5913        }
5914        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
5915            if (!handled) {
5916                handled = showLongClickTooltip((int) x, (int) y);
5917            }
5918        }
5919        if (handled) {
5920            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5921        }
5922        return handled;
5923    }
5924
5925    /**
5926     * Call this view's OnContextClickListener, if it is defined.
5927     *
5928     * @param x the x coordinate of the context click
5929     * @param y the y coordinate of the context click
5930     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5931     *         otherwise.
5932     */
5933    public boolean performContextClick(float x, float y) {
5934        return performContextClick();
5935    }
5936
5937    /**
5938     * Call this view's OnContextClickListener, if it is defined.
5939     *
5940     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5941     *         otherwise.
5942     */
5943    public boolean performContextClick() {
5944        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5945
5946        boolean handled = false;
5947        ListenerInfo li = mListenerInfo;
5948        if (li != null && li.mOnContextClickListener != null) {
5949            handled = li.mOnContextClickListener.onContextClick(View.this);
5950        }
5951        if (handled) {
5952            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5953        }
5954        return handled;
5955    }
5956
5957    /**
5958     * Performs button-related actions during a touch down event.
5959     *
5960     * @param event The event.
5961     * @return True if the down was consumed.
5962     *
5963     * @hide
5964     */
5965    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5966        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5967            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5968            showContextMenu(event.getX(), event.getY());
5969            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5970            return true;
5971        }
5972        return false;
5973    }
5974
5975    /**
5976     * Shows the context menu for this view.
5977     *
5978     * @return {@code true} if the context menu was shown, {@code false}
5979     *         otherwise
5980     * @see #showContextMenu(float, float)
5981     */
5982    public boolean showContextMenu() {
5983        return getParent().showContextMenuForChild(this);
5984    }
5985
5986    /**
5987     * Shows the context menu for this view anchored to the specified
5988     * view-relative coordinate.
5989     *
5990     * @param x the X coordinate in pixels relative to the view to which the
5991     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5992     * @param y the Y coordinate in pixels relative to the view to which the
5993     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5994     * @return {@code true} if the context menu was shown, {@code false}
5995     *         otherwise
5996     */
5997    public boolean showContextMenu(float x, float y) {
5998        return getParent().showContextMenuForChild(this, x, y);
5999    }
6000
6001    /**
6002     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
6003     *
6004     * @param callback Callback that will control the lifecycle of the action mode
6005     * @return The new action mode if it is started, null otherwise
6006     *
6007     * @see ActionMode
6008     * @see #startActionMode(android.view.ActionMode.Callback, int)
6009     */
6010    public ActionMode startActionMode(ActionMode.Callback callback) {
6011        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
6012    }
6013
6014    /**
6015     * Start an action mode with the given type.
6016     *
6017     * @param callback Callback that will control the lifecycle of the action mode
6018     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6019     * @return The new action mode if it is started, null otherwise
6020     *
6021     * @see ActionMode
6022     */
6023    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6024        ViewParent parent = getParent();
6025        if (parent == null) return null;
6026        try {
6027            return parent.startActionModeForChild(this, callback, type);
6028        } catch (AbstractMethodError ame) {
6029            // Older implementations of custom views might not implement this.
6030            return parent.startActionModeForChild(this, callback);
6031        }
6032    }
6033
6034    /**
6035     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
6036     * Context, creating a unique View identifier to retrieve the result.
6037     *
6038     * @param intent The Intent to be started.
6039     * @param requestCode The request code to use.
6040     * @hide
6041     */
6042    public void startActivityForResult(Intent intent, int requestCode) {
6043        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
6044        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
6045    }
6046
6047    /**
6048     * If this View corresponds to the calling who, dispatches the activity result.
6049     * @param who The identifier for the targeted View to receive the result.
6050     * @param requestCode The integer request code originally supplied to
6051     *                    startActivityForResult(), allowing you to identify who this
6052     *                    result came from.
6053     * @param resultCode The integer result code returned by the child activity
6054     *                   through its setResult().
6055     * @param data An Intent, which can return result data to the caller
6056     *               (various data can be attached to Intent "extras").
6057     * @return {@code true} if the activity result was dispatched.
6058     * @hide
6059     */
6060    public boolean dispatchActivityResult(
6061            String who, int requestCode, int resultCode, Intent data) {
6062        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6063            onActivityResult(requestCode, resultCode, data);
6064            mStartActivityRequestWho = null;
6065            return true;
6066        }
6067        return false;
6068    }
6069
6070    /**
6071     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6072     *
6073     * @param requestCode The integer request code originally supplied to
6074     *                    startActivityForResult(), allowing you to identify who this
6075     *                    result came from.
6076     * @param resultCode The integer result code returned by the child activity
6077     *                   through its setResult().
6078     * @param data An Intent, which can return result data to the caller
6079     *               (various data can be attached to Intent "extras").
6080     * @hide
6081     */
6082    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6083        // Do nothing.
6084    }
6085
6086    /**
6087     * Register a callback to be invoked when a hardware key is pressed in this view.
6088     * Key presses in software input methods will generally not trigger the methods of
6089     * this listener.
6090     * @param l the key listener to attach to this view
6091     */
6092    public void setOnKeyListener(OnKeyListener l) {
6093        getListenerInfo().mOnKeyListener = l;
6094    }
6095
6096    /**
6097     * Register a callback to be invoked when a touch event is sent to this view.
6098     * @param l the touch listener to attach to this view
6099     */
6100    public void setOnTouchListener(OnTouchListener l) {
6101        getListenerInfo().mOnTouchListener = l;
6102    }
6103
6104    /**
6105     * Register a callback to be invoked when a generic motion event is sent to this view.
6106     * @param l the generic motion listener to attach to this view
6107     */
6108    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6109        getListenerInfo().mOnGenericMotionListener = l;
6110    }
6111
6112    /**
6113     * Register a callback to be invoked when a hover event is sent to this view.
6114     * @param l the hover listener to attach to this view
6115     */
6116    public void setOnHoverListener(OnHoverListener l) {
6117        getListenerInfo().mOnHoverListener = l;
6118    }
6119
6120    /**
6121     * Register a drag event listener callback object for this View. The parameter is
6122     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6123     * View, the system calls the
6124     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6125     * @param l An implementation of {@link android.view.View.OnDragListener}.
6126     */
6127    public void setOnDragListener(OnDragListener l) {
6128        getListenerInfo().mOnDragListener = l;
6129    }
6130
6131    /**
6132     * Give this view focus. This will cause
6133     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6134     *
6135     * Note: this does not check whether this {@link View} should get focus, it just
6136     * gives it focus no matter what.  It should only be called internally by framework
6137     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6138     *
6139     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6140     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6141     *        focus moved when requestFocus() is called. It may not always
6142     *        apply, in which case use the default View.FOCUS_DOWN.
6143     * @param previouslyFocusedRect The rectangle of the view that had focus
6144     *        prior in this View's coordinate system.
6145     */
6146    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6147        if (DBG) {
6148            System.out.println(this + " requestFocus()");
6149        }
6150
6151        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6152            mPrivateFlags |= PFLAG_FOCUSED;
6153
6154            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6155
6156            if (mParent != null) {
6157                mParent.requestChildFocus(this, this);
6158                if (mParent instanceof ViewGroup) {
6159                    ((ViewGroup) mParent).setDefaultFocus(this);
6160                }
6161            }
6162
6163            if (mAttachInfo != null) {
6164                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6165            }
6166
6167            onFocusChanged(true, direction, previouslyFocusedRect);
6168            refreshDrawableState();
6169        }
6170    }
6171
6172    /**
6173     * Sets this view's preference for reveal behavior when it gains focus.
6174     *
6175     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6176     * this view would prefer to be brought fully into view when it gains focus.
6177     * For example, a text field that a user is meant to type into. Other views such
6178     * as scrolling containers may prefer to opt-out of this behavior.</p>
6179     *
6180     * <p>The default value for views is true, though subclasses may change this
6181     * based on their preferred behavior.</p>
6182     *
6183     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6184     *
6185     * @see #getRevealOnFocusHint()
6186     */
6187    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6188        if (revealOnFocus) {
6189            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6190        } else {
6191            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6192        }
6193    }
6194
6195    /**
6196     * Returns this view's preference for reveal behavior when it gains focus.
6197     *
6198     * <p>When this method returns true for a child view requesting focus, ancestor
6199     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6200     * should make a best effort to make the newly focused child fully visible to the user.
6201     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6202     * other properties affecting visibility to the user as part of the focus change.</p>
6203     *
6204     * @return true if this view would prefer to become fully visible when it gains focus,
6205     *         false if it would prefer not to disrupt scroll positioning
6206     *
6207     * @see #setRevealOnFocusHint(boolean)
6208     */
6209    public final boolean getRevealOnFocusHint() {
6210        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6211    }
6212
6213    /**
6214     * Populates <code>outRect</code> with the hotspot bounds. By default,
6215     * the hotspot bounds are identical to the screen bounds.
6216     *
6217     * @param outRect rect to populate with hotspot bounds
6218     * @hide Only for internal use by views and widgets.
6219     */
6220    public void getHotspotBounds(Rect outRect) {
6221        final Drawable background = getBackground();
6222        if (background != null) {
6223            background.getHotspotBounds(outRect);
6224        } else {
6225            getBoundsOnScreen(outRect);
6226        }
6227    }
6228
6229    /**
6230     * Request that a rectangle of this view be visible on the screen,
6231     * scrolling if necessary just enough.
6232     *
6233     * <p>A View should call this if it maintains some notion of which part
6234     * of its content is interesting.  For example, a text editing view
6235     * should call this when its cursor moves.
6236     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6237     * It should not be affected by which part of the View is currently visible or its scroll
6238     * position.
6239     *
6240     * @param rectangle The rectangle in the View's content coordinate space
6241     * @return Whether any parent scrolled.
6242     */
6243    public boolean requestRectangleOnScreen(Rect rectangle) {
6244        return requestRectangleOnScreen(rectangle, false);
6245    }
6246
6247    /**
6248     * Request that a rectangle of this view be visible on the screen,
6249     * scrolling if necessary just enough.
6250     *
6251     * <p>A View should call this if it maintains some notion of which part
6252     * of its content is interesting.  For example, a text editing view
6253     * should call this when its cursor moves.
6254     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6255     * It should not be affected by which part of the View is currently visible or its scroll
6256     * position.
6257     * <p>When <code>immediate</code> is set to true, scrolling will not be
6258     * animated.
6259     *
6260     * @param rectangle The rectangle in the View's content coordinate space
6261     * @param immediate True to forbid animated scrolling, false otherwise
6262     * @return Whether any parent scrolled.
6263     */
6264    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6265        if (mParent == null) {
6266            return false;
6267        }
6268
6269        View child = this;
6270
6271        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6272        position.set(rectangle);
6273
6274        ViewParent parent = mParent;
6275        boolean scrolled = false;
6276        while (parent != null) {
6277            rectangle.set((int) position.left, (int) position.top,
6278                    (int) position.right, (int) position.bottom);
6279
6280            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6281
6282            if (!(parent instanceof View)) {
6283                break;
6284            }
6285
6286            // move it from child's content coordinate space to parent's content coordinate space
6287            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6288
6289            child = (View) parent;
6290            parent = child.getParent();
6291        }
6292
6293        return scrolled;
6294    }
6295
6296    /**
6297     * Called when this view wants to give up focus. If focus is cleared
6298     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6299     * <p>
6300     * <strong>Note:</strong> When a View clears focus the framework is trying
6301     * to give focus to the first focusable View from the top. Hence, if this
6302     * View is the first from the top that can take focus, then all callbacks
6303     * related to clearing focus will be invoked after which the framework will
6304     * give focus to this view.
6305     * </p>
6306     */
6307    public void clearFocus() {
6308        if (DBG) {
6309            System.out.println(this + " clearFocus()");
6310        }
6311
6312        clearFocusInternal(null, true, true);
6313    }
6314
6315    /**
6316     * Clears focus from the view, optionally propagating the change up through
6317     * the parent hierarchy and requesting that the root view place new focus.
6318     *
6319     * @param propagate whether to propagate the change up through the parent
6320     *            hierarchy
6321     * @param refocus when propagate is true, specifies whether to request the
6322     *            root view place new focus
6323     */
6324    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6325        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6326            mPrivateFlags &= ~PFLAG_FOCUSED;
6327
6328            if (propagate && mParent != null) {
6329                mParent.clearChildFocus(this);
6330            }
6331
6332            onFocusChanged(false, 0, null);
6333            refreshDrawableState();
6334
6335            if (propagate && (!refocus || !rootViewRequestFocus())) {
6336                notifyGlobalFocusCleared(this);
6337            }
6338        }
6339    }
6340
6341    void notifyGlobalFocusCleared(View oldFocus) {
6342        if (oldFocus != null && mAttachInfo != null) {
6343            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6344        }
6345    }
6346
6347    boolean rootViewRequestFocus() {
6348        final View root = getRootView();
6349        return root != null && root.requestFocus();
6350    }
6351
6352    /**
6353     * Called internally by the view system when a new view is getting focus.
6354     * This is what clears the old focus.
6355     * <p>
6356     * <b>NOTE:</b> The parent view's focused child must be updated manually
6357     * after calling this method. Otherwise, the view hierarchy may be left in
6358     * an inconstent state.
6359     */
6360    void unFocus(View focused) {
6361        if (DBG) {
6362            System.out.println(this + " unFocus()");
6363        }
6364
6365        clearFocusInternal(focused, false, false);
6366    }
6367
6368    /**
6369     * Returns true if this view has focus itself, or is the ancestor of the
6370     * view that has focus.
6371     *
6372     * @return True if this view has or contains focus, false otherwise.
6373     */
6374    @ViewDebug.ExportedProperty(category = "focus")
6375    public boolean hasFocus() {
6376        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6377    }
6378
6379    /**
6380     * Returns true if this view is focusable or if it contains a reachable View
6381     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6382     * is a View whose parents do not block descendants focus.
6383     *
6384     * Only {@link #VISIBLE} views are considered focusable.
6385     *
6386     * @return True if the view is focusable or if the view contains a focusable
6387     *         View, false otherwise.
6388     *
6389     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6390     * @see ViewGroup#getTouchscreenBlocksFocus()
6391     */
6392    public boolean hasFocusable() {
6393        return hasFocusable(true);
6394    }
6395
6396    /**
6397     * @hide pending determination of whether this should be public or not.
6398     * Currently used for compatibility with old focusability expectations in ListView.
6399     */
6400    public boolean hasFocusable(boolean allowAutoFocus) {
6401        if (!isFocusableInTouchMode()) {
6402            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6403                final ViewGroup g = (ViewGroup) p;
6404                if (g.shouldBlockFocusForTouchscreen()) {
6405                    return false;
6406                }
6407            }
6408        }
6409        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6410            return false;
6411        }
6412        return allowAutoFocus ? getFocusable() != NOT_FOCUSABLE : getFocusable() == FOCUSABLE;
6413    }
6414
6415    /**
6416     * Called by the view system when the focus state of this view changes.
6417     * When the focus change event is caused by directional navigation, direction
6418     * and previouslyFocusedRect provide insight into where the focus is coming from.
6419     * When overriding, be sure to call up through to the super class so that
6420     * the standard focus handling will occur.
6421     *
6422     * @param gainFocus True if the View has focus; false otherwise.
6423     * @param direction The direction focus has moved when requestFocus()
6424     *                  is called to give this view focus. Values are
6425     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6426     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6427     *                  It may not always apply, in which case use the default.
6428     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6429     *        system, of the previously focused view.  If applicable, this will be
6430     *        passed in as finer grained information about where the focus is coming
6431     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6432     */
6433    @CallSuper
6434    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6435            @Nullable Rect previouslyFocusedRect) {
6436        if (gainFocus) {
6437            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6438        } else {
6439            notifyViewAccessibilityStateChangedIfNeeded(
6440                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6441        }
6442
6443        InputMethodManager imm = InputMethodManager.peekInstance();
6444        if (!gainFocus) {
6445            if (isPressed()) {
6446                setPressed(false);
6447            }
6448            if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6449                imm.focusOut(this);
6450            }
6451            onFocusLost();
6452        } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6453            imm.focusIn(this);
6454        }
6455
6456        if (isAutoFillable()) {
6457            AutoFillManager afm = getAutoFillManager();
6458            if (afm != null) {
6459                afm.updateAutoFillInput(this, gainFocus
6460                        ? AutoFillManager.FLAG_UPDATE_UI_SHOW
6461                        : AutoFillManager.FLAG_UPDATE_UI_HIDE);
6462            }
6463        }
6464
6465        invalidate(true);
6466        ListenerInfo li = mListenerInfo;
6467        if (li != null && li.mOnFocusChangeListener != null) {
6468            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6469        }
6470
6471        if (mAttachInfo != null) {
6472            mAttachInfo.mKeyDispatchState.reset(this);
6473        }
6474    }
6475
6476    /**
6477     * Sends an accessibility event of the given type. If accessibility is
6478     * not enabled this method has no effect. The default implementation calls
6479     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6480     * to populate information about the event source (this View), then calls
6481     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6482     * populate the text content of the event source including its descendants,
6483     * and last calls
6484     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6485     * on its parent to request sending of the event to interested parties.
6486     * <p>
6487     * If an {@link AccessibilityDelegate} has been specified via calling
6488     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6489     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6490     * responsible for handling this call.
6491     * </p>
6492     *
6493     * @param eventType The type of the event to send, as defined by several types from
6494     * {@link android.view.accessibility.AccessibilityEvent}, such as
6495     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6496     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6497     *
6498     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6499     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6500     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6501     * @see AccessibilityDelegate
6502     */
6503    public void sendAccessibilityEvent(int eventType) {
6504        if (mAccessibilityDelegate != null) {
6505            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6506        } else {
6507            sendAccessibilityEventInternal(eventType);
6508        }
6509    }
6510
6511    /**
6512     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6513     * {@link AccessibilityEvent} to make an announcement which is related to some
6514     * sort of a context change for which none of the events representing UI transitions
6515     * is a good fit. For example, announcing a new page in a book. If accessibility
6516     * is not enabled this method does nothing.
6517     *
6518     * @param text The announcement text.
6519     */
6520    public void announceForAccessibility(CharSequence text) {
6521        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6522            AccessibilityEvent event = AccessibilityEvent.obtain(
6523                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6524            onInitializeAccessibilityEvent(event);
6525            event.getText().add(text);
6526            event.setContentDescription(null);
6527            mParent.requestSendAccessibilityEvent(this, event);
6528        }
6529    }
6530
6531    /**
6532     * @see #sendAccessibilityEvent(int)
6533     *
6534     * Note: Called from the default {@link AccessibilityDelegate}.
6535     *
6536     * @hide
6537     */
6538    public void sendAccessibilityEventInternal(int eventType) {
6539        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6540            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6541        }
6542    }
6543
6544    /**
6545     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6546     * takes as an argument an empty {@link AccessibilityEvent} and does not
6547     * perform a check whether accessibility is enabled.
6548     * <p>
6549     * If an {@link AccessibilityDelegate} has been specified via calling
6550     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6551     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6552     * is responsible for handling this call.
6553     * </p>
6554     *
6555     * @param event The event to send.
6556     *
6557     * @see #sendAccessibilityEvent(int)
6558     */
6559    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6560        if (mAccessibilityDelegate != null) {
6561            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6562        } else {
6563            sendAccessibilityEventUncheckedInternal(event);
6564        }
6565    }
6566
6567    /**
6568     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6569     *
6570     * Note: Called from the default {@link AccessibilityDelegate}.
6571     *
6572     * @hide
6573     */
6574    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6575        if (!isShown()) {
6576            return;
6577        }
6578        onInitializeAccessibilityEvent(event);
6579        // Only a subset of accessibility events populates text content.
6580        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6581            dispatchPopulateAccessibilityEvent(event);
6582        }
6583        // In the beginning we called #isShown(), so we know that getParent() is not null.
6584        getParent().requestSendAccessibilityEvent(this, event);
6585    }
6586
6587    /**
6588     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6589     * to its children for adding their text content to the event. Note that the
6590     * event text is populated in a separate dispatch path since we add to the
6591     * event not only the text of the source but also the text of all its descendants.
6592     * A typical implementation will call
6593     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6594     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6595     * on each child. Override this method if custom population of the event text
6596     * content is required.
6597     * <p>
6598     * If an {@link AccessibilityDelegate} has been specified via calling
6599     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6600     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6601     * is responsible for handling this call.
6602     * </p>
6603     * <p>
6604     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6605     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6606     * </p>
6607     *
6608     * @param event The event.
6609     *
6610     * @return True if the event population was completed.
6611     */
6612    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6613        if (mAccessibilityDelegate != null) {
6614            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6615        } else {
6616            return dispatchPopulateAccessibilityEventInternal(event);
6617        }
6618    }
6619
6620    /**
6621     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6622     *
6623     * Note: Called from the default {@link AccessibilityDelegate}.
6624     *
6625     * @hide
6626     */
6627    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6628        onPopulateAccessibilityEvent(event);
6629        return false;
6630    }
6631
6632    /**
6633     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6634     * giving a chance to this View to populate the accessibility event with its
6635     * text content. While this method is free to modify event
6636     * attributes other than text content, doing so should normally be performed in
6637     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6638     * <p>
6639     * Example: Adding formatted date string to an accessibility event in addition
6640     *          to the text added by the super implementation:
6641     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6642     *     super.onPopulateAccessibilityEvent(event);
6643     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6644     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6645     *         mCurrentDate.getTimeInMillis(), flags);
6646     *     event.getText().add(selectedDateUtterance);
6647     * }</pre>
6648     * <p>
6649     * If an {@link AccessibilityDelegate} has been specified via calling
6650     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6651     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6652     * is responsible for handling this call.
6653     * </p>
6654     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6655     * information to the event, in case the default implementation has basic information to add.
6656     * </p>
6657     *
6658     * @param event The accessibility event which to populate.
6659     *
6660     * @see #sendAccessibilityEvent(int)
6661     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6662     */
6663    @CallSuper
6664    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6665        if (mAccessibilityDelegate != null) {
6666            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6667        } else {
6668            onPopulateAccessibilityEventInternal(event);
6669        }
6670    }
6671
6672    /**
6673     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6674     *
6675     * Note: Called from the default {@link AccessibilityDelegate}.
6676     *
6677     * @hide
6678     */
6679    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6680    }
6681
6682    /**
6683     * Initializes an {@link AccessibilityEvent} with information about
6684     * this View which is the event source. In other words, the source of
6685     * an accessibility event is the view whose state change triggered firing
6686     * the event.
6687     * <p>
6688     * Example: Setting the password property of an event in addition
6689     *          to properties set by the super implementation:
6690     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6691     *     super.onInitializeAccessibilityEvent(event);
6692     *     event.setPassword(true);
6693     * }</pre>
6694     * <p>
6695     * If an {@link AccessibilityDelegate} has been specified via calling
6696     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6697     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6698     * is responsible for handling this call.
6699     * </p>
6700     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6701     * information to the event, in case the default implementation has basic information to add.
6702     * </p>
6703     * @param event The event to initialize.
6704     *
6705     * @see #sendAccessibilityEvent(int)
6706     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6707     */
6708    @CallSuper
6709    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6710        if (mAccessibilityDelegate != null) {
6711            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6712        } else {
6713            onInitializeAccessibilityEventInternal(event);
6714        }
6715    }
6716
6717    /**
6718     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6719     *
6720     * Note: Called from the default {@link AccessibilityDelegate}.
6721     *
6722     * @hide
6723     */
6724    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6725        event.setSource(this);
6726        event.setClassName(getAccessibilityClassName());
6727        event.setPackageName(getContext().getPackageName());
6728        event.setEnabled(isEnabled());
6729        event.setContentDescription(mContentDescription);
6730
6731        switch (event.getEventType()) {
6732            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6733                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6734                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6735                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6736                event.setItemCount(focusablesTempList.size());
6737                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6738                if (mAttachInfo != null) {
6739                    focusablesTempList.clear();
6740                }
6741            } break;
6742            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6743                CharSequence text = getIterableTextForAccessibility();
6744                if (text != null && text.length() > 0) {
6745                    event.setFromIndex(getAccessibilitySelectionStart());
6746                    event.setToIndex(getAccessibilitySelectionEnd());
6747                    event.setItemCount(text.length());
6748                }
6749            } break;
6750        }
6751    }
6752
6753    /**
6754     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6755     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6756     * This method is responsible for obtaining an accessibility node info from a
6757     * pool of reusable instances and calling
6758     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6759     * initialize the former.
6760     * <p>
6761     * Note: The client is responsible for recycling the obtained instance by calling
6762     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6763     * </p>
6764     *
6765     * @return A populated {@link AccessibilityNodeInfo}.
6766     *
6767     * @see AccessibilityNodeInfo
6768     */
6769    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6770        if (mAccessibilityDelegate != null) {
6771            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6772        } else {
6773            return createAccessibilityNodeInfoInternal();
6774        }
6775    }
6776
6777    /**
6778     * @see #createAccessibilityNodeInfo()
6779     *
6780     * @hide
6781     */
6782    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6783        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6784        if (provider != null) {
6785            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6786        } else {
6787            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6788            onInitializeAccessibilityNodeInfo(info);
6789            return info;
6790        }
6791    }
6792
6793    /**
6794     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6795     * The base implementation sets:
6796     * <ul>
6797     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6798     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6799     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6800     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6801     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6802     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6803     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6804     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6805     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6806     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6807     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6808     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6809     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6810     * </ul>
6811     * <p>
6812     * Subclasses should override this method, call the super implementation,
6813     * and set additional attributes.
6814     * </p>
6815     * <p>
6816     * If an {@link AccessibilityDelegate} has been specified via calling
6817     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6818     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6819     * is responsible for handling this call.
6820     * </p>
6821     *
6822     * @param info The instance to initialize.
6823     */
6824    @CallSuper
6825    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6826        if (mAccessibilityDelegate != null) {
6827            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6828        } else {
6829            onInitializeAccessibilityNodeInfoInternal(info);
6830        }
6831    }
6832
6833    /**
6834     * Gets the location of this view in screen coordinates.
6835     *
6836     * @param outRect The output location
6837     * @hide
6838     */
6839    public void getBoundsOnScreen(Rect outRect) {
6840        getBoundsOnScreen(outRect, false);
6841    }
6842
6843    /**
6844     * Gets the location of this view in screen coordinates.
6845     *
6846     * @param outRect The output location
6847     * @param clipToParent Whether to clip child bounds to the parent ones.
6848     * @hide
6849     */
6850    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6851        if (mAttachInfo == null) {
6852            return;
6853        }
6854
6855        RectF position = mAttachInfo.mTmpTransformRect;
6856        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6857
6858        if (!hasIdentityMatrix()) {
6859            getMatrix().mapRect(position);
6860        }
6861
6862        position.offset(mLeft, mTop);
6863
6864        ViewParent parent = mParent;
6865        while (parent instanceof View) {
6866            View parentView = (View) parent;
6867
6868            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6869
6870            if (clipToParent) {
6871                position.left = Math.max(position.left, 0);
6872                position.top = Math.max(position.top, 0);
6873                position.right = Math.min(position.right, parentView.getWidth());
6874                position.bottom = Math.min(position.bottom, parentView.getHeight());
6875            }
6876
6877            if (!parentView.hasIdentityMatrix()) {
6878                parentView.getMatrix().mapRect(position);
6879            }
6880
6881            position.offset(parentView.mLeft, parentView.mTop);
6882
6883            parent = parentView.mParent;
6884        }
6885
6886        if (parent instanceof ViewRootImpl) {
6887            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6888            position.offset(0, -viewRootImpl.mCurScrollY);
6889        }
6890
6891        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6892
6893        outRect.set(Math.round(position.left), Math.round(position.top),
6894                Math.round(position.right), Math.round(position.bottom));
6895    }
6896
6897    /**
6898     * Return the class name of this object to be used for accessibility purposes.
6899     * Subclasses should only override this if they are implementing something that
6900     * should be seen as a completely new class of view when used by accessibility,
6901     * unrelated to the class it is deriving from.  This is used to fill in
6902     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6903     */
6904    public CharSequence getAccessibilityClassName() {
6905        return View.class.getName();
6906    }
6907
6908    /**
6909     * Called when assist structure is being retrieved from a view as part of
6910     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6911     * @param structure Fill in with structured view data.  The default implementation
6912     * fills in all data that can be inferred from the view itself.
6913     */
6914    public void onProvideStructure(ViewStructure structure) {
6915        onProvideStructureForAssistOrAutoFill(structure, 0);
6916    }
6917
6918    /**
6919     * Called when assist structure is being retrieved from a view as part of an auto-fill request.
6920     *
6921     * <p>The structure must be filled according to the request type, which is set in the
6922     * {@code flags} parameter - see the documentation on each flag for more details.
6923     *
6924     * @param structure Fill in with structured view data.  The default implementation
6925     * fills in all data that can be inferred from the view itself.
6926     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
6927     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
6928     */
6929    public void onProvideAutoFillStructure(ViewStructure structure, int flags) {
6930        onProvideStructureForAssistOrAutoFill(structure, flags);
6931    }
6932
6933    private void onProvideStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
6934        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
6935        // this method should take a boolean with the type of request.
6936        boolean forAutoFill = (flags
6937                & (View.AUTO_FILL_FLAG_TYPE_FILL
6938                        | View.AUTO_FILL_FLAG_TYPE_SAVE)) != 0;
6939        final int id = mID;
6940        if (id != NO_ID && !isViewIdGenerated(id)) {
6941            String pkg, type, entry;
6942            try {
6943                final Resources res = getResources();
6944                entry = res.getResourceEntryName(id);
6945                type = res.getResourceTypeName(id);
6946                pkg = res.getResourcePackageName(id);
6947            } catch (Resources.NotFoundException e) {
6948                entry = type = pkg = null;
6949            }
6950            structure.setId(id, pkg, type, entry);
6951        } else {
6952            structure.setId(id, null, null, null);
6953        }
6954
6955        if (forAutoFill) {
6956            // The auto-fill id needs to be unique, but its value doesn't matter, so it's better to
6957            // reuse the accessibility id to save space.
6958            structure.setAutoFillId(getAccessibilityViewId());
6959            structure.setAutoFillType(getAutoFillType());
6960        }
6961
6962        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6963        if (!hasIdentityMatrix()) {
6964            structure.setTransformation(getMatrix());
6965        }
6966        structure.setElevation(getZ());
6967        structure.setVisibility(getVisibility());
6968        structure.setEnabled(isEnabled());
6969        if (isClickable()) {
6970            structure.setClickable(true);
6971        }
6972        if (isFocusable()) {
6973            structure.setFocusable(true);
6974        }
6975        if (isFocused()) {
6976            structure.setFocused(true);
6977        }
6978        if (isAccessibilityFocused()) {
6979            structure.setAccessibilityFocused(true);
6980        }
6981        if (isSelected()) {
6982            structure.setSelected(true);
6983        }
6984        if (isActivated()) {
6985            structure.setActivated(true);
6986        }
6987        if (isLongClickable()) {
6988            structure.setLongClickable(true);
6989        }
6990        if (this instanceof Checkable) {
6991            structure.setCheckable(true);
6992            if (((Checkable)this).isChecked()) {
6993                structure.setChecked(true);
6994            }
6995        }
6996        if (isContextClickable()) {
6997            structure.setContextClickable(true);
6998        }
6999        structure.setClassName(getAccessibilityClassName().toString());
7000        structure.setContentDescription(getContentDescription());
7001    }
7002
7003    /**
7004     * Called when assist structure is being retrieved from a view as part of
7005     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
7006     * generate additional virtual structure under this view.  The defaullt implementation
7007     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
7008     * view's virtual accessibility nodes, if any.  You can override this for a more
7009     * optimal implementation providing this data.
7010     */
7011    public void onProvideVirtualStructure(ViewStructure structure) {
7012        onProvideVirtualStructureForAssistOrAutoFill(structure, 0);
7013    }
7014
7015    /**
7016     * Called when assist structure is being retrieved from a view as part of an auto-fill request
7017     * to generate additional virtual structure under this view.
7018     *
7019     * <p>The defaullt implementation uses {@link #getAccessibilityNodeProvider()} to try to
7020     * generate this from the view's virtual accessibility nodes, if any. You can override this
7021     * for a more optimal implementation providing this data.
7022     *
7023     * <p>The structure must be filled according to the request type, which is set in the
7024     * {@code flags} parameter - see the documentation on each flag for more details.
7025     *
7026     * @param structure Fill in with structured view data.
7027     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7028     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
7029     */
7030    public void onProvideAutoFillVirtualStructure(ViewStructure structure, int flags) {
7031        onProvideVirtualStructureForAssistOrAutoFill(structure, flags);
7032    }
7033
7034    private void onProvideVirtualStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
7035        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7036        // this method should take a boolean with the type of request.
7037        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7038        if (provider != null) {
7039            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
7040            structure.setChildCount(1);
7041            ViewStructure root = structure.newChild(0);
7042            populateVirtualStructure(root, provider, info, flags);
7043            info.recycle();
7044        }
7045    }
7046
7047    /**
7048     * Gets the {@link VirtualViewDelegate} responsible for auto-filling the virtual children of
7049     * this view.
7050     *
7051     * <p>By default returns {@code null} but should be overridden when view provides a virtual
7052     * hierachy on {@link OnProvideAssistDataListener} that takes flags used by the AutoFill
7053     * Framework (such as {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7054     * {@link #AUTO_FILL_FLAG_TYPE_SAVE}).
7055     */
7056    @Nullable
7057    public VirtualViewDelegate getAutoFillVirtualViewDelegate(
7058            @SuppressWarnings("unused") VirtualViewDelegate.Callback callback) {
7059        return null;
7060    }
7061
7062    /**
7063     * Automatically fills the content of this view with the {@code value}.
7064     *
7065     * <p>By default does nothing, but views should override it (and {@link #getAutoFillType()} to
7066     * support the AutoFill Framework.
7067     *
7068     * <p>Typically, it is implemented by:
7069     *
7070     * <ol>
7071     * <li>Call the proper getter method on {@link AutoFillValue} to fetch the actual value.
7072     * <li>Pass the actual value to the equivalent setter in the view.
7073     * <ol>
7074     *
7075     * <p>For example, a text-field view would call:
7076     *
7077     * <pre class="prettyprint">
7078     * CharSequence text = value.getTextValue();
7079     * if (text != null) {
7080     *     setText(text);
7081     * }
7082     * </pre>
7083     */
7084    public void autoFill(@SuppressWarnings("unused") AutoFillValue value) {
7085    }
7086
7087    /**
7088     * Describes the auto-fill type that should be used on calls to
7089     * {@link #autoFill(AutoFillValue)} and
7090     * {@link VirtualViewDelegate#autoFill(int, AutoFillValue)}.
7091     *
7092     * <p>By default returns {@code null}, but views should override it (and
7093     * {@link #autoFill(AutoFillValue)} to support the AutoFill Framework.
7094     */
7095    @Nullable
7096    public AutoFillType getAutoFillType() {
7097        return null;
7098    }
7099
7100    @Nullable
7101    private AutoFillManager getAutoFillManager() {
7102        return mContext.getSystemService(AutoFillManager.class);
7103    }
7104
7105    private boolean isAutoFillable() {
7106        return getAutoFillType() != null && !isAutoFillBlocked();
7107    }
7108
7109    private void populateVirtualStructure(ViewStructure structure,
7110            AccessibilityNodeProvider provider, AccessibilityNodeInfo info, int flags) {
7111        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7112        // this method should take a boolean with the type of request.
7113
7114        final boolean sanitized = (flags & View.AUTO_FILL_FLAG_TYPE_FILL) != 0;
7115
7116        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
7117                null, null, null);
7118        Rect rect = structure.getTempRect();
7119        info.getBoundsInParent(rect);
7120        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
7121        structure.setVisibility(VISIBLE);
7122        structure.setEnabled(info.isEnabled());
7123        if (info.isClickable()) {
7124            structure.setClickable(true);
7125        }
7126        if (info.isFocusable()) {
7127            structure.setFocusable(true);
7128        }
7129        if (info.isFocused()) {
7130            structure.setFocused(true);
7131        }
7132        if (info.isAccessibilityFocused()) {
7133            structure.setAccessibilityFocused(true);
7134        }
7135        if (info.isSelected()) {
7136            structure.setSelected(true);
7137        }
7138        if (info.isLongClickable()) {
7139            structure.setLongClickable(true);
7140        }
7141        if (info.isCheckable()) {
7142            structure.setCheckable(true);
7143            if (info.isChecked()) {
7144                structure.setChecked(true);
7145            }
7146        }
7147        if (info.isContextClickable()) {
7148            structure.setContextClickable(true);
7149        }
7150        CharSequence cname = info.getClassName();
7151        structure.setClassName(cname != null ? cname.toString() : null);
7152        structure.setContentDescription(info.getContentDescription());
7153        if (!sanitized && (info.getText() != null || info.getError() != null)) {
7154            // TODO(b/33197203) (b/33269702): when sanitized, try to use the Accessibility API to
7155            // just set sanitized values (like text coming from resource files), rather than not
7156            // setting it at all.
7157            structure.setText(info.getText(), info.getTextSelectionStart(),
7158                    info.getTextSelectionEnd());
7159        }
7160        final int NCHILDREN = info.getChildCount();
7161        if (NCHILDREN > 0) {
7162            structure.setChildCount(NCHILDREN);
7163            for (int i=0; i<NCHILDREN; i++) {
7164                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
7165                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
7166                ViewStructure child = structure.newChild(i);
7167                populateVirtualStructure(child, provider, cinfo, flags);
7168                cinfo.recycle();
7169            }
7170        }
7171    }
7172
7173    /**
7174     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
7175     * implementation calls {@link #onProvideStructure} and
7176     * {@link #onProvideVirtualStructure}.
7177     */
7178    public void dispatchProvideStructure(ViewStructure structure) {
7179        dispatchProvideStructureForAssistOrAutoFill(structure, 0);
7180    }
7181
7182    /**
7183     * Dispatch creation of {@link ViewStructure} down the hierarchy.
7184     *
7185     * <p>The structure must be filled according to the request type, which is set in the
7186     * {@code flags} parameter - see the documentation on each flag for more details.
7187     *
7188     * <p>The default implementation calls {@link #onProvideAutoFillStructure(ViewStructure, int)}
7189     * and {@link #onProvideAutoFillVirtualStructure(ViewStructure, int)}.
7190     *
7191     * @param structure Fill in with structured view data.
7192     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7193     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
7194     */
7195    public void dispatchProvideAutoFillStructure(ViewStructure structure, int flags) {
7196        dispatchProvideStructureForAssistOrAutoFill(structure, flags);
7197    }
7198
7199    private void dispatchProvideStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
7200        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7201        // this method should take a boolean with the type of request.
7202        boolean forAutoFill = (flags
7203                & (View.AUTO_FILL_FLAG_TYPE_FILL
7204                        | View.AUTO_FILL_FLAG_TYPE_SAVE)) != 0;
7205
7206        boolean blocked = forAutoFill ? isAutoFillBlocked() : isAssistBlocked();
7207        if (!blocked) {
7208            if (forAutoFill) {
7209                onProvideAutoFillStructure(structure, flags);
7210                onProvideAutoFillVirtualStructure(structure, flags);
7211            } else {
7212                onProvideStructure(structure);
7213                onProvideVirtualStructure(structure);
7214            }
7215        } else {
7216            structure.setClassName(getAccessibilityClassName().toString());
7217            structure.setAssistBlocked(true);
7218        }
7219    }
7220
7221    /**
7222     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
7223     *
7224     * Note: Called from the default {@link AccessibilityDelegate}.
7225     *
7226     * @hide
7227     */
7228    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
7229        if (mAttachInfo == null) {
7230            return;
7231        }
7232
7233        Rect bounds = mAttachInfo.mTmpInvalRect;
7234
7235        getDrawingRect(bounds);
7236        info.setBoundsInParent(bounds);
7237
7238        getBoundsOnScreen(bounds, true);
7239        info.setBoundsInScreen(bounds);
7240
7241        ViewParent parent = getParentForAccessibility();
7242        if (parent instanceof View) {
7243            info.setParent((View) parent);
7244        }
7245
7246        if (mID != View.NO_ID) {
7247            View rootView = getRootView();
7248            if (rootView == null) {
7249                rootView = this;
7250            }
7251
7252            View label = rootView.findLabelForView(this, mID);
7253            if (label != null) {
7254                info.setLabeledBy(label);
7255            }
7256
7257            if ((mAttachInfo.mAccessibilityFetchFlags
7258                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
7259                    && Resources.resourceHasPackage(mID)) {
7260                try {
7261                    String viewId = getResources().getResourceName(mID);
7262                    info.setViewIdResourceName(viewId);
7263                } catch (Resources.NotFoundException nfe) {
7264                    /* ignore */
7265                }
7266            }
7267        }
7268
7269        if (mLabelForId != View.NO_ID) {
7270            View rootView = getRootView();
7271            if (rootView == null) {
7272                rootView = this;
7273            }
7274            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
7275            if (labeled != null) {
7276                info.setLabelFor(labeled);
7277            }
7278        }
7279
7280        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
7281            View rootView = getRootView();
7282            if (rootView == null) {
7283                rootView = this;
7284            }
7285            View next = rootView.findViewInsideOutShouldExist(this,
7286                    mAccessibilityTraversalBeforeId);
7287            if (next != null && next.includeForAccessibility()) {
7288                info.setTraversalBefore(next);
7289            }
7290        }
7291
7292        if (mAccessibilityTraversalAfterId != View.NO_ID) {
7293            View rootView = getRootView();
7294            if (rootView == null) {
7295                rootView = this;
7296            }
7297            View next = rootView.findViewInsideOutShouldExist(this,
7298                    mAccessibilityTraversalAfterId);
7299            if (next != null && next.includeForAccessibility()) {
7300                info.setTraversalAfter(next);
7301            }
7302        }
7303
7304        info.setVisibleToUser(isVisibleToUser());
7305
7306        info.setImportantForAccessibility(isImportantForAccessibility());
7307        info.setPackageName(mContext.getPackageName());
7308        info.setClassName(getAccessibilityClassName());
7309        info.setContentDescription(getContentDescription());
7310
7311        info.setEnabled(isEnabled());
7312        info.setClickable(isClickable());
7313        info.setFocusable(isFocusable());
7314        info.setFocused(isFocused());
7315        info.setAccessibilityFocused(isAccessibilityFocused());
7316        info.setSelected(isSelected());
7317        info.setLongClickable(isLongClickable());
7318        info.setContextClickable(isContextClickable());
7319        info.setLiveRegion(getAccessibilityLiveRegion());
7320
7321        // TODO: These make sense only if we are in an AdapterView but all
7322        // views can be selected. Maybe from accessibility perspective
7323        // we should report as selectable view in an AdapterView.
7324        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
7325        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
7326
7327        if (isFocusable()) {
7328            if (isFocused()) {
7329                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
7330            } else {
7331                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
7332            }
7333        }
7334
7335        if (!isAccessibilityFocused()) {
7336            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
7337        } else {
7338            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
7339        }
7340
7341        if (isClickable() && isEnabled()) {
7342            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
7343        }
7344
7345        if (isLongClickable() && isEnabled()) {
7346            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
7347        }
7348
7349        if (isContextClickable() && isEnabled()) {
7350            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
7351        }
7352
7353        CharSequence text = getIterableTextForAccessibility();
7354        if (text != null && text.length() > 0) {
7355            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
7356
7357            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
7358            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
7359            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
7360            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
7361                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
7362                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
7363        }
7364
7365        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
7366        populateAccessibilityNodeInfoDrawingOrderInParent(info);
7367    }
7368
7369    /**
7370     * Determine the order in which this view will be drawn relative to its siblings for a11y
7371     *
7372     * @param info The info whose drawing order should be populated
7373     */
7374    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
7375        /*
7376         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7377         * drawing order may not be well-defined, and some Views with custom drawing order may
7378         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7379         */
7380        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7381            info.setDrawingOrder(0);
7382            return;
7383        }
7384        int drawingOrderInParent = 1;
7385        // Iterate up the hierarchy if parents are not important for a11y
7386        View viewAtDrawingLevel = this;
7387        final ViewParent parent = getParentForAccessibility();
7388        while (viewAtDrawingLevel != parent) {
7389            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7390            if (!(currentParent instanceof ViewGroup)) {
7391                // Should only happen for the Decor
7392                drawingOrderInParent = 0;
7393                break;
7394            } else {
7395                final ViewGroup parentGroup = (ViewGroup) currentParent;
7396                final int childCount = parentGroup.getChildCount();
7397                if (childCount > 1) {
7398                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7399                    if (preorderedList != null) {
7400                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7401                        for (int i = 0; i < childDrawIndex; i++) {
7402                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7403                        }
7404                    } else {
7405                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7406                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7407                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7408                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7409                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
7410                        if (childDrawIndex != 0) {
7411                            for (int i = 0; i < numChildrenToIterate; i++) {
7412                                final int otherDrawIndex = (customOrder ?
7413                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
7414                                if (otherDrawIndex < childDrawIndex) {
7415                                    drawingOrderInParent +=
7416                                            numViewsForAccessibility(parentGroup.getChildAt(i));
7417                                }
7418                            }
7419                        }
7420                    }
7421                }
7422            }
7423            viewAtDrawingLevel = (View) currentParent;
7424        }
7425        info.setDrawingOrder(drawingOrderInParent);
7426    }
7427
7428    private static int numViewsForAccessibility(View view) {
7429        if (view != null) {
7430            if (view.includeForAccessibility()) {
7431                return 1;
7432            } else if (view instanceof ViewGroup) {
7433                return ((ViewGroup) view).getNumChildrenForAccessibility();
7434            }
7435        }
7436        return 0;
7437    }
7438
7439    private View findLabelForView(View view, int labeledId) {
7440        if (mMatchLabelForPredicate == null) {
7441            mMatchLabelForPredicate = new MatchLabelForPredicate();
7442        }
7443        mMatchLabelForPredicate.mLabeledId = labeledId;
7444        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7445    }
7446
7447    /**
7448     * Computes whether this view is visible to the user. Such a view is
7449     * attached, visible, all its predecessors are visible, it is not clipped
7450     * entirely by its predecessors, and has an alpha greater than zero.
7451     *
7452     * @return Whether the view is visible on the screen.
7453     *
7454     * @hide
7455     */
7456    protected boolean isVisibleToUser() {
7457        return isVisibleToUser(null);
7458    }
7459
7460    /**
7461     * Computes whether the given portion of this view is visible to the user.
7462     * Such a view is attached, visible, all its predecessors are visible,
7463     * has an alpha greater than zero, and the specified portion is not
7464     * clipped entirely by its predecessors.
7465     *
7466     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7467     *                    <code>null</code>, and the entire view will be tested in this case.
7468     *                    When <code>true</code> is returned by the function, the actual visible
7469     *                    region will be stored in this parameter; that is, if boundInView is fully
7470     *                    contained within the view, no modification will be made, otherwise regions
7471     *                    outside of the visible area of the view will be clipped.
7472     *
7473     * @return Whether the specified portion of the view is visible on the screen.
7474     *
7475     * @hide
7476     */
7477    protected boolean isVisibleToUser(Rect boundInView) {
7478        if (mAttachInfo != null) {
7479            // Attached to invisible window means this view is not visible.
7480            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7481                return false;
7482            }
7483            // An invisible predecessor or one with alpha zero means
7484            // that this view is not visible to the user.
7485            Object current = this;
7486            while (current instanceof View) {
7487                View view = (View) current;
7488                // We have attach info so this view is attached and there is no
7489                // need to check whether we reach to ViewRootImpl on the way up.
7490                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7491                        view.getVisibility() != VISIBLE) {
7492                    return false;
7493                }
7494                current = view.mParent;
7495            }
7496            // Check if the view is entirely covered by its predecessors.
7497            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7498            Point offset = mAttachInfo.mPoint;
7499            if (!getGlobalVisibleRect(visibleRect, offset)) {
7500                return false;
7501            }
7502            // Check if the visible portion intersects the rectangle of interest.
7503            if (boundInView != null) {
7504                visibleRect.offset(-offset.x, -offset.y);
7505                return boundInView.intersect(visibleRect);
7506            }
7507            return true;
7508        }
7509        return false;
7510    }
7511
7512    /**
7513     * Returns the delegate for implementing accessibility support via
7514     * composition. For more details see {@link AccessibilityDelegate}.
7515     *
7516     * @return The delegate, or null if none set.
7517     *
7518     * @hide
7519     */
7520    public AccessibilityDelegate getAccessibilityDelegate() {
7521        return mAccessibilityDelegate;
7522    }
7523
7524    /**
7525     * Sets a delegate for implementing accessibility support via composition
7526     * (as opposed to inheritance). For more details, see
7527     * {@link AccessibilityDelegate}.
7528     * <p>
7529     * <strong>Note:</strong> On platform versions prior to
7530     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7531     * views in the {@code android.widget.*} package are called <i>before</i>
7532     * host methods. This prevents certain properties such as class name from
7533     * being modified by overriding
7534     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7535     * as any changes will be overwritten by the host class.
7536     * <p>
7537     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7538     * methods are called <i>after</i> host methods, which all properties to be
7539     * modified without being overwritten by the host class.
7540     *
7541     * @param delegate the object to which accessibility method calls should be
7542     *                 delegated
7543     * @see AccessibilityDelegate
7544     */
7545    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7546        mAccessibilityDelegate = delegate;
7547    }
7548
7549    /**
7550     * Gets the provider for managing a virtual view hierarchy rooted at this View
7551     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7552     * that explore the window content.
7553     * <p>
7554     * If this method returns an instance, this instance is responsible for managing
7555     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7556     * View including the one representing the View itself. Similarly the returned
7557     * instance is responsible for performing accessibility actions on any virtual
7558     * view or the root view itself.
7559     * </p>
7560     * <p>
7561     * If an {@link AccessibilityDelegate} has been specified via calling
7562     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7563     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7564     * is responsible for handling this call.
7565     * </p>
7566     *
7567     * @return The provider.
7568     *
7569     * @see AccessibilityNodeProvider
7570     */
7571    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7572        if (mAccessibilityDelegate != null) {
7573            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7574        } else {
7575            return null;
7576        }
7577    }
7578
7579    /**
7580     * Gets the unique identifier of this view on the screen for accessibility purposes.
7581     *
7582     * @return The view accessibility id.
7583     *
7584     * @hide
7585     */
7586    public int getAccessibilityViewId() {
7587        if (mAccessibilityViewId == NO_ID) {
7588            mAccessibilityViewId = sNextAccessibilityViewId++;
7589        }
7590        return mAccessibilityViewId;
7591    }
7592
7593    /**
7594     * Gets the unique identifier of the window in which this View reseides.
7595     *
7596     * @return The window accessibility id.
7597     *
7598     * @hide
7599     */
7600    public int getAccessibilityWindowId() {
7601        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7602                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7603    }
7604
7605    /**
7606     * Returns the {@link View}'s content description.
7607     * <p>
7608     * <strong>Note:</strong> Do not override this method, as it will have no
7609     * effect on the content description presented to accessibility services.
7610     * You must call {@link #setContentDescription(CharSequence)} to modify the
7611     * content description.
7612     *
7613     * @return the content description
7614     * @see #setContentDescription(CharSequence)
7615     * @attr ref android.R.styleable#View_contentDescription
7616     */
7617    @ViewDebug.ExportedProperty(category = "accessibility")
7618    public CharSequence getContentDescription() {
7619        return mContentDescription;
7620    }
7621
7622    /**
7623     * Sets the {@link View}'s content description.
7624     * <p>
7625     * A content description briefly describes the view and is primarily used
7626     * for accessibility support to determine how a view should be presented to
7627     * the user. In the case of a view with no textual representation, such as
7628     * {@link android.widget.ImageButton}, a useful content description
7629     * explains what the view does. For example, an image button with a phone
7630     * icon that is used to place a call may use "Call" as its content
7631     * description. An image of a floppy disk that is used to save a file may
7632     * use "Save".
7633     *
7634     * @param contentDescription The content description.
7635     * @see #getContentDescription()
7636     * @attr ref android.R.styleable#View_contentDescription
7637     */
7638    @RemotableViewMethod
7639    public void setContentDescription(CharSequence contentDescription) {
7640        if (mContentDescription == null) {
7641            if (contentDescription == null) {
7642                return;
7643            }
7644        } else if (mContentDescription.equals(contentDescription)) {
7645            return;
7646        }
7647        mContentDescription = contentDescription;
7648        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7649        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7650            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7651            notifySubtreeAccessibilityStateChangedIfNeeded();
7652        } else {
7653            notifyViewAccessibilityStateChangedIfNeeded(
7654                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7655        }
7656    }
7657
7658    /**
7659     * Sets the id of a view before which this one is visited in accessibility traversal.
7660     * A screen-reader must visit the content of this view before the content of the one
7661     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7662     * will traverse the entire content of B before traversing the entire content of A,
7663     * regardles of what traversal strategy it is using.
7664     * <p>
7665     * Views that do not have specified before/after relationships are traversed in order
7666     * determined by the screen-reader.
7667     * </p>
7668     * <p>
7669     * Setting that this view is before a view that is not important for accessibility
7670     * or if this view is not important for accessibility will have no effect as the
7671     * screen-reader is not aware of unimportant views.
7672     * </p>
7673     *
7674     * @param beforeId The id of a view this one precedes in accessibility traversal.
7675     *
7676     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7677     *
7678     * @see #setImportantForAccessibility(int)
7679     */
7680    @RemotableViewMethod
7681    public void setAccessibilityTraversalBefore(int beforeId) {
7682        if (mAccessibilityTraversalBeforeId == beforeId) {
7683            return;
7684        }
7685        mAccessibilityTraversalBeforeId = beforeId;
7686        notifyViewAccessibilityStateChangedIfNeeded(
7687                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7688    }
7689
7690    /**
7691     * Gets the id of a view before which this one is visited in accessibility traversal.
7692     *
7693     * @return The id of a view this one precedes in accessibility traversal if
7694     *         specified, otherwise {@link #NO_ID}.
7695     *
7696     * @see #setAccessibilityTraversalBefore(int)
7697     */
7698    public int getAccessibilityTraversalBefore() {
7699        return mAccessibilityTraversalBeforeId;
7700    }
7701
7702    /**
7703     * Sets the id of a view after which this one is visited in accessibility traversal.
7704     * A screen-reader must visit the content of the other view before the content of this
7705     * one. For example, if view B is set to be after view A, then a screen-reader
7706     * will traverse the entire content of A before traversing the entire content of B,
7707     * regardles of what traversal strategy it is using.
7708     * <p>
7709     * Views that do not have specified before/after relationships are traversed in order
7710     * determined by the screen-reader.
7711     * </p>
7712     * <p>
7713     * Setting that this view is after a view that is not important for accessibility
7714     * or if this view is not important for accessibility will have no effect as the
7715     * screen-reader is not aware of unimportant views.
7716     * </p>
7717     *
7718     * @param afterId The id of a view this one succedees in accessibility traversal.
7719     *
7720     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7721     *
7722     * @see #setImportantForAccessibility(int)
7723     */
7724    @RemotableViewMethod
7725    public void setAccessibilityTraversalAfter(int afterId) {
7726        if (mAccessibilityTraversalAfterId == afterId) {
7727            return;
7728        }
7729        mAccessibilityTraversalAfterId = afterId;
7730        notifyViewAccessibilityStateChangedIfNeeded(
7731                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7732    }
7733
7734    /**
7735     * Gets the id of a view after which this one is visited in accessibility traversal.
7736     *
7737     * @return The id of a view this one succeedes in accessibility traversal if
7738     *         specified, otherwise {@link #NO_ID}.
7739     *
7740     * @see #setAccessibilityTraversalAfter(int)
7741     */
7742    public int getAccessibilityTraversalAfter() {
7743        return mAccessibilityTraversalAfterId;
7744    }
7745
7746    /**
7747     * Gets the id of a view for which this view serves as a label for
7748     * accessibility purposes.
7749     *
7750     * @return The labeled view id.
7751     */
7752    @ViewDebug.ExportedProperty(category = "accessibility")
7753    public int getLabelFor() {
7754        return mLabelForId;
7755    }
7756
7757    /**
7758     * Sets the id of a view for which this view serves as a label for
7759     * accessibility purposes.
7760     *
7761     * @param id The labeled view id.
7762     */
7763    @RemotableViewMethod
7764    public void setLabelFor(@IdRes int id) {
7765        if (mLabelForId == id) {
7766            return;
7767        }
7768        mLabelForId = id;
7769        if (mLabelForId != View.NO_ID
7770                && mID == View.NO_ID) {
7771            mID = generateViewId();
7772        }
7773        notifyViewAccessibilityStateChangedIfNeeded(
7774                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7775    }
7776
7777    /**
7778     * Invoked whenever this view loses focus, either by losing window focus or by losing
7779     * focus within its window. This method can be used to clear any state tied to the
7780     * focus. For instance, if a button is held pressed with the trackball and the window
7781     * loses focus, this method can be used to cancel the press.
7782     *
7783     * Subclasses of View overriding this method should always call super.onFocusLost().
7784     *
7785     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7786     * @see #onWindowFocusChanged(boolean)
7787     *
7788     * @hide pending API council approval
7789     */
7790    @CallSuper
7791    protected void onFocusLost() {
7792        resetPressedState();
7793    }
7794
7795    private void resetPressedState() {
7796        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7797            return;
7798        }
7799
7800        if (isPressed()) {
7801            setPressed(false);
7802
7803            if (!mHasPerformedLongPress) {
7804                removeLongPressCallback();
7805            }
7806        }
7807    }
7808
7809    /**
7810     * Returns true if this view has focus
7811     *
7812     * @return True if this view has focus, false otherwise.
7813     */
7814    @ViewDebug.ExportedProperty(category = "focus")
7815    public boolean isFocused() {
7816        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7817    }
7818
7819    /**
7820     * Find the view in the hierarchy rooted at this view that currently has
7821     * focus.
7822     *
7823     * @return The view that currently has focus, or null if no focused view can
7824     *         be found.
7825     */
7826    public View findFocus() {
7827        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7828    }
7829
7830    /**
7831     * Indicates whether this view is one of the set of scrollable containers in
7832     * its window.
7833     *
7834     * @return whether this view is one of the set of scrollable containers in
7835     * its window
7836     *
7837     * @attr ref android.R.styleable#View_isScrollContainer
7838     */
7839    public boolean isScrollContainer() {
7840        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7841    }
7842
7843    /**
7844     * Change whether this view is one of the set of scrollable containers in
7845     * its window.  This will be used to determine whether the window can
7846     * resize or must pan when a soft input area is open -- scrollable
7847     * containers allow the window to use resize mode since the container
7848     * will appropriately shrink.
7849     *
7850     * @attr ref android.R.styleable#View_isScrollContainer
7851     */
7852    public void setScrollContainer(boolean isScrollContainer) {
7853        if (isScrollContainer) {
7854            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7855                mAttachInfo.mScrollContainers.add(this);
7856                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7857            }
7858            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7859        } else {
7860            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7861                mAttachInfo.mScrollContainers.remove(this);
7862            }
7863            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7864        }
7865    }
7866
7867    /**
7868     * Returns the quality of the drawing cache.
7869     *
7870     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7871     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7872     *
7873     * @see #setDrawingCacheQuality(int)
7874     * @see #setDrawingCacheEnabled(boolean)
7875     * @see #isDrawingCacheEnabled()
7876     *
7877     * @attr ref android.R.styleable#View_drawingCacheQuality
7878     */
7879    @DrawingCacheQuality
7880    public int getDrawingCacheQuality() {
7881        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7882    }
7883
7884    /**
7885     * Set the drawing cache quality of this view. This value is used only when the
7886     * drawing cache is enabled
7887     *
7888     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7889     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7890     *
7891     * @see #getDrawingCacheQuality()
7892     * @see #setDrawingCacheEnabled(boolean)
7893     * @see #isDrawingCacheEnabled()
7894     *
7895     * @attr ref android.R.styleable#View_drawingCacheQuality
7896     */
7897    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7898        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7899    }
7900
7901    /**
7902     * Returns whether the screen should remain on, corresponding to the current
7903     * value of {@link #KEEP_SCREEN_ON}.
7904     *
7905     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7906     *
7907     * @see #setKeepScreenOn(boolean)
7908     *
7909     * @attr ref android.R.styleable#View_keepScreenOn
7910     */
7911    public boolean getKeepScreenOn() {
7912        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7913    }
7914
7915    /**
7916     * Controls whether the screen should remain on, modifying the
7917     * value of {@link #KEEP_SCREEN_ON}.
7918     *
7919     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7920     *
7921     * @see #getKeepScreenOn()
7922     *
7923     * @attr ref android.R.styleable#View_keepScreenOn
7924     */
7925    public void setKeepScreenOn(boolean keepScreenOn) {
7926        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7927    }
7928
7929    /**
7930     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7931     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7932     *
7933     * @attr ref android.R.styleable#View_nextFocusLeft
7934     */
7935    public int getNextFocusLeftId() {
7936        return mNextFocusLeftId;
7937    }
7938
7939    /**
7940     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7941     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7942     * decide automatically.
7943     *
7944     * @attr ref android.R.styleable#View_nextFocusLeft
7945     */
7946    public void setNextFocusLeftId(int nextFocusLeftId) {
7947        mNextFocusLeftId = nextFocusLeftId;
7948    }
7949
7950    /**
7951     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7952     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7953     *
7954     * @attr ref android.R.styleable#View_nextFocusRight
7955     */
7956    public int getNextFocusRightId() {
7957        return mNextFocusRightId;
7958    }
7959
7960    /**
7961     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7962     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7963     * decide automatically.
7964     *
7965     * @attr ref android.R.styleable#View_nextFocusRight
7966     */
7967    public void setNextFocusRightId(int nextFocusRightId) {
7968        mNextFocusRightId = nextFocusRightId;
7969    }
7970
7971    /**
7972     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7973     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7974     *
7975     * @attr ref android.R.styleable#View_nextFocusUp
7976     */
7977    public int getNextFocusUpId() {
7978        return mNextFocusUpId;
7979    }
7980
7981    /**
7982     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7983     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7984     * decide automatically.
7985     *
7986     * @attr ref android.R.styleable#View_nextFocusUp
7987     */
7988    public void setNextFocusUpId(int nextFocusUpId) {
7989        mNextFocusUpId = nextFocusUpId;
7990    }
7991
7992    /**
7993     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7994     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7995     *
7996     * @attr ref android.R.styleable#View_nextFocusDown
7997     */
7998    public int getNextFocusDownId() {
7999        return mNextFocusDownId;
8000    }
8001
8002    /**
8003     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
8004     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
8005     * decide automatically.
8006     *
8007     * @attr ref android.R.styleable#View_nextFocusDown
8008     */
8009    public void setNextFocusDownId(int nextFocusDownId) {
8010        mNextFocusDownId = nextFocusDownId;
8011    }
8012
8013    /**
8014     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8015     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8016     *
8017     * @attr ref android.R.styleable#View_nextFocusForward
8018     */
8019    public int getNextFocusForwardId() {
8020        return mNextFocusForwardId;
8021    }
8022
8023    /**
8024     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8025     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
8026     * decide automatically.
8027     *
8028     * @attr ref android.R.styleable#View_nextFocusForward
8029     */
8030    public void setNextFocusForwardId(int nextFocusForwardId) {
8031        mNextFocusForwardId = nextFocusForwardId;
8032    }
8033
8034    /**
8035     * Gets the id of the root of the next keyboard navigation cluster.
8036     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
8037     * decide automatically.
8038     *
8039     * @attr ref android.R.styleable#View_nextClusterForward
8040     */
8041    public int getNextClusterForwardId() {
8042        return mNextClusterForwardId;
8043    }
8044
8045    /**
8046     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
8047     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
8048     * decide automatically.
8049     *
8050     * @attr ref android.R.styleable#View_nextClusterForward
8051     */
8052    public void setNextClusterForwardId(int nextClusterForwardId) {
8053        mNextClusterForwardId = nextClusterForwardId;
8054    }
8055
8056    /**
8057     * Returns the visibility of this view and all of its ancestors
8058     *
8059     * @return True if this view and all of its ancestors are {@link #VISIBLE}
8060     */
8061    public boolean isShown() {
8062        View current = this;
8063        //noinspection ConstantConditions
8064        do {
8065            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8066                return false;
8067            }
8068            ViewParent parent = current.mParent;
8069            if (parent == null) {
8070                return false; // We are not attached to the view root
8071            }
8072            if (!(parent instanceof View)) {
8073                return true;
8074            }
8075            current = (View) parent;
8076        } while (current != null);
8077
8078        return false;
8079    }
8080
8081    /**
8082     * Called by the view hierarchy when the content insets for a window have
8083     * changed, to allow it to adjust its content to fit within those windows.
8084     * The content insets tell you the space that the status bar, input method,
8085     * and other system windows infringe on the application's window.
8086     *
8087     * <p>You do not normally need to deal with this function, since the default
8088     * window decoration given to applications takes care of applying it to the
8089     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
8090     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
8091     * and your content can be placed under those system elements.  You can then
8092     * use this method within your view hierarchy if you have parts of your UI
8093     * which you would like to ensure are not being covered.
8094     *
8095     * <p>The default implementation of this method simply applies the content
8096     * insets to the view's padding, consuming that content (modifying the
8097     * insets to be 0), and returning true.  This behavior is off by default, but can
8098     * be enabled through {@link #setFitsSystemWindows(boolean)}.
8099     *
8100     * <p>This function's traversal down the hierarchy is depth-first.  The same content
8101     * insets object is propagated down the hierarchy, so any changes made to it will
8102     * be seen by all following views (including potentially ones above in
8103     * the hierarchy since this is a depth-first traversal).  The first view
8104     * that returns true will abort the entire traversal.
8105     *
8106     * <p>The default implementation works well for a situation where it is
8107     * used with a container that covers the entire window, allowing it to
8108     * apply the appropriate insets to its content on all edges.  If you need
8109     * a more complicated layout (such as two different views fitting system
8110     * windows, one on the top of the window, and one on the bottom),
8111     * you can override the method and handle the insets however you would like.
8112     * Note that the insets provided by the framework are always relative to the
8113     * far edges of the window, not accounting for the location of the called view
8114     * within that window.  (In fact when this method is called you do not yet know
8115     * where the layout will place the view, as it is done before layout happens.)
8116     *
8117     * <p>Note: unlike many View methods, there is no dispatch phase to this
8118     * call.  If you are overriding it in a ViewGroup and want to allow the
8119     * call to continue to your children, you must be sure to call the super
8120     * implementation.
8121     *
8122     * <p>Here is a sample layout that makes use of fitting system windows
8123     * to have controls for a video view placed inside of the window decorations
8124     * that it hides and shows.  This can be used with code like the second
8125     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
8126     *
8127     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
8128     *
8129     * @param insets Current content insets of the window.  Prior to
8130     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
8131     * the insets or else you and Android will be unhappy.
8132     *
8133     * @return {@code true} if this view applied the insets and it should not
8134     * continue propagating further down the hierarchy, {@code false} otherwise.
8135     * @see #getFitsSystemWindows()
8136     * @see #setFitsSystemWindows(boolean)
8137     * @see #setSystemUiVisibility(int)
8138     *
8139     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
8140     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
8141     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
8142     * to implement handling their own insets.
8143     */
8144    @Deprecated
8145    protected boolean fitSystemWindows(Rect insets) {
8146        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
8147            if (insets == null) {
8148                // Null insets by definition have already been consumed.
8149                // This call cannot apply insets since there are none to apply,
8150                // so return false.
8151                return false;
8152            }
8153            // If we're not in the process of dispatching the newer apply insets call,
8154            // that means we're not in the compatibility path. Dispatch into the newer
8155            // apply insets path and take things from there.
8156            try {
8157                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
8158                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
8159            } finally {
8160                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
8161            }
8162        } else {
8163            // We're being called from the newer apply insets path.
8164            // Perform the standard fallback behavior.
8165            return fitSystemWindowsInt(insets);
8166        }
8167    }
8168
8169    private boolean fitSystemWindowsInt(Rect insets) {
8170        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
8171            mUserPaddingStart = UNDEFINED_PADDING;
8172            mUserPaddingEnd = UNDEFINED_PADDING;
8173            Rect localInsets = sThreadLocal.get();
8174            if (localInsets == null) {
8175                localInsets = new Rect();
8176                sThreadLocal.set(localInsets);
8177            }
8178            boolean res = computeFitSystemWindows(insets, localInsets);
8179            mUserPaddingLeftInitial = localInsets.left;
8180            mUserPaddingRightInitial = localInsets.right;
8181            internalSetPadding(localInsets.left, localInsets.top,
8182                    localInsets.right, localInsets.bottom);
8183            return res;
8184        }
8185        return false;
8186    }
8187
8188    /**
8189     * Called when the view should apply {@link WindowInsets} according to its internal policy.
8190     *
8191     * <p>This method should be overridden by views that wish to apply a policy different from or
8192     * in addition to the default behavior. Clients that wish to force a view subtree
8193     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
8194     *
8195     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
8196     * it will be called during dispatch instead of this method. The listener may optionally
8197     * call this method from its own implementation if it wishes to apply the view's default
8198     * insets policy in addition to its own.</p>
8199     *
8200     * <p>Implementations of this method should either return the insets parameter unchanged
8201     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
8202     * that this view applied itself. This allows new inset types added in future platform
8203     * versions to pass through existing implementations unchanged without being erroneously
8204     * consumed.</p>
8205     *
8206     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
8207     * property is set then the view will consume the system window insets and apply them
8208     * as padding for the view.</p>
8209     *
8210     * @param insets Insets to apply
8211     * @return The supplied insets with any applied insets consumed
8212     */
8213    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
8214        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
8215            // We weren't called from within a direct call to fitSystemWindows,
8216            // call into it as a fallback in case we're in a class that overrides it
8217            // and has logic to perform.
8218            if (fitSystemWindows(insets.getSystemWindowInsets())) {
8219                return insets.consumeSystemWindowInsets();
8220            }
8221        } else {
8222            // We were called from within a direct call to fitSystemWindows.
8223            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
8224                return insets.consumeSystemWindowInsets();
8225            }
8226        }
8227        return insets;
8228    }
8229
8230    /**
8231     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
8232     * window insets to this view. The listener's
8233     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
8234     * method will be called instead of the view's
8235     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
8236     *
8237     * @param listener Listener to set
8238     *
8239     * @see #onApplyWindowInsets(WindowInsets)
8240     */
8241    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
8242        getListenerInfo().mOnApplyWindowInsetsListener = listener;
8243    }
8244
8245    /**
8246     * Request to apply the given window insets to this view or another view in its subtree.
8247     *
8248     * <p>This method should be called by clients wishing to apply insets corresponding to areas
8249     * obscured by window decorations or overlays. This can include the status and navigation bars,
8250     * action bars, input methods and more. New inset categories may be added in the future.
8251     * The method returns the insets provided minus any that were applied by this view or its
8252     * children.</p>
8253     *
8254     * <p>Clients wishing to provide custom behavior should override the
8255     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
8256     * {@link OnApplyWindowInsetsListener} via the
8257     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
8258     * method.</p>
8259     *
8260     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
8261     * </p>
8262     *
8263     * @param insets Insets to apply
8264     * @return The provided insets minus the insets that were consumed
8265     */
8266    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
8267        try {
8268            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
8269            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
8270                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
8271            } else {
8272                return onApplyWindowInsets(insets);
8273            }
8274        } finally {
8275            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
8276        }
8277    }
8278
8279    /**
8280     * Compute the view's coordinate within the surface.
8281     *
8282     * <p>Computes the coordinates of this view in its surface. The argument
8283     * must be an array of two integers. After the method returns, the array
8284     * contains the x and y location in that order.</p>
8285     * @hide
8286     * @param location an array of two integers in which to hold the coordinates
8287     */
8288    public void getLocationInSurface(@Size(2) int[] location) {
8289        getLocationInWindow(location);
8290        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
8291            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
8292            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
8293        }
8294    }
8295
8296    /**
8297     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
8298     * only available if the view is attached.
8299     *
8300     * @return WindowInsets from the top of the view hierarchy or null if View is detached
8301     */
8302    public WindowInsets getRootWindowInsets() {
8303        if (mAttachInfo != null) {
8304            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
8305        }
8306        return null;
8307    }
8308
8309    /**
8310     * @hide Compute the insets that should be consumed by this view and the ones
8311     * that should propagate to those under it.
8312     */
8313    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
8314        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8315                || mAttachInfo == null
8316                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
8317                        && !mAttachInfo.mOverscanRequested)) {
8318            outLocalInsets.set(inoutInsets);
8319            inoutInsets.set(0, 0, 0, 0);
8320            return true;
8321        } else {
8322            // The application wants to take care of fitting system window for
8323            // the content...  however we still need to take care of any overscan here.
8324            final Rect overscan = mAttachInfo.mOverscanInsets;
8325            outLocalInsets.set(overscan);
8326            inoutInsets.left -= overscan.left;
8327            inoutInsets.top -= overscan.top;
8328            inoutInsets.right -= overscan.right;
8329            inoutInsets.bottom -= overscan.bottom;
8330            return false;
8331        }
8332    }
8333
8334    /**
8335     * Compute insets that should be consumed by this view and the ones that should propagate
8336     * to those under it.
8337     *
8338     * @param in Insets currently being processed by this View, likely received as a parameter
8339     *           to {@link #onApplyWindowInsets(WindowInsets)}.
8340     * @param outLocalInsets A Rect that will receive the insets that should be consumed
8341     *                       by this view
8342     * @return Insets that should be passed along to views under this one
8343     */
8344    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
8345        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8346                || mAttachInfo == null
8347                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
8348            outLocalInsets.set(in.getSystemWindowInsets());
8349            return in.consumeSystemWindowInsets();
8350        } else {
8351            outLocalInsets.set(0, 0, 0, 0);
8352            return in;
8353        }
8354    }
8355
8356    /**
8357     * Sets whether or not this view should account for system screen decorations
8358     * such as the status bar and inset its content; that is, controlling whether
8359     * the default implementation of {@link #fitSystemWindows(Rect)} will be
8360     * executed.  See that method for more details.
8361     *
8362     * <p>Note that if you are providing your own implementation of
8363     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
8364     * flag to true -- your implementation will be overriding the default
8365     * implementation that checks this flag.
8366     *
8367     * @param fitSystemWindows If true, then the default implementation of
8368     * {@link #fitSystemWindows(Rect)} will be executed.
8369     *
8370     * @attr ref android.R.styleable#View_fitsSystemWindows
8371     * @see #getFitsSystemWindows()
8372     * @see #fitSystemWindows(Rect)
8373     * @see #setSystemUiVisibility(int)
8374     */
8375    public void setFitsSystemWindows(boolean fitSystemWindows) {
8376        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
8377    }
8378
8379    /**
8380     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
8381     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
8382     * will be executed.
8383     *
8384     * @return {@code true} if the default implementation of
8385     * {@link #fitSystemWindows(Rect)} will be executed.
8386     *
8387     * @attr ref android.R.styleable#View_fitsSystemWindows
8388     * @see #setFitsSystemWindows(boolean)
8389     * @see #fitSystemWindows(Rect)
8390     * @see #setSystemUiVisibility(int)
8391     */
8392    @ViewDebug.ExportedProperty
8393    public boolean getFitsSystemWindows() {
8394        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
8395    }
8396
8397    /** @hide */
8398    public boolean fitsSystemWindows() {
8399        return getFitsSystemWindows();
8400    }
8401
8402    /**
8403     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8404     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8405     */
8406    @Deprecated
8407    public void requestFitSystemWindows() {
8408        if (mParent != null) {
8409            mParent.requestFitSystemWindows();
8410        }
8411    }
8412
8413    /**
8414     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
8415     */
8416    public void requestApplyInsets() {
8417        requestFitSystemWindows();
8418    }
8419
8420    /**
8421     * For use by PhoneWindow to make its own system window fitting optional.
8422     * @hide
8423     */
8424    public void makeOptionalFitsSystemWindows() {
8425        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
8426    }
8427
8428    /**
8429     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
8430     * treat them as such.
8431     * @hide
8432     */
8433    public void getOutsets(Rect outOutsetRect) {
8434        if (mAttachInfo != null) {
8435            outOutsetRect.set(mAttachInfo.mOutsets);
8436        } else {
8437            outOutsetRect.setEmpty();
8438        }
8439    }
8440
8441    /**
8442     * Returns the visibility status for this view.
8443     *
8444     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8445     * @attr ref android.R.styleable#View_visibility
8446     */
8447    @ViewDebug.ExportedProperty(mapping = {
8448        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
8449        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
8450        @ViewDebug.IntToString(from = GONE,      to = "GONE")
8451    })
8452    @Visibility
8453    public int getVisibility() {
8454        return mViewFlags & VISIBILITY_MASK;
8455    }
8456
8457    /**
8458     * Set the visibility state of this view.
8459     *
8460     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8461     * @attr ref android.R.styleable#View_visibility
8462     */
8463    @RemotableViewMethod
8464    public void setVisibility(@Visibility int visibility) {
8465        setFlags(visibility, VISIBILITY_MASK);
8466    }
8467
8468    /**
8469     * Returns the enabled status for this view. The interpretation of the
8470     * enabled state varies by subclass.
8471     *
8472     * @return True if this view is enabled, false otherwise.
8473     */
8474    @ViewDebug.ExportedProperty
8475    public boolean isEnabled() {
8476        return (mViewFlags & ENABLED_MASK) == ENABLED;
8477    }
8478
8479    /**
8480     * Set the enabled state of this view. The interpretation of the enabled
8481     * state varies by subclass.
8482     *
8483     * @param enabled True if this view is enabled, false otherwise.
8484     */
8485    @RemotableViewMethod
8486    public void setEnabled(boolean enabled) {
8487        if (enabled == isEnabled()) return;
8488
8489        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8490
8491        /*
8492         * The View most likely has to change its appearance, so refresh
8493         * the drawable state.
8494         */
8495        refreshDrawableState();
8496
8497        // Invalidate too, since the default behavior for views is to be
8498        // be drawn at 50% alpha rather than to change the drawable.
8499        invalidate(true);
8500
8501        if (!enabled) {
8502            cancelPendingInputEvents();
8503        }
8504    }
8505
8506    /**
8507     * Set whether this view can receive the focus.
8508     * <p>
8509     * Setting this to false will also ensure that this view is not focusable
8510     * in touch mode.
8511     *
8512     * @param focusable If true, this view can receive the focus.
8513     *
8514     * @see #setFocusableInTouchMode(boolean)
8515     * @see #setFocusable(int)
8516     * @attr ref android.R.styleable#View_focusable
8517     */
8518    public void setFocusable(boolean focusable) {
8519        setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
8520    }
8521
8522    /**
8523     * Sets whether this view can receive focus.
8524     * <p>
8525     * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
8526     * automatically based on the view's interactivity. This is the default.
8527     * <p>
8528     * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
8529     * in touch mode.
8530     *
8531     * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
8532     *                  or {@link #FOCUSABLE_AUTO}.
8533     * @see #setFocusableInTouchMode(boolean)
8534     * @attr ref android.R.styleable#View_focusable
8535     */
8536    public void setFocusable(@Focusable int focusable) {
8537        if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
8538            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8539        }
8540        setFlags(focusable, FOCUSABLE_MASK);
8541    }
8542
8543    /**
8544     * Set whether this view can receive focus while in touch mode.
8545     *
8546     * Setting this to true will also ensure that this view is focusable.
8547     *
8548     * @param focusableInTouchMode If true, this view can receive the focus while
8549     *   in touch mode.
8550     *
8551     * @see #setFocusable(boolean)
8552     * @attr ref android.R.styleable#View_focusableInTouchMode
8553     */
8554    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8555        // Focusable in touch mode should always be set before the focusable flag
8556        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8557        // which, in touch mode, will not successfully request focus on this view
8558        // because the focusable in touch mode flag is not set
8559        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8560        if (focusableInTouchMode) {
8561            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8562        }
8563    }
8564
8565    /**
8566     * Set whether this view should have sound effects enabled for events such as
8567     * clicking and touching.
8568     *
8569     * <p>You may wish to disable sound effects for a view if you already play sounds,
8570     * for instance, a dial key that plays dtmf tones.
8571     *
8572     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8573     * @see #isSoundEffectsEnabled()
8574     * @see #playSoundEffect(int)
8575     * @attr ref android.R.styleable#View_soundEffectsEnabled
8576     */
8577    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8578        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8579    }
8580
8581    /**
8582     * @return whether this view should have sound effects enabled for events such as
8583     *     clicking and touching.
8584     *
8585     * @see #setSoundEffectsEnabled(boolean)
8586     * @see #playSoundEffect(int)
8587     * @attr ref android.R.styleable#View_soundEffectsEnabled
8588     */
8589    @ViewDebug.ExportedProperty
8590    public boolean isSoundEffectsEnabled() {
8591        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8592    }
8593
8594    /**
8595     * Set whether this view should have haptic feedback for events such as
8596     * long presses.
8597     *
8598     * <p>You may wish to disable haptic feedback if your view already controls
8599     * its own haptic feedback.
8600     *
8601     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8602     * @see #isHapticFeedbackEnabled()
8603     * @see #performHapticFeedback(int)
8604     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8605     */
8606    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8607        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8608    }
8609
8610    /**
8611     * @return whether this view should have haptic feedback enabled for events
8612     * long presses.
8613     *
8614     * @see #setHapticFeedbackEnabled(boolean)
8615     * @see #performHapticFeedback(int)
8616     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8617     */
8618    @ViewDebug.ExportedProperty
8619    public boolean isHapticFeedbackEnabled() {
8620        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8621    }
8622
8623    /**
8624     * Returns the layout direction for this view.
8625     *
8626     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8627     *   {@link #LAYOUT_DIRECTION_RTL},
8628     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8629     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8630     *
8631     * @attr ref android.R.styleable#View_layoutDirection
8632     *
8633     * @hide
8634     */
8635    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8636        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8637        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8638        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8639        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8640    })
8641    @LayoutDir
8642    public int getRawLayoutDirection() {
8643        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8644    }
8645
8646    /**
8647     * Set the layout direction for this view. This will propagate a reset of layout direction
8648     * resolution to the view's children and resolve layout direction for this view.
8649     *
8650     * @param layoutDirection the layout direction to set. Should be one of:
8651     *
8652     * {@link #LAYOUT_DIRECTION_LTR},
8653     * {@link #LAYOUT_DIRECTION_RTL},
8654     * {@link #LAYOUT_DIRECTION_INHERIT},
8655     * {@link #LAYOUT_DIRECTION_LOCALE}.
8656     *
8657     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8658     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8659     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8660     *
8661     * @attr ref android.R.styleable#View_layoutDirection
8662     */
8663    @RemotableViewMethod
8664    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8665        if (getRawLayoutDirection() != layoutDirection) {
8666            // Reset the current layout direction and the resolved one
8667            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8668            resetRtlProperties();
8669            // Set the new layout direction (filtered)
8670            mPrivateFlags2 |=
8671                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8672            // We need to resolve all RTL properties as they all depend on layout direction
8673            resolveRtlPropertiesIfNeeded();
8674            requestLayout();
8675            invalidate(true);
8676        }
8677    }
8678
8679    /**
8680     * Returns the resolved layout direction for this view.
8681     *
8682     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8683     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8684     *
8685     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8686     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8687     *
8688     * @attr ref android.R.styleable#View_layoutDirection
8689     */
8690    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8691        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8692        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8693    })
8694    @ResolvedLayoutDir
8695    public int getLayoutDirection() {
8696        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8697        if (targetSdkVersion < JELLY_BEAN_MR1) {
8698            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8699            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8700        }
8701        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8702                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8703    }
8704
8705    /**
8706     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8707     * layout attribute and/or the inherited value from the parent
8708     *
8709     * @return true if the layout is right-to-left.
8710     *
8711     * @hide
8712     */
8713    @ViewDebug.ExportedProperty(category = "layout")
8714    public boolean isLayoutRtl() {
8715        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8716    }
8717
8718    /**
8719     * Indicates whether the view is currently tracking transient state that the
8720     * app should not need to concern itself with saving and restoring, but that
8721     * the framework should take special note to preserve when possible.
8722     *
8723     * <p>A view with transient state cannot be trivially rebound from an external
8724     * data source, such as an adapter binding item views in a list. This may be
8725     * because the view is performing an animation, tracking user selection
8726     * of content, or similar.</p>
8727     *
8728     * @return true if the view has transient state
8729     */
8730    @ViewDebug.ExportedProperty(category = "layout")
8731    public boolean hasTransientState() {
8732        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8733    }
8734
8735    /**
8736     * Set whether this view is currently tracking transient state that the
8737     * framework should attempt to preserve when possible. This flag is reference counted,
8738     * so every call to setHasTransientState(true) should be paired with a later call
8739     * to setHasTransientState(false).
8740     *
8741     * <p>A view with transient state cannot be trivially rebound from an external
8742     * data source, such as an adapter binding item views in a list. This may be
8743     * because the view is performing an animation, tracking user selection
8744     * of content, or similar.</p>
8745     *
8746     * @param hasTransientState true if this view has transient state
8747     */
8748    public void setHasTransientState(boolean hasTransientState) {
8749        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8750                mTransientStateCount - 1;
8751        if (mTransientStateCount < 0) {
8752            mTransientStateCount = 0;
8753            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8754                    "unmatched pair of setHasTransientState calls");
8755        } else if ((hasTransientState && mTransientStateCount == 1) ||
8756                (!hasTransientState && mTransientStateCount == 0)) {
8757            // update flag if we've just incremented up from 0 or decremented down to 0
8758            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8759                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8760            if (mParent != null) {
8761                try {
8762                    mParent.childHasTransientStateChanged(this, hasTransientState);
8763                } catch (AbstractMethodError e) {
8764                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8765                            " does not fully implement ViewParent", e);
8766                }
8767            }
8768        }
8769    }
8770
8771    /**
8772     * Returns true if this view is currently attached to a window.
8773     */
8774    public boolean isAttachedToWindow() {
8775        return mAttachInfo != null;
8776    }
8777
8778    /**
8779     * Returns true if this view has been through at least one layout since it
8780     * was last attached to or detached from a window.
8781     */
8782    public boolean isLaidOut() {
8783        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8784    }
8785
8786    /**
8787     * If this view doesn't do any drawing on its own, set this flag to
8788     * allow further optimizations. By default, this flag is not set on
8789     * View, but could be set on some View subclasses such as ViewGroup.
8790     *
8791     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8792     * you should clear this flag.
8793     *
8794     * @param willNotDraw whether or not this View draw on its own
8795     */
8796    public void setWillNotDraw(boolean willNotDraw) {
8797        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8798    }
8799
8800    /**
8801     * Returns whether or not this View draws on its own.
8802     *
8803     * @return true if this view has nothing to draw, false otherwise
8804     */
8805    @ViewDebug.ExportedProperty(category = "drawing")
8806    public boolean willNotDraw() {
8807        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8808    }
8809
8810    /**
8811     * When a View's drawing cache is enabled, drawing is redirected to an
8812     * offscreen bitmap. Some views, like an ImageView, must be able to
8813     * bypass this mechanism if they already draw a single bitmap, to avoid
8814     * unnecessary usage of the memory.
8815     *
8816     * @param willNotCacheDrawing true if this view does not cache its
8817     *        drawing, false otherwise
8818     */
8819    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8820        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8821    }
8822
8823    /**
8824     * Returns whether or not this View can cache its drawing or not.
8825     *
8826     * @return true if this view does not cache its drawing, false otherwise
8827     */
8828    @ViewDebug.ExportedProperty(category = "drawing")
8829    public boolean willNotCacheDrawing() {
8830        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8831    }
8832
8833    /**
8834     * Indicates whether this view reacts to click events or not.
8835     *
8836     * @return true if the view is clickable, false otherwise
8837     *
8838     * @see #setClickable(boolean)
8839     * @attr ref android.R.styleable#View_clickable
8840     */
8841    @ViewDebug.ExportedProperty
8842    public boolean isClickable() {
8843        return (mViewFlags & CLICKABLE) == CLICKABLE;
8844    }
8845
8846    /**
8847     * Enables or disables click events for this view. When a view
8848     * is clickable it will change its state to "pressed" on every click.
8849     * Subclasses should set the view clickable to visually react to
8850     * user's clicks.
8851     *
8852     * @param clickable true to make the view clickable, false otherwise
8853     *
8854     * @see #isClickable()
8855     * @attr ref android.R.styleable#View_clickable
8856     */
8857    public void setClickable(boolean clickable) {
8858        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8859    }
8860
8861    /**
8862     * Indicates whether this view reacts to long click events or not.
8863     *
8864     * @return true if the view is long clickable, false otherwise
8865     *
8866     * @see #setLongClickable(boolean)
8867     * @attr ref android.R.styleable#View_longClickable
8868     */
8869    public boolean isLongClickable() {
8870        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8871    }
8872
8873    /**
8874     * Enables or disables long click events for this view. When a view is long
8875     * clickable it reacts to the user holding down the button for a longer
8876     * duration than a tap. This event can either launch the listener or a
8877     * context menu.
8878     *
8879     * @param longClickable true to make the view long clickable, false otherwise
8880     * @see #isLongClickable()
8881     * @attr ref android.R.styleable#View_longClickable
8882     */
8883    public void setLongClickable(boolean longClickable) {
8884        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8885    }
8886
8887    /**
8888     * Indicates whether this view reacts to context clicks or not.
8889     *
8890     * @return true if the view is context clickable, false otherwise
8891     * @see #setContextClickable(boolean)
8892     * @attr ref android.R.styleable#View_contextClickable
8893     */
8894    public boolean isContextClickable() {
8895        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8896    }
8897
8898    /**
8899     * Enables or disables context clicking for this view. This event can launch the listener.
8900     *
8901     * @param contextClickable true to make the view react to a context click, false otherwise
8902     * @see #isContextClickable()
8903     * @attr ref android.R.styleable#View_contextClickable
8904     */
8905    public void setContextClickable(boolean contextClickable) {
8906        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8907    }
8908
8909    /**
8910     * Sets the pressed state for this view and provides a touch coordinate for
8911     * animation hinting.
8912     *
8913     * @param pressed Pass true to set the View's internal state to "pressed",
8914     *            or false to reverts the View's internal state from a
8915     *            previously set "pressed" state.
8916     * @param x The x coordinate of the touch that caused the press
8917     * @param y The y coordinate of the touch that caused the press
8918     */
8919    private void setPressed(boolean pressed, float x, float y) {
8920        if (pressed) {
8921            drawableHotspotChanged(x, y);
8922        }
8923
8924        setPressed(pressed);
8925    }
8926
8927    /**
8928     * Sets the pressed state for this view.
8929     *
8930     * @see #isClickable()
8931     * @see #setClickable(boolean)
8932     *
8933     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8934     *        the View's internal state from a previously set "pressed" state.
8935     */
8936    public void setPressed(boolean pressed) {
8937        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8938
8939        if (pressed) {
8940            mPrivateFlags |= PFLAG_PRESSED;
8941        } else {
8942            mPrivateFlags &= ~PFLAG_PRESSED;
8943        }
8944
8945        if (needsRefresh) {
8946            refreshDrawableState();
8947        }
8948        dispatchSetPressed(pressed);
8949    }
8950
8951    /**
8952     * Dispatch setPressed to all of this View's children.
8953     *
8954     * @see #setPressed(boolean)
8955     *
8956     * @param pressed The new pressed state
8957     */
8958    protected void dispatchSetPressed(boolean pressed) {
8959    }
8960
8961    /**
8962     * Indicates whether the view is currently in pressed state. Unless
8963     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8964     * the pressed state.
8965     *
8966     * @see #setPressed(boolean)
8967     * @see #isClickable()
8968     * @see #setClickable(boolean)
8969     *
8970     * @return true if the view is currently pressed, false otherwise
8971     */
8972    @ViewDebug.ExportedProperty
8973    public boolean isPressed() {
8974        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8975    }
8976
8977    /**
8978     * @hide
8979     * Indicates whether this view will participate in data collection through
8980     * {@link ViewStructure}.  If true, it will not provide any data
8981     * for itself or its children.  If false, the normal data collection will be allowed.
8982     *
8983     * @return Returns false if assist data collection is not blocked, else true.
8984     *
8985     * @see #setAssistBlocked(boolean)
8986     * @attr ref android.R.styleable#View_assistBlocked
8987     */
8988    public boolean isAssistBlocked() {
8989        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8990    }
8991
8992    /**
8993     * @hide
8994     * Indicates whether this view will participate in data collection through
8995     * {@link ViewStructure} for auto-fill purposes.
8996     *
8997     * <p>If {@code true}, it will not provide any data for itself or its children.
8998     * <p>If {@code false}, the normal data collection will be allowed.
8999     *
9000     * @return Returns {@code false} if assist data collection for auto-fill is not blocked,
9001     * else {@code true}.
9002     *
9003     * TODO(b/33197203): update / remove javadoc tags below
9004     * @see #setAssistBlocked(boolean)
9005     * @attr ref android.R.styleable#View_assistBlocked
9006     */
9007    public boolean isAutoFillBlocked() {
9008        return false; // TODO(b/33197203): properly implement it
9009    }
9010
9011    /**
9012     * @hide
9013     * Controls whether assist data collection from this view and its children is enabled
9014     * (that is, whether {@link #onProvideStructure} and
9015     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
9016     * allowing normal assist collection.  Setting this to false will disable assist collection.
9017     *
9018     * @param enabled Set to true to <em>disable</em> assist data collection, or false
9019     * (the default) to allow it.
9020     *
9021     * @see #isAssistBlocked()
9022     * @see #onProvideStructure
9023     * @see #onProvideVirtualStructure
9024     * @attr ref android.R.styleable#View_assistBlocked
9025     */
9026    public void setAssistBlocked(boolean enabled) {
9027        if (enabled) {
9028            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
9029        } else {
9030            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
9031        }
9032    }
9033
9034    /**
9035     * Indicates whether this view will save its state (that is,
9036     * whether its {@link #onSaveInstanceState} method will be called).
9037     *
9038     * @return Returns true if the view state saving is enabled, else false.
9039     *
9040     * @see #setSaveEnabled(boolean)
9041     * @attr ref android.R.styleable#View_saveEnabled
9042     */
9043    public boolean isSaveEnabled() {
9044        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
9045    }
9046
9047    /**
9048     * Controls whether the saving of this view's state is
9049     * enabled (that is, whether its {@link #onSaveInstanceState} method
9050     * will be called).  Note that even if freezing is enabled, the
9051     * view still must have an id assigned to it (via {@link #setId(int)})
9052     * for its state to be saved.  This flag can only disable the
9053     * saving of this view; any child views may still have their state saved.
9054     *
9055     * @param enabled Set to false to <em>disable</em> state saving, or true
9056     * (the default) to allow it.
9057     *
9058     * @see #isSaveEnabled()
9059     * @see #setId(int)
9060     * @see #onSaveInstanceState()
9061     * @attr ref android.R.styleable#View_saveEnabled
9062     */
9063    public void setSaveEnabled(boolean enabled) {
9064        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
9065    }
9066
9067    /**
9068     * Gets whether the framework should discard touches when the view's
9069     * window is obscured by another visible window.
9070     * Refer to the {@link View} security documentation for more details.
9071     *
9072     * @return True if touch filtering is enabled.
9073     *
9074     * @see #setFilterTouchesWhenObscured(boolean)
9075     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9076     */
9077    @ViewDebug.ExportedProperty
9078    public boolean getFilterTouchesWhenObscured() {
9079        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
9080    }
9081
9082    /**
9083     * Sets whether the framework should discard touches when the view's
9084     * window is obscured by another visible window.
9085     * Refer to the {@link View} security documentation for more details.
9086     *
9087     * @param enabled True if touch filtering should be enabled.
9088     *
9089     * @see #getFilterTouchesWhenObscured
9090     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9091     */
9092    public void setFilterTouchesWhenObscured(boolean enabled) {
9093        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
9094                FILTER_TOUCHES_WHEN_OBSCURED);
9095    }
9096
9097    /**
9098     * Indicates whether the entire hierarchy under this view will save its
9099     * state when a state saving traversal occurs from its parent.  The default
9100     * is true; if false, these views will not be saved unless
9101     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9102     *
9103     * @return Returns true if the view state saving from parent is enabled, else false.
9104     *
9105     * @see #setSaveFromParentEnabled(boolean)
9106     */
9107    public boolean isSaveFromParentEnabled() {
9108        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
9109    }
9110
9111    /**
9112     * Controls whether the entire hierarchy under this view will save its
9113     * state when a state saving traversal occurs from its parent.  The default
9114     * is true; if false, these views will not be saved unless
9115     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9116     *
9117     * @param enabled Set to false to <em>disable</em> state saving, or true
9118     * (the default) to allow it.
9119     *
9120     * @see #isSaveFromParentEnabled()
9121     * @see #setId(int)
9122     * @see #onSaveInstanceState()
9123     */
9124    public void setSaveFromParentEnabled(boolean enabled) {
9125        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
9126    }
9127
9128
9129    /**
9130     * Returns whether this View is currently able to take focus.
9131     *
9132     * @return True if this view can take focus, or false otherwise.
9133     */
9134    @ViewDebug.ExportedProperty(category = "focus")
9135    public final boolean isFocusable() {
9136        return FOCUSABLE == (mViewFlags & FOCUSABLE);
9137    }
9138
9139    /**
9140     * Returns the focusable setting for this view.
9141     *
9142     * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}.
9143     * @attr ref android.R.styleable#View_focusable
9144     */
9145    @ViewDebug.ExportedProperty(mapping = {
9146            @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"),
9147            @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"),
9148            @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO")
9149            })
9150    @Focusable
9151    public int getFocusable() {
9152        return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
9153    }
9154
9155    /**
9156     * When a view is focusable, it may not want to take focus when in touch mode.
9157     * For example, a button would like focus when the user is navigating via a D-pad
9158     * so that the user can click on it, but once the user starts touching the screen,
9159     * the button shouldn't take focus
9160     * @return Whether the view is focusable in touch mode.
9161     * @attr ref android.R.styleable#View_focusableInTouchMode
9162     */
9163    @ViewDebug.ExportedProperty
9164    public final boolean isFocusableInTouchMode() {
9165        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
9166    }
9167
9168    /**
9169     * Find the nearest view in the specified direction that can take focus.
9170     * This does not actually give focus to that view.
9171     *
9172     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9173     *
9174     * @return The nearest focusable in the specified direction, or null if none
9175     *         can be found.
9176     */
9177    public View focusSearch(@FocusRealDirection int direction) {
9178        if (mParent != null) {
9179            return mParent.focusSearch(this, direction);
9180        } else {
9181            return null;
9182        }
9183    }
9184
9185    /**
9186     * Returns whether this View is a root of a keyboard navigation cluster.
9187     *
9188     * @return True if this view is a root of a cluster, or false otherwise.
9189     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9190     */
9191    @ViewDebug.ExportedProperty(category = "keyboardNavigationCluster")
9192    public final boolean isKeyboardNavigationCluster() {
9193        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
9194    }
9195
9196    /**
9197     * Set whether this view is a root of a keyboard navigation cluster.
9198     *
9199     * @param isCluster If true, this view is a root of a cluster.
9200     *
9201     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9202     */
9203    public void setKeyboardNavigationCluster(boolean isCluster) {
9204        if (isCluster) {
9205            mPrivateFlags3 |= PFLAG3_CLUSTER;
9206        } else {
9207            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
9208        }
9209    }
9210
9211    /**
9212     * Returns whether this View should receive focus when the focus is restored for the view
9213     * hierarchy containing this view.
9214     * <p>
9215     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9216     * window or serves as a target of cluster navigation.
9217     *
9218     * @see #restoreDefaultFocus(int)
9219     *
9220     * @return {@code true} if this view is the default-focus view, {@code false} otherwise
9221     * @attr ref android.R.styleable#View_focusedByDefault
9222     */
9223    @ViewDebug.ExportedProperty(category = "focusedByDefault")
9224    public final boolean isFocusedByDefault() {
9225        return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
9226    }
9227
9228    /**
9229     * Sets whether this View should receive focus when the focus is restored for the view
9230     * hierarchy containing this view.
9231     * <p>
9232     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9233     * window or serves as a target of cluster navigation.
9234     *
9235     * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
9236     *                           {@code false} otherwise.
9237     *
9238     * @see #restoreDefaultFocus(int)
9239     *
9240     * @attr ref android.R.styleable#View_focusedByDefault
9241     */
9242    public void setFocusedByDefault(boolean isFocusedByDefault) {
9243        if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
9244            return;
9245        }
9246
9247        if (isFocusedByDefault) {
9248            mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
9249        } else {
9250            mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
9251        }
9252
9253        if (mParent instanceof ViewGroup) {
9254            if (isFocusedByDefault) {
9255                ((ViewGroup) mParent).setDefaultFocus(this);
9256            } else {
9257                ((ViewGroup) mParent).cleanDefaultFocus(this);
9258            }
9259        }
9260    }
9261
9262    /**
9263     * Returns whether the view hierarchy with this view as a root contain a default-focus view.
9264     *
9265     * @return {@code true} if this view has default focus, {@code false} otherwise
9266     */
9267    boolean hasDefaultFocus() {
9268        return isFocusedByDefault();
9269    }
9270
9271    /**
9272     * Find the nearest keyboard navigation cluster in the specified direction.
9273     * This does not actually give focus to that cluster.
9274     *
9275     * @param currentCluster The starting point of the search. Null means the current cluster is not
9276     *                       found yet
9277     * @param direction Direction to look
9278     *
9279     * @return The nearest keyboard navigation cluster in the specified direction, or null if none
9280     *         can be found
9281     */
9282    public View keyboardNavigationClusterSearch(View currentCluster, int direction) {
9283        if (isKeyboardNavigationCluster()) {
9284            currentCluster = this;
9285        }
9286        if (isRootNamespace()) {
9287            // Root namespace means we should consider ourselves the top of the
9288            // tree for group searching; otherwise we could be group searching
9289            // into other tabs.  see LocalActivityManager and TabHost for more info.
9290            return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
9291                    this, currentCluster, direction);
9292        } else if (mParent != null) {
9293            return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
9294        }
9295        return null;
9296    }
9297
9298    /**
9299     * This method is the last chance for the focused view and its ancestors to
9300     * respond to an arrow key. This is called when the focused view did not
9301     * consume the key internally, nor could the view system find a new view in
9302     * the requested direction to give focus to.
9303     *
9304     * @param focused The currently focused view.
9305     * @param direction The direction focus wants to move. One of FOCUS_UP,
9306     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
9307     * @return True if the this view consumed this unhandled move.
9308     */
9309    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
9310        return false;
9311    }
9312
9313    /**
9314     * If a user manually specified the next view id for a particular direction,
9315     * use the root to look up the view.
9316     * @param root The root view of the hierarchy containing this view.
9317     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
9318     * or FOCUS_BACKWARD.
9319     * @return The user specified next view, or null if there is none.
9320     */
9321    View findUserSetNextFocus(View root, @FocusDirection int direction) {
9322        switch (direction) {
9323            case FOCUS_LEFT:
9324                if (mNextFocusLeftId == View.NO_ID) return null;
9325                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
9326            case FOCUS_RIGHT:
9327                if (mNextFocusRightId == View.NO_ID) return null;
9328                return findViewInsideOutShouldExist(root, mNextFocusRightId);
9329            case FOCUS_UP:
9330                if (mNextFocusUpId == View.NO_ID) return null;
9331                return findViewInsideOutShouldExist(root, mNextFocusUpId);
9332            case FOCUS_DOWN:
9333                if (mNextFocusDownId == View.NO_ID) return null;
9334                return findViewInsideOutShouldExist(root, mNextFocusDownId);
9335            case FOCUS_FORWARD:
9336                if (mNextFocusForwardId == View.NO_ID) return null;
9337                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
9338            case FOCUS_BACKWARD: {
9339                if (mID == View.NO_ID) return null;
9340                final int id = mID;
9341                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
9342                    @Override
9343                    public boolean apply(View t) {
9344                        return t.mNextFocusForwardId == id;
9345                    }
9346                });
9347            }
9348        }
9349        return null;
9350    }
9351
9352    private View findViewInsideOutShouldExist(View root, int id) {
9353        if (mMatchIdPredicate == null) {
9354            mMatchIdPredicate = new MatchIdPredicate();
9355        }
9356        mMatchIdPredicate.mId = id;
9357        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
9358        if (result == null) {
9359            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
9360        }
9361        return result;
9362    }
9363
9364    /**
9365     * Find and return all focusable views that are descendants of this view,
9366     * possibly including this view if it is focusable itself.
9367     *
9368     * @param direction The direction of the focus
9369     * @return A list of focusable views
9370     */
9371    public ArrayList<View> getFocusables(@FocusDirection int direction) {
9372        ArrayList<View> result = new ArrayList<View>(24);
9373        addFocusables(result, direction);
9374        return result;
9375    }
9376
9377    /**
9378     * Add any focusable views that are descendants of this view (possibly
9379     * including this view if it is focusable itself) to views.  If we are in touch mode,
9380     * only add views that are also focusable in touch mode.
9381     *
9382     * @param views Focusable views found so far
9383     * @param direction The direction of the focus
9384     */
9385    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
9386        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
9387    }
9388
9389    /**
9390     * Adds any focusable views that are descendants of this view (possibly
9391     * including this view if it is focusable itself) to views. This method
9392     * adds all focusable views regardless if we are in touch mode or
9393     * only views focusable in touch mode if we are in touch mode or
9394     * only views that can take accessibility focus if accessibility is enabled
9395     * depending on the focusable mode parameter.
9396     *
9397     * @param views Focusable views found so far or null if all we are interested is
9398     *        the number of focusables.
9399     * @param direction The direction of the focus.
9400     * @param focusableMode The type of focusables to be added.
9401     *
9402     * @see #FOCUSABLES_ALL
9403     * @see #FOCUSABLES_TOUCH_MODE
9404     */
9405    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
9406            @FocusableMode int focusableMode) {
9407        if (views == null) {
9408            return;
9409        }
9410        if (!isFocusable()) {
9411            return;
9412        }
9413        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
9414                && !isFocusableInTouchMode()) {
9415            return;
9416        }
9417        views.add(this);
9418    }
9419
9420    /**
9421     * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
9422     * including this view if it is a cluster root itself) to views.
9423     *
9424     * @param views Keyboard navigation cluster roots found so far
9425     * @param direction Direction to look
9426     */
9427    public void addKeyboardNavigationClusters(
9428            @NonNull Collection<View> views,
9429            int direction) {
9430        if (!(isKeyboardNavigationCluster())) {
9431            return;
9432        }
9433        views.add(this);
9434    }
9435
9436    /**
9437     * Finds the Views that contain given text. The containment is case insensitive.
9438     * The search is performed by either the text that the View renders or the content
9439     * description that describes the view for accessibility purposes and the view does
9440     * not render or both. Clients can specify how the search is to be performed via
9441     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
9442     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
9443     *
9444     * @param outViews The output list of matching Views.
9445     * @param searched The text to match against.
9446     *
9447     * @see #FIND_VIEWS_WITH_TEXT
9448     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
9449     * @see #setContentDescription(CharSequence)
9450     */
9451    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
9452            @FindViewFlags int flags) {
9453        if (getAccessibilityNodeProvider() != null) {
9454            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
9455                outViews.add(this);
9456            }
9457        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
9458                && (searched != null && searched.length() > 0)
9459                && (mContentDescription != null && mContentDescription.length() > 0)) {
9460            String searchedLowerCase = searched.toString().toLowerCase();
9461            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
9462            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
9463                outViews.add(this);
9464            }
9465        }
9466    }
9467
9468    /**
9469     * Find and return all touchable views that are descendants of this view,
9470     * possibly including this view if it is touchable itself.
9471     *
9472     * @return A list of touchable views
9473     */
9474    public ArrayList<View> getTouchables() {
9475        ArrayList<View> result = new ArrayList<View>();
9476        addTouchables(result);
9477        return result;
9478    }
9479
9480    /**
9481     * Add any touchable views that are descendants of this view (possibly
9482     * including this view if it is touchable itself) to views.
9483     *
9484     * @param views Touchable views found so far
9485     */
9486    public void addTouchables(ArrayList<View> views) {
9487        final int viewFlags = mViewFlags;
9488
9489        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
9490                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
9491                && (viewFlags & ENABLED_MASK) == ENABLED) {
9492            views.add(this);
9493        }
9494    }
9495
9496    /**
9497     * Returns whether this View is accessibility focused.
9498     *
9499     * @return True if this View is accessibility focused.
9500     */
9501    public boolean isAccessibilityFocused() {
9502        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
9503    }
9504
9505    /**
9506     * Call this to try to give accessibility focus to this view.
9507     *
9508     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
9509     * returns false or the view is no visible or the view already has accessibility
9510     * focus.
9511     *
9512     * See also {@link #focusSearch(int)}, which is what you call to say that you
9513     * have focus, and you want your parent to look for the next one.
9514     *
9515     * @return Whether this view actually took accessibility focus.
9516     *
9517     * @hide
9518     */
9519    public boolean requestAccessibilityFocus() {
9520        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
9521        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
9522            return false;
9523        }
9524        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9525            return false;
9526        }
9527        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
9528            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
9529            ViewRootImpl viewRootImpl = getViewRootImpl();
9530            if (viewRootImpl != null) {
9531                viewRootImpl.setAccessibilityFocus(this, null);
9532            }
9533            invalidate();
9534            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
9535            return true;
9536        }
9537        return false;
9538    }
9539
9540    /**
9541     * Call this to try to clear accessibility focus of this view.
9542     *
9543     * See also {@link #focusSearch(int)}, which is what you call to say that you
9544     * have focus, and you want your parent to look for the next one.
9545     *
9546     * @hide
9547     */
9548    public void clearAccessibilityFocus() {
9549        clearAccessibilityFocusNoCallbacks(0);
9550
9551        // Clear the global reference of accessibility focus if this view or
9552        // any of its descendants had accessibility focus. This will NOT send
9553        // an event or update internal state if focus is cleared from a
9554        // descendant view, which may leave views in inconsistent states.
9555        final ViewRootImpl viewRootImpl = getViewRootImpl();
9556        if (viewRootImpl != null) {
9557            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
9558            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9559                viewRootImpl.setAccessibilityFocus(null, null);
9560            }
9561        }
9562    }
9563
9564    private void sendAccessibilityHoverEvent(int eventType) {
9565        // Since we are not delivering to a client accessibility events from not
9566        // important views (unless the clinet request that) we need to fire the
9567        // event from the deepest view exposed to the client. As a consequence if
9568        // the user crosses a not exposed view the client will see enter and exit
9569        // of the exposed predecessor followed by and enter and exit of that same
9570        // predecessor when entering and exiting the not exposed descendant. This
9571        // is fine since the client has a clear idea which view is hovered at the
9572        // price of a couple more events being sent. This is a simple and
9573        // working solution.
9574        View source = this;
9575        while (true) {
9576            if (source.includeForAccessibility()) {
9577                source.sendAccessibilityEvent(eventType);
9578                return;
9579            }
9580            ViewParent parent = source.getParent();
9581            if (parent instanceof View) {
9582                source = (View) parent;
9583            } else {
9584                return;
9585            }
9586        }
9587    }
9588
9589    /**
9590     * Clears accessibility focus without calling any callback methods
9591     * normally invoked in {@link #clearAccessibilityFocus()}. This method
9592     * is used separately from that one for clearing accessibility focus when
9593     * giving this focus to another view.
9594     *
9595     * @param action The action, if any, that led to focus being cleared. Set to
9596     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
9597     * the window.
9598     */
9599    void clearAccessibilityFocusNoCallbacks(int action) {
9600        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
9601            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
9602            invalidate();
9603            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9604                AccessibilityEvent event = AccessibilityEvent.obtain(
9605                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
9606                event.setAction(action);
9607                if (mAccessibilityDelegate != null) {
9608                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
9609                } else {
9610                    sendAccessibilityEventUnchecked(event);
9611                }
9612            }
9613        }
9614    }
9615
9616    /**
9617     * Call this to try to give focus to a specific view or to one of its
9618     * descendants.
9619     *
9620     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9621     * false), or if it is focusable and it is not focusable in touch mode
9622     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9623     *
9624     * See also {@link #focusSearch(int)}, which is what you call to say that you
9625     * have focus, and you want your parent to look for the next one.
9626     *
9627     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
9628     * {@link #FOCUS_DOWN} and <code>null</code>.
9629     *
9630     * @return Whether this view or one of its descendants actually took focus.
9631     */
9632    public final boolean requestFocus() {
9633        return requestFocus(View.FOCUS_DOWN);
9634    }
9635
9636    /**
9637     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
9638     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
9639     * Nested keyboard navigation clusters are excluded from the hierarchy.
9640     *
9641     * @param direction The direction of the focus
9642     * @return Whether this view or one of its descendants actually took focus
9643     */
9644    public boolean restoreDefaultFocus(@FocusDirection int direction) {
9645        return requestFocus(direction);
9646    }
9647
9648    /**
9649     * Call this to try to give focus to a specific view or to one of its
9650     * descendants and give it a hint about what direction focus is heading.
9651     *
9652     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9653     * false), or if it is focusable and it is not focusable in touch mode
9654     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9655     *
9656     * See also {@link #focusSearch(int)}, which is what you call to say that you
9657     * have focus, and you want your parent to look for the next one.
9658     *
9659     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9660     * <code>null</code> set for the previously focused rectangle.
9661     *
9662     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9663     * @return Whether this view or one of its descendants actually took focus.
9664     */
9665    public final boolean requestFocus(int direction) {
9666        return requestFocus(direction, null);
9667    }
9668
9669    /**
9670     * Call this to try to give focus to a specific view or to one of its descendants
9671     * and give it hints about the direction and a specific rectangle that the focus
9672     * is coming from.  The rectangle can help give larger views a finer grained hint
9673     * about where focus is coming from, and therefore, where to show selection, or
9674     * forward focus change internally.
9675     *
9676     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9677     * false), or if it is focusable and it is not focusable in touch mode
9678     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9679     *
9680     * A View will not take focus if it is not visible.
9681     *
9682     * A View will not take focus if one of its parents has
9683     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9684     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9685     *
9686     * See also {@link #focusSearch(int)}, which is what you call to say that you
9687     * have focus, and you want your parent to look for the next one.
9688     *
9689     * You may wish to override this method if your custom {@link View} has an internal
9690     * {@link View} that it wishes to forward the request to.
9691     *
9692     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9693     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9694     *        to give a finer grained hint about where focus is coming from.  May be null
9695     *        if there is no hint.
9696     * @return Whether this view or one of its descendants actually took focus.
9697     */
9698    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9699        return requestFocusNoSearch(direction, previouslyFocusedRect);
9700    }
9701
9702    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9703        // need to be focusable
9704        if ((mViewFlags & FOCUSABLE) != FOCUSABLE
9705                || (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9706            return false;
9707        }
9708
9709        // need to be focusable in touch mode if in touch mode
9710        if (isInTouchMode() &&
9711            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9712               return false;
9713        }
9714
9715        // need to not have any parents blocking us
9716        if (hasAncestorThatBlocksDescendantFocus()) {
9717            return false;
9718        }
9719
9720        handleFocusGainInternal(direction, previouslyFocusedRect);
9721        return true;
9722    }
9723
9724    /**
9725     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9726     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9727     * touch mode to request focus when they are touched.
9728     *
9729     * @return Whether this view or one of its descendants actually took focus.
9730     *
9731     * @see #isInTouchMode()
9732     *
9733     */
9734    public final boolean requestFocusFromTouch() {
9735        // Leave touch mode if we need to
9736        if (isInTouchMode()) {
9737            ViewRootImpl viewRoot = getViewRootImpl();
9738            if (viewRoot != null) {
9739                viewRoot.ensureTouchMode(false);
9740            }
9741        }
9742        return requestFocus(View.FOCUS_DOWN);
9743    }
9744
9745    /**
9746     * @return Whether any ancestor of this view blocks descendant focus.
9747     */
9748    private boolean hasAncestorThatBlocksDescendantFocus() {
9749        final boolean focusableInTouchMode = isFocusableInTouchMode();
9750        ViewParent ancestor = mParent;
9751        while (ancestor instanceof ViewGroup) {
9752            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9753            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9754                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9755                return true;
9756            } else {
9757                ancestor = vgAncestor.getParent();
9758            }
9759        }
9760        return false;
9761    }
9762
9763    /**
9764     * Gets the mode for determining whether this View is important for accessibility.
9765     * A view is important for accessibility if it fires accessibility events and if it
9766     * is reported to accessibility services that query the screen.
9767     *
9768     * @return The mode for determining whether a view is important for accessibility, one
9769     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
9770     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
9771     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
9772     *
9773     * @attr ref android.R.styleable#View_importantForAccessibility
9774     *
9775     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9776     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9777     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9778     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9779     */
9780    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9781            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9782            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9783            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9784            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9785                    to = "noHideDescendants")
9786        })
9787    public int getImportantForAccessibility() {
9788        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9789                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9790    }
9791
9792    /**
9793     * Sets the live region mode for this view. This indicates to accessibility
9794     * services whether they should automatically notify the user about changes
9795     * to the view's content description or text, or to the content descriptions
9796     * or text of the view's children (where applicable).
9797     * <p>
9798     * For example, in a login screen with a TextView that displays an "incorrect
9799     * password" notification, that view should be marked as a live region with
9800     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9801     * <p>
9802     * To disable change notifications for this view, use
9803     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9804     * mode for most views.
9805     * <p>
9806     * To indicate that the user should be notified of changes, use
9807     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9808     * <p>
9809     * If the view's changes should interrupt ongoing speech and notify the user
9810     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9811     *
9812     * @param mode The live region mode for this view, one of:
9813     *        <ul>
9814     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9815     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9816     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9817     *        </ul>
9818     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9819     */
9820    public void setAccessibilityLiveRegion(int mode) {
9821        if (mode != getAccessibilityLiveRegion()) {
9822            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9823            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9824                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9825            notifyViewAccessibilityStateChangedIfNeeded(
9826                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9827        }
9828    }
9829
9830    /**
9831     * Gets the live region mode for this View.
9832     *
9833     * @return The live region mode for the view.
9834     *
9835     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9836     *
9837     * @see #setAccessibilityLiveRegion(int)
9838     */
9839    public int getAccessibilityLiveRegion() {
9840        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9841                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9842    }
9843
9844    /**
9845     * Sets how to determine whether this view is important for accessibility
9846     * which is if it fires accessibility events and if it is reported to
9847     * accessibility services that query the screen.
9848     *
9849     * @param mode How to determine whether this view is important for accessibility.
9850     *
9851     * @attr ref android.R.styleable#View_importantForAccessibility
9852     *
9853     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9854     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9855     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9856     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9857     */
9858    public void setImportantForAccessibility(int mode) {
9859        final int oldMode = getImportantForAccessibility();
9860        if (mode != oldMode) {
9861            final boolean hideDescendants =
9862                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9863
9864            // If this node or its descendants are no longer important, try to
9865            // clear accessibility focus.
9866            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9867                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9868                if (focusHost != null) {
9869                    focusHost.clearAccessibilityFocus();
9870                }
9871            }
9872
9873            // If we're moving between AUTO and another state, we might not need
9874            // to send a subtree changed notification. We'll store the computed
9875            // importance, since we'll need to check it later to make sure.
9876            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9877                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9878            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9879            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9880            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9881                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9882            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9883                notifySubtreeAccessibilityStateChangedIfNeeded();
9884            } else {
9885                notifyViewAccessibilityStateChangedIfNeeded(
9886                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9887            }
9888        }
9889    }
9890
9891    /**
9892     * Returns the view within this view's hierarchy that is hosting
9893     * accessibility focus.
9894     *
9895     * @param searchDescendants whether to search for focus in descendant views
9896     * @return the view hosting accessibility focus, or {@code null}
9897     */
9898    private View findAccessibilityFocusHost(boolean searchDescendants) {
9899        if (isAccessibilityFocusedViewOrHost()) {
9900            return this;
9901        }
9902
9903        if (searchDescendants) {
9904            final ViewRootImpl viewRoot = getViewRootImpl();
9905            if (viewRoot != null) {
9906                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9907                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9908                    return focusHost;
9909                }
9910            }
9911        }
9912
9913        return null;
9914    }
9915
9916    /**
9917     * Computes whether this view should be exposed for accessibility. In
9918     * general, views that are interactive or provide information are exposed
9919     * while views that serve only as containers are hidden.
9920     * <p>
9921     * If an ancestor of this view has importance
9922     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9923     * returns <code>false</code>.
9924     * <p>
9925     * Otherwise, the value is computed according to the view's
9926     * {@link #getImportantForAccessibility()} value:
9927     * <ol>
9928     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9929     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9930     * </code>
9931     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9932     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9933     * view satisfies any of the following:
9934     * <ul>
9935     * <li>Is actionable, e.g. {@link #isClickable()},
9936     * {@link #isLongClickable()}, or {@link #isFocusable()}
9937     * <li>Has an {@link AccessibilityDelegate}
9938     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9939     * {@link OnKeyListener}, etc.
9940     * <li>Is an accessibility live region, e.g.
9941     * {@link #getAccessibilityLiveRegion()} is not
9942     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9943     * </ul>
9944     * </ol>
9945     *
9946     * @return Whether the view is exposed for accessibility.
9947     * @see #setImportantForAccessibility(int)
9948     * @see #getImportantForAccessibility()
9949     */
9950    public boolean isImportantForAccessibility() {
9951        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9952                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9953        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9954                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9955            return false;
9956        }
9957
9958        // Check parent mode to ensure we're not hidden.
9959        ViewParent parent = mParent;
9960        while (parent instanceof View) {
9961            if (((View) parent).getImportantForAccessibility()
9962                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9963                return false;
9964            }
9965            parent = parent.getParent();
9966        }
9967
9968        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9969                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9970                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9971    }
9972
9973    /**
9974     * Gets the parent for accessibility purposes. Note that the parent for
9975     * accessibility is not necessary the immediate parent. It is the first
9976     * predecessor that is important for accessibility.
9977     *
9978     * @return The parent for accessibility purposes.
9979     */
9980    public ViewParent getParentForAccessibility() {
9981        if (mParent instanceof View) {
9982            View parentView = (View) mParent;
9983            if (parentView.includeForAccessibility()) {
9984                return mParent;
9985            } else {
9986                return mParent.getParentForAccessibility();
9987            }
9988        }
9989        return null;
9990    }
9991
9992    /**
9993     * Adds the children of this View relevant for accessibility to the given list
9994     * as output. Since some Views are not important for accessibility the added
9995     * child views are not necessarily direct children of this view, rather they are
9996     * the first level of descendants important for accessibility.
9997     *
9998     * @param outChildren The output list that will receive children for accessibility.
9999     */
10000    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
10001
10002    }
10003
10004    /**
10005     * Whether to regard this view for accessibility. A view is regarded for
10006     * accessibility if it is important for accessibility or the querying
10007     * accessibility service has explicitly requested that view not
10008     * important for accessibility are regarded.
10009     *
10010     * @return Whether to regard the view for accessibility.
10011     *
10012     * @hide
10013     */
10014    public boolean includeForAccessibility() {
10015        if (mAttachInfo != null) {
10016            return (mAttachInfo.mAccessibilityFetchFlags
10017                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
10018                    || isImportantForAccessibility();
10019        }
10020        return false;
10021    }
10022
10023    /**
10024     * Returns whether the View is considered actionable from
10025     * accessibility perspective. Such view are important for
10026     * accessibility.
10027     *
10028     * @return True if the view is actionable for accessibility.
10029     *
10030     * @hide
10031     */
10032    public boolean isActionableForAccessibility() {
10033        return (isClickable() || isLongClickable() || isFocusable());
10034    }
10035
10036    /**
10037     * Returns whether the View has registered callbacks which makes it
10038     * important for accessibility.
10039     *
10040     * @return True if the view is actionable for accessibility.
10041     */
10042    private boolean hasListenersForAccessibility() {
10043        ListenerInfo info = getListenerInfo();
10044        return mTouchDelegate != null || info.mOnKeyListener != null
10045                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
10046                || info.mOnHoverListener != null || info.mOnDragListener != null;
10047    }
10048
10049    /**
10050     * Notifies that the accessibility state of this view changed. The change
10051     * is local to this view and does not represent structural changes such
10052     * as children and parent. For example, the view became focusable. The
10053     * notification is at at most once every
10054     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10055     * to avoid unnecessary load to the system. Also once a view has a pending
10056     * notification this method is a NOP until the notification has been sent.
10057     *
10058     * @hide
10059     */
10060    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
10061        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10062            return;
10063        }
10064        if (mSendViewStateChangedAccessibilityEvent == null) {
10065            mSendViewStateChangedAccessibilityEvent =
10066                    new SendViewStateChangedAccessibilityEvent();
10067        }
10068        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
10069    }
10070
10071    /**
10072     * Notifies that the accessibility state of this view changed. The change
10073     * is *not* local to this view and does represent structural changes such
10074     * as children and parent. For example, the view size changed. The
10075     * notification is at at most once every
10076     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10077     * to avoid unnecessary load to the system. Also once a view has a pending
10078     * notification this method is a NOP until the notification has been sent.
10079     *
10080     * @hide
10081     */
10082    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
10083        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10084            return;
10085        }
10086        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
10087            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10088            if (mParent != null) {
10089                try {
10090                    mParent.notifySubtreeAccessibilityStateChanged(
10091                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
10092                } catch (AbstractMethodError e) {
10093                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10094                            " does not fully implement ViewParent", e);
10095                }
10096            }
10097        }
10098    }
10099
10100    /**
10101     * Change the visibility of the View without triggering any other changes. This is
10102     * important for transitions, where visibility changes should not adjust focus or
10103     * trigger a new layout. This is only used when the visibility has already been changed
10104     * and we need a transient value during an animation. When the animation completes,
10105     * the original visibility value is always restored.
10106     *
10107     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
10108     * @hide
10109     */
10110    public void setTransitionVisibility(@Visibility int visibility) {
10111        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
10112    }
10113
10114    /**
10115     * Reset the flag indicating the accessibility state of the subtree rooted
10116     * at this view changed.
10117     */
10118    void resetSubtreeAccessibilityStateChanged() {
10119        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10120    }
10121
10122    /**
10123     * Report an accessibility action to this view's parents for delegated processing.
10124     *
10125     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
10126     * call this method to delegate an accessibility action to a supporting parent. If the parent
10127     * returns true from its
10128     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
10129     * method this method will return true to signify that the action was consumed.</p>
10130     *
10131     * <p>This method is useful for implementing nested scrolling child views. If
10132     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
10133     * a custom view implementation may invoke this method to allow a parent to consume the
10134     * scroll first. If this method returns true the custom view should skip its own scrolling
10135     * behavior.</p>
10136     *
10137     * @param action Accessibility action to delegate
10138     * @param arguments Optional action arguments
10139     * @return true if the action was consumed by a parent
10140     */
10141    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
10142        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
10143            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
10144                return true;
10145            }
10146        }
10147        return false;
10148    }
10149
10150    /**
10151     * Performs the specified accessibility action on the view. For
10152     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
10153     * <p>
10154     * If an {@link AccessibilityDelegate} has been specified via calling
10155     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
10156     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
10157     * is responsible for handling this call.
10158     * </p>
10159     *
10160     * <p>The default implementation will delegate
10161     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
10162     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
10163     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
10164     *
10165     * @param action The action to perform.
10166     * @param arguments Optional action arguments.
10167     * @return Whether the action was performed.
10168     */
10169    public boolean performAccessibilityAction(int action, Bundle arguments) {
10170      if (mAccessibilityDelegate != null) {
10171          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
10172      } else {
10173          return performAccessibilityActionInternal(action, arguments);
10174      }
10175    }
10176
10177   /**
10178    * @see #performAccessibilityAction(int, Bundle)
10179    *
10180    * Note: Called from the default {@link AccessibilityDelegate}.
10181    *
10182    * @hide
10183    */
10184    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
10185        if (isNestedScrollingEnabled()
10186                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
10187                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
10188                || action == R.id.accessibilityActionScrollUp
10189                || action == R.id.accessibilityActionScrollLeft
10190                || action == R.id.accessibilityActionScrollDown
10191                || action == R.id.accessibilityActionScrollRight)) {
10192            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
10193                return true;
10194            }
10195        }
10196
10197        switch (action) {
10198            case AccessibilityNodeInfo.ACTION_CLICK: {
10199                if (isClickable()) {
10200                    performClick();
10201                    return true;
10202                }
10203            } break;
10204            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
10205                if (isLongClickable()) {
10206                    performLongClick();
10207                    return true;
10208                }
10209            } break;
10210            case AccessibilityNodeInfo.ACTION_FOCUS: {
10211                if (!hasFocus()) {
10212                    // Get out of touch mode since accessibility
10213                    // wants to move focus around.
10214                    getViewRootImpl().ensureTouchMode(false);
10215                    return requestFocus();
10216                }
10217            } break;
10218            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
10219                if (hasFocus()) {
10220                    clearFocus();
10221                    return !isFocused();
10222                }
10223            } break;
10224            case AccessibilityNodeInfo.ACTION_SELECT: {
10225                if (!isSelected()) {
10226                    setSelected(true);
10227                    return isSelected();
10228                }
10229            } break;
10230            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
10231                if (isSelected()) {
10232                    setSelected(false);
10233                    return !isSelected();
10234                }
10235            } break;
10236            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
10237                if (!isAccessibilityFocused()) {
10238                    return requestAccessibilityFocus();
10239                }
10240            } break;
10241            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
10242                if (isAccessibilityFocused()) {
10243                    clearAccessibilityFocus();
10244                    return true;
10245                }
10246            } break;
10247            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
10248                if (arguments != null) {
10249                    final int granularity = arguments.getInt(
10250                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10251                    final boolean extendSelection = arguments.getBoolean(
10252                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10253                    return traverseAtGranularity(granularity, true, extendSelection);
10254                }
10255            } break;
10256            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
10257                if (arguments != null) {
10258                    final int granularity = arguments.getInt(
10259                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10260                    final boolean extendSelection = arguments.getBoolean(
10261                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10262                    return traverseAtGranularity(granularity, false, extendSelection);
10263                }
10264            } break;
10265            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
10266                CharSequence text = getIterableTextForAccessibility();
10267                if (text == null) {
10268                    return false;
10269                }
10270                final int start = (arguments != null) ? arguments.getInt(
10271                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
10272                final int end = (arguments != null) ? arguments.getInt(
10273                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
10274                // Only cursor position can be specified (selection length == 0)
10275                if ((getAccessibilitySelectionStart() != start
10276                        || getAccessibilitySelectionEnd() != end)
10277                        && (start == end)) {
10278                    setAccessibilitySelection(start, end);
10279                    notifyViewAccessibilityStateChangedIfNeeded(
10280                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10281                    return true;
10282                }
10283            } break;
10284            case R.id.accessibilityActionShowOnScreen: {
10285                if (mAttachInfo != null) {
10286                    final Rect r = mAttachInfo.mTmpInvalRect;
10287                    getDrawingRect(r);
10288                    return requestRectangleOnScreen(r, true);
10289                }
10290            } break;
10291            case R.id.accessibilityActionContextClick: {
10292                if (isContextClickable()) {
10293                    performContextClick();
10294                    return true;
10295                }
10296            } break;
10297        }
10298        return false;
10299    }
10300
10301    private boolean traverseAtGranularity(int granularity, boolean forward,
10302            boolean extendSelection) {
10303        CharSequence text = getIterableTextForAccessibility();
10304        if (text == null || text.length() == 0) {
10305            return false;
10306        }
10307        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
10308        if (iterator == null) {
10309            return false;
10310        }
10311        int current = getAccessibilitySelectionEnd();
10312        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10313            current = forward ? 0 : text.length();
10314        }
10315        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
10316        if (range == null) {
10317            return false;
10318        }
10319        final int segmentStart = range[0];
10320        final int segmentEnd = range[1];
10321        int selectionStart;
10322        int selectionEnd;
10323        if (extendSelection && isAccessibilitySelectionExtendable()) {
10324            selectionStart = getAccessibilitySelectionStart();
10325            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10326                selectionStart = forward ? segmentStart : segmentEnd;
10327            }
10328            selectionEnd = forward ? segmentEnd : segmentStart;
10329        } else {
10330            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
10331        }
10332        setAccessibilitySelection(selectionStart, selectionEnd);
10333        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
10334                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
10335        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
10336        return true;
10337    }
10338
10339    /**
10340     * Gets the text reported for accessibility purposes.
10341     *
10342     * @return The accessibility text.
10343     *
10344     * @hide
10345     */
10346    public CharSequence getIterableTextForAccessibility() {
10347        return getContentDescription();
10348    }
10349
10350    /**
10351     * Gets whether accessibility selection can be extended.
10352     *
10353     * @return If selection is extensible.
10354     *
10355     * @hide
10356     */
10357    public boolean isAccessibilitySelectionExtendable() {
10358        return false;
10359    }
10360
10361    /**
10362     * @hide
10363     */
10364    public int getAccessibilitySelectionStart() {
10365        return mAccessibilityCursorPosition;
10366    }
10367
10368    /**
10369     * @hide
10370     */
10371    public int getAccessibilitySelectionEnd() {
10372        return getAccessibilitySelectionStart();
10373    }
10374
10375    /**
10376     * @hide
10377     */
10378    public void setAccessibilitySelection(int start, int end) {
10379        if (start ==  end && end == mAccessibilityCursorPosition) {
10380            return;
10381        }
10382        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
10383            mAccessibilityCursorPosition = start;
10384        } else {
10385            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
10386        }
10387        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
10388    }
10389
10390    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
10391            int fromIndex, int toIndex) {
10392        if (mParent == null) {
10393            return;
10394        }
10395        AccessibilityEvent event = AccessibilityEvent.obtain(
10396                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
10397        onInitializeAccessibilityEvent(event);
10398        onPopulateAccessibilityEvent(event);
10399        event.setFromIndex(fromIndex);
10400        event.setToIndex(toIndex);
10401        event.setAction(action);
10402        event.setMovementGranularity(granularity);
10403        mParent.requestSendAccessibilityEvent(this, event);
10404    }
10405
10406    /**
10407     * @hide
10408     */
10409    public TextSegmentIterator getIteratorForGranularity(int granularity) {
10410        switch (granularity) {
10411            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
10412                CharSequence text = getIterableTextForAccessibility();
10413                if (text != null && text.length() > 0) {
10414                    CharacterTextSegmentIterator iterator =
10415                        CharacterTextSegmentIterator.getInstance(
10416                                mContext.getResources().getConfiguration().locale);
10417                    iterator.initialize(text.toString());
10418                    return iterator;
10419                }
10420            } break;
10421            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
10422                CharSequence text = getIterableTextForAccessibility();
10423                if (text != null && text.length() > 0) {
10424                    WordTextSegmentIterator iterator =
10425                        WordTextSegmentIterator.getInstance(
10426                                mContext.getResources().getConfiguration().locale);
10427                    iterator.initialize(text.toString());
10428                    return iterator;
10429                }
10430            } break;
10431            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
10432                CharSequence text = getIterableTextForAccessibility();
10433                if (text != null && text.length() > 0) {
10434                    ParagraphTextSegmentIterator iterator =
10435                        ParagraphTextSegmentIterator.getInstance();
10436                    iterator.initialize(text.toString());
10437                    return iterator;
10438                }
10439            } break;
10440        }
10441        return null;
10442    }
10443
10444    /**
10445     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
10446     * and {@link #onFinishTemporaryDetach()}.
10447     *
10448     * <p>This method always returns {@code true} when called directly or indirectly from
10449     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
10450     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
10451     * <ul>
10452     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
10453     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
10454     * </ul>
10455     * </p>
10456     *
10457     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
10458     * and {@link #onFinishTemporaryDetach()}.
10459     */
10460    public final boolean isTemporarilyDetached() {
10461        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
10462    }
10463
10464    /**
10465     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
10466     * a container View.
10467     */
10468    @CallSuper
10469    public void dispatchStartTemporaryDetach() {
10470        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
10471        onStartTemporaryDetach();
10472    }
10473
10474    /**
10475     * This is called when a container is going to temporarily detach a child, with
10476     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
10477     * It will either be followed by {@link #onFinishTemporaryDetach()} or
10478     * {@link #onDetachedFromWindow()} when the container is done.
10479     */
10480    public void onStartTemporaryDetach() {
10481        removeUnsetPressCallback();
10482        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
10483    }
10484
10485    /**
10486     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
10487     * a container View.
10488     */
10489    @CallSuper
10490    public void dispatchFinishTemporaryDetach() {
10491        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
10492        onFinishTemporaryDetach();
10493        if (hasWindowFocus() && hasFocus()) {
10494            InputMethodManager.getInstance().focusIn(this);
10495        }
10496    }
10497
10498    /**
10499     * Called after {@link #onStartTemporaryDetach} when the container is done
10500     * changing the view.
10501     */
10502    public void onFinishTemporaryDetach() {
10503    }
10504
10505    /**
10506     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
10507     * for this view's window.  Returns null if the view is not currently attached
10508     * to the window.  Normally you will not need to use this directly, but
10509     * just use the standard high-level event callbacks like
10510     * {@link #onKeyDown(int, KeyEvent)}.
10511     */
10512    public KeyEvent.DispatcherState getKeyDispatcherState() {
10513        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
10514    }
10515
10516    /**
10517     * Dispatch a key event before it is processed by any input method
10518     * associated with the view hierarchy.  This can be used to intercept
10519     * key events in special situations before the IME consumes them; a
10520     * typical example would be handling the BACK key to update the application's
10521     * UI instead of allowing the IME to see it and close itself.
10522     *
10523     * @param event The key event to be dispatched.
10524     * @return True if the event was handled, false otherwise.
10525     */
10526    public boolean dispatchKeyEventPreIme(KeyEvent event) {
10527        return onKeyPreIme(event.getKeyCode(), event);
10528    }
10529
10530    /**
10531     * Dispatch a key event to the next view on the focus path. This path runs
10532     * from the top of the view tree down to the currently focused view. If this
10533     * view has focus, it will dispatch to itself. Otherwise it will dispatch
10534     * the next node down the focus path. This method also fires any key
10535     * listeners.
10536     *
10537     * @param event The key event to be dispatched.
10538     * @return True if the event was handled, false otherwise.
10539     */
10540    public boolean dispatchKeyEvent(KeyEvent event) {
10541        if (mInputEventConsistencyVerifier != null) {
10542            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
10543        }
10544
10545        // Give any attached key listener a first crack at the event.
10546        //noinspection SimplifiableIfStatement
10547        ListenerInfo li = mListenerInfo;
10548        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10549                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
10550            return true;
10551        }
10552
10553        if (event.dispatch(this, mAttachInfo != null
10554                ? mAttachInfo.mKeyDispatchState : null, this)) {
10555            return true;
10556        }
10557
10558        if (mInputEventConsistencyVerifier != null) {
10559            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10560        }
10561        return false;
10562    }
10563
10564    /**
10565     * Dispatches a key shortcut event.
10566     *
10567     * @param event The key event to be dispatched.
10568     * @return True if the event was handled by the view, false otherwise.
10569     */
10570    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
10571        return onKeyShortcut(event.getKeyCode(), event);
10572    }
10573
10574    /**
10575     * Pass the touch screen motion event down to the target view, or this
10576     * view if it is the target.
10577     *
10578     * @param event The motion event to be dispatched.
10579     * @return True if the event was handled by the view, false otherwise.
10580     */
10581    public boolean dispatchTouchEvent(MotionEvent event) {
10582        // If the event should be handled by accessibility focus first.
10583        if (event.isTargetAccessibilityFocus()) {
10584            // We don't have focus or no virtual descendant has it, do not handle the event.
10585            if (!isAccessibilityFocusedViewOrHost()) {
10586                return false;
10587            }
10588            // We have focus and got the event, then use normal event dispatch.
10589            event.setTargetAccessibilityFocus(false);
10590        }
10591
10592        boolean result = false;
10593
10594        if (mInputEventConsistencyVerifier != null) {
10595            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
10596        }
10597
10598        final int actionMasked = event.getActionMasked();
10599        if (actionMasked == MotionEvent.ACTION_DOWN) {
10600            // Defensive cleanup for new gesture
10601            stopNestedScroll();
10602        }
10603
10604        if (onFilterTouchEventForSecurity(event)) {
10605            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
10606                result = true;
10607            }
10608            //noinspection SimplifiableIfStatement
10609            ListenerInfo li = mListenerInfo;
10610            if (li != null && li.mOnTouchListener != null
10611                    && (mViewFlags & ENABLED_MASK) == ENABLED
10612                    && li.mOnTouchListener.onTouch(this, event)) {
10613                result = true;
10614            }
10615
10616            if (!result && onTouchEvent(event)) {
10617                result = true;
10618            }
10619        }
10620
10621        if (!result && mInputEventConsistencyVerifier != null) {
10622            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10623        }
10624
10625        // Clean up after nested scrolls if this is the end of a gesture;
10626        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
10627        // of the gesture.
10628        if (actionMasked == MotionEvent.ACTION_UP ||
10629                actionMasked == MotionEvent.ACTION_CANCEL ||
10630                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
10631            stopNestedScroll();
10632        }
10633
10634        return result;
10635    }
10636
10637    boolean isAccessibilityFocusedViewOrHost() {
10638        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
10639                .getAccessibilityFocusedHost() == this);
10640    }
10641
10642    /**
10643     * Filter the touch event to apply security policies.
10644     *
10645     * @param event The motion event to be filtered.
10646     * @return True if the event should be dispatched, false if the event should be dropped.
10647     *
10648     * @see #getFilterTouchesWhenObscured
10649     */
10650    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
10651        //noinspection RedundantIfStatement
10652        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
10653                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
10654            // Window is obscured, drop this touch.
10655            return false;
10656        }
10657        return true;
10658    }
10659
10660    /**
10661     * Pass a trackball motion event down to the focused view.
10662     *
10663     * @param event The motion event to be dispatched.
10664     * @return True if the event was handled by the view, false otherwise.
10665     */
10666    public boolean dispatchTrackballEvent(MotionEvent event) {
10667        if (mInputEventConsistencyVerifier != null) {
10668            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
10669        }
10670
10671        return onTrackballEvent(event);
10672    }
10673
10674    /**
10675     * Pass a captured pointer event down to the focused view.
10676     *
10677     * @param event The motion event to be dispatched.
10678     * @return True if the event was handled by the view, false otherwise.
10679     */
10680    public boolean dispatchCapturedPointerEvent(MotionEvent event) {
10681        if (!hasPointerCapture()) {
10682            return false;
10683        }
10684        //noinspection SimplifiableIfStatement
10685        ListenerInfo li = mListenerInfo;
10686        if (li != null && li.mOnCapturedPointerListener != null
10687                && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) {
10688            return true;
10689        }
10690        return onCapturedPointerEvent(event);
10691    }
10692
10693    /**
10694     * Dispatch a generic motion event.
10695     * <p>
10696     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10697     * are delivered to the view under the pointer.  All other generic motion events are
10698     * delivered to the focused view.  Hover events are handled specially and are delivered
10699     * to {@link #onHoverEvent(MotionEvent)}.
10700     * </p>
10701     *
10702     * @param event The motion event to be dispatched.
10703     * @return True if the event was handled by the view, false otherwise.
10704     */
10705    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10706        if (mInputEventConsistencyVerifier != null) {
10707            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10708        }
10709
10710        final int source = event.getSource();
10711        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10712            final int action = event.getAction();
10713            if (action == MotionEvent.ACTION_HOVER_ENTER
10714                    || action == MotionEvent.ACTION_HOVER_MOVE
10715                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10716                if (dispatchHoverEvent(event)) {
10717                    return true;
10718                }
10719            } else if (dispatchGenericPointerEvent(event)) {
10720                return true;
10721            }
10722        } else if (dispatchGenericFocusedEvent(event)) {
10723            return true;
10724        }
10725
10726        if (dispatchGenericMotionEventInternal(event)) {
10727            return true;
10728        }
10729
10730        if (mInputEventConsistencyVerifier != null) {
10731            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10732        }
10733        return false;
10734    }
10735
10736    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10737        //noinspection SimplifiableIfStatement
10738        ListenerInfo li = mListenerInfo;
10739        if (li != null && li.mOnGenericMotionListener != null
10740                && (mViewFlags & ENABLED_MASK) == ENABLED
10741                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10742            return true;
10743        }
10744
10745        if (onGenericMotionEvent(event)) {
10746            return true;
10747        }
10748
10749        final int actionButton = event.getActionButton();
10750        switch (event.getActionMasked()) {
10751            case MotionEvent.ACTION_BUTTON_PRESS:
10752                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10753                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10754                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10755                    if (performContextClick(event.getX(), event.getY())) {
10756                        mInContextButtonPress = true;
10757                        setPressed(true, event.getX(), event.getY());
10758                        removeTapCallback();
10759                        removeLongPressCallback();
10760                        return true;
10761                    }
10762                }
10763                break;
10764
10765            case MotionEvent.ACTION_BUTTON_RELEASE:
10766                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10767                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10768                    mInContextButtonPress = false;
10769                    mIgnoreNextUpEvent = true;
10770                }
10771                break;
10772        }
10773
10774        if (mInputEventConsistencyVerifier != null) {
10775            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10776        }
10777        return false;
10778    }
10779
10780    /**
10781     * Dispatch a hover event.
10782     * <p>
10783     * Do not call this method directly.
10784     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10785     * </p>
10786     *
10787     * @param event The motion event to be dispatched.
10788     * @return True if the event was handled by the view, false otherwise.
10789     */
10790    protected boolean dispatchHoverEvent(MotionEvent event) {
10791        ListenerInfo li = mListenerInfo;
10792        //noinspection SimplifiableIfStatement
10793        if (li != null && li.mOnHoverListener != null
10794                && (mViewFlags & ENABLED_MASK) == ENABLED
10795                && li.mOnHoverListener.onHover(this, event)) {
10796            return true;
10797        }
10798
10799        return onHoverEvent(event);
10800    }
10801
10802    /**
10803     * Returns true if the view has a child to which it has recently sent
10804     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10805     * it does not have a hovered child, then it must be the innermost hovered view.
10806     * @hide
10807     */
10808    protected boolean hasHoveredChild() {
10809        return false;
10810    }
10811
10812    /**
10813     * Dispatch a generic motion event to the view under the first pointer.
10814     * <p>
10815     * Do not call this method directly.
10816     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10817     * </p>
10818     *
10819     * @param event The motion event to be dispatched.
10820     * @return True if the event was handled by the view, false otherwise.
10821     */
10822    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10823        return false;
10824    }
10825
10826    /**
10827     * Dispatch a generic motion event to the currently focused view.
10828     * <p>
10829     * Do not call this method directly.
10830     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10831     * </p>
10832     *
10833     * @param event The motion event to be dispatched.
10834     * @return True if the event was handled by the view, false otherwise.
10835     */
10836    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10837        return false;
10838    }
10839
10840    /**
10841     * Dispatch a pointer event.
10842     * <p>
10843     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10844     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10845     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10846     * and should not be expected to handle other pointing device features.
10847     * </p>
10848     *
10849     * @param event The motion event to be dispatched.
10850     * @return True if the event was handled by the view, false otherwise.
10851     * @hide
10852     */
10853    public final boolean dispatchPointerEvent(MotionEvent event) {
10854        if (event.isTouchEvent()) {
10855            return dispatchTouchEvent(event);
10856        } else {
10857            return dispatchGenericMotionEvent(event);
10858        }
10859    }
10860
10861    /**
10862     * Called when the window containing this view gains or loses window focus.
10863     * ViewGroups should override to route to their children.
10864     *
10865     * @param hasFocus True if the window containing this view now has focus,
10866     *        false otherwise.
10867     */
10868    public void dispatchWindowFocusChanged(boolean hasFocus) {
10869        onWindowFocusChanged(hasFocus);
10870    }
10871
10872    /**
10873     * Called when the window containing this view gains or loses focus.  Note
10874     * that this is separate from view focus: to receive key events, both
10875     * your view and its window must have focus.  If a window is displayed
10876     * on top of yours that takes input focus, then your own window will lose
10877     * focus but the view focus will remain unchanged.
10878     *
10879     * @param hasWindowFocus True if the window containing this view now has
10880     *        focus, false otherwise.
10881     */
10882    public void onWindowFocusChanged(boolean hasWindowFocus) {
10883        InputMethodManager imm = InputMethodManager.peekInstance();
10884        if (!hasWindowFocus) {
10885            if (isPressed()) {
10886                setPressed(false);
10887            }
10888            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
10889            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10890                imm.focusOut(this);
10891            }
10892            removeLongPressCallback();
10893            removeTapCallback();
10894            onFocusLost();
10895        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10896            imm.focusIn(this);
10897        }
10898        refreshDrawableState();
10899    }
10900
10901    /**
10902     * Returns true if this view is in a window that currently has window focus.
10903     * Note that this is not the same as the view itself having focus.
10904     *
10905     * @return True if this view is in a window that currently has window focus.
10906     */
10907    public boolean hasWindowFocus() {
10908        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10909    }
10910
10911    /**
10912     * Dispatch a view visibility change down the view hierarchy.
10913     * ViewGroups should override to route to their children.
10914     * @param changedView The view whose visibility changed. Could be 'this' or
10915     * an ancestor view.
10916     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10917     * {@link #INVISIBLE} or {@link #GONE}.
10918     */
10919    protected void dispatchVisibilityChanged(@NonNull View changedView,
10920            @Visibility int visibility) {
10921        onVisibilityChanged(changedView, visibility);
10922    }
10923
10924    /**
10925     * Called when the visibility of the view or an ancestor of the view has
10926     * changed.
10927     *
10928     * @param changedView The view whose visibility changed. May be
10929     *                    {@code this} or an ancestor view.
10930     * @param visibility The new visibility, one of {@link #VISIBLE},
10931     *                   {@link #INVISIBLE} or {@link #GONE}.
10932     */
10933    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10934    }
10935
10936    /**
10937     * Dispatch a hint about whether this view is displayed. For instance, when
10938     * a View moves out of the screen, it might receives a display hint indicating
10939     * the view is not displayed. Applications should not <em>rely</em> on this hint
10940     * as there is no guarantee that they will receive one.
10941     *
10942     * @param hint A hint about whether or not this view is displayed:
10943     * {@link #VISIBLE} or {@link #INVISIBLE}.
10944     */
10945    public void dispatchDisplayHint(@Visibility int hint) {
10946        onDisplayHint(hint);
10947    }
10948
10949    /**
10950     * Gives this view a hint about whether is displayed or not. For instance, when
10951     * a View moves out of the screen, it might receives a display hint indicating
10952     * the view is not displayed. Applications should not <em>rely</em> on this hint
10953     * as there is no guarantee that they will receive one.
10954     *
10955     * @param hint A hint about whether or not this view is displayed:
10956     * {@link #VISIBLE} or {@link #INVISIBLE}.
10957     */
10958    protected void onDisplayHint(@Visibility int hint) {
10959    }
10960
10961    /**
10962     * Dispatch a window visibility change down the view hierarchy.
10963     * ViewGroups should override to route to their children.
10964     *
10965     * @param visibility The new visibility of the window.
10966     *
10967     * @see #onWindowVisibilityChanged(int)
10968     */
10969    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10970        onWindowVisibilityChanged(visibility);
10971    }
10972
10973    /**
10974     * Called when the window containing has change its visibility
10975     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10976     * that this tells you whether or not your window is being made visible
10977     * to the window manager; this does <em>not</em> tell you whether or not
10978     * your window is obscured by other windows on the screen, even if it
10979     * is itself visible.
10980     *
10981     * @param visibility The new visibility of the window.
10982     */
10983    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10984        if (visibility == VISIBLE) {
10985            initialAwakenScrollBars();
10986        }
10987    }
10988
10989    /**
10990     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10991     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10992     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10993     *
10994     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10995     *                  ancestors or by window visibility
10996     * @return true if this view is visible to the user, not counting clipping or overlapping
10997     */
10998    boolean dispatchVisibilityAggregated(boolean isVisible) {
10999        final boolean thisVisible = getVisibility() == VISIBLE;
11000        // If we're not visible but something is telling us we are, ignore it.
11001        if (thisVisible || !isVisible) {
11002            onVisibilityAggregated(isVisible);
11003        }
11004        return thisVisible && isVisible;
11005    }
11006
11007    /**
11008     * Called when the user-visibility of this View is potentially affected by a change
11009     * to this view itself, an ancestor view or the window this view is attached to.
11010     *
11011     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
11012     *                  and this view's window is also visible
11013     */
11014    @CallSuper
11015    public void onVisibilityAggregated(boolean isVisible) {
11016        if (isVisible && mAttachInfo != null) {
11017            initialAwakenScrollBars();
11018        }
11019
11020        final Drawable dr = mBackground;
11021        if (dr != null && isVisible != dr.isVisible()) {
11022            dr.setVisible(isVisible, false);
11023        }
11024        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
11025        if (fg != null && isVisible != fg.isVisible()) {
11026            fg.setVisible(isVisible, false);
11027        }
11028    }
11029
11030    /**
11031     * Returns the current visibility of the window this view is attached to
11032     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
11033     *
11034     * @return Returns the current visibility of the view's window.
11035     */
11036    @Visibility
11037    public int getWindowVisibility() {
11038        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
11039    }
11040
11041    /**
11042     * Retrieve the overall visible display size in which the window this view is
11043     * attached to has been positioned in.  This takes into account screen
11044     * decorations above the window, for both cases where the window itself
11045     * is being position inside of them or the window is being placed under
11046     * then and covered insets are used for the window to position its content
11047     * inside.  In effect, this tells you the available area where content can
11048     * be placed and remain visible to users.
11049     *
11050     * <p>This function requires an IPC back to the window manager to retrieve
11051     * the requested information, so should not be used in performance critical
11052     * code like drawing.
11053     *
11054     * @param outRect Filled in with the visible display frame.  If the view
11055     * is not attached to a window, this is simply the raw display size.
11056     */
11057    public void getWindowVisibleDisplayFrame(Rect outRect) {
11058        if (mAttachInfo != null) {
11059            try {
11060                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11061            } catch (RemoteException e) {
11062                return;
11063            }
11064            // XXX This is really broken, and probably all needs to be done
11065            // in the window manager, and we need to know more about whether
11066            // we want the area behind or in front of the IME.
11067            final Rect insets = mAttachInfo.mVisibleInsets;
11068            outRect.left += insets.left;
11069            outRect.top += insets.top;
11070            outRect.right -= insets.right;
11071            outRect.bottom -= insets.bottom;
11072            return;
11073        }
11074        // The view is not attached to a display so we don't have a context.
11075        // Make a best guess about the display size.
11076        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11077        d.getRectSize(outRect);
11078    }
11079
11080    /**
11081     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
11082     * is currently in without any insets.
11083     *
11084     * @hide
11085     */
11086    public void getWindowDisplayFrame(Rect outRect) {
11087        if (mAttachInfo != null) {
11088            try {
11089                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11090            } catch (RemoteException e) {
11091                return;
11092            }
11093            return;
11094        }
11095        // The view is not attached to a display so we don't have a context.
11096        // Make a best guess about the display size.
11097        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11098        d.getRectSize(outRect);
11099    }
11100
11101    /**
11102     * Dispatch a notification about a resource configuration change down
11103     * the view hierarchy.
11104     * ViewGroups should override to route to their children.
11105     *
11106     * @param newConfig The new resource configuration.
11107     *
11108     * @see #onConfigurationChanged(android.content.res.Configuration)
11109     */
11110    public void dispatchConfigurationChanged(Configuration newConfig) {
11111        onConfigurationChanged(newConfig);
11112    }
11113
11114    /**
11115     * Called when the current configuration of the resources being used
11116     * by the application have changed.  You can use this to decide when
11117     * to reload resources that can changed based on orientation and other
11118     * configuration characteristics.  You only need to use this if you are
11119     * not relying on the normal {@link android.app.Activity} mechanism of
11120     * recreating the activity instance upon a configuration change.
11121     *
11122     * @param newConfig The new resource configuration.
11123     */
11124    protected void onConfigurationChanged(Configuration newConfig) {
11125    }
11126
11127    /**
11128     * Private function to aggregate all per-view attributes in to the view
11129     * root.
11130     */
11131    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11132        performCollectViewAttributes(attachInfo, visibility);
11133    }
11134
11135    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11136        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
11137            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
11138                attachInfo.mKeepScreenOn = true;
11139            }
11140            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
11141            ListenerInfo li = mListenerInfo;
11142            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
11143                attachInfo.mHasSystemUiListeners = true;
11144            }
11145        }
11146    }
11147
11148    void needGlobalAttributesUpdate(boolean force) {
11149        final AttachInfo ai = mAttachInfo;
11150        if (ai != null && !ai.mRecomputeGlobalAttributes) {
11151            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
11152                    || ai.mHasSystemUiListeners) {
11153                ai.mRecomputeGlobalAttributes = true;
11154            }
11155        }
11156    }
11157
11158    /**
11159     * Returns whether the device is currently in touch mode.  Touch mode is entered
11160     * once the user begins interacting with the device by touch, and affects various
11161     * things like whether focus is always visible to the user.
11162     *
11163     * @return Whether the device is in touch mode.
11164     */
11165    @ViewDebug.ExportedProperty
11166    public boolean isInTouchMode() {
11167        if (mAttachInfo != null) {
11168            return mAttachInfo.mInTouchMode;
11169        } else {
11170            return ViewRootImpl.isInTouchMode();
11171        }
11172    }
11173
11174    /**
11175     * Returns the context the view is running in, through which it can
11176     * access the current theme, resources, etc.
11177     *
11178     * @return The view's Context.
11179     */
11180    @ViewDebug.CapturedViewProperty
11181    public final Context getContext() {
11182        return mContext;
11183    }
11184
11185    /**
11186     * Handle a key event before it is processed by any input method
11187     * associated with the view hierarchy.  This can be used to intercept
11188     * key events in special situations before the IME consumes them; a
11189     * typical example would be handling the BACK key to update the application's
11190     * UI instead of allowing the IME to see it and close itself.
11191     *
11192     * @param keyCode The value in event.getKeyCode().
11193     * @param event Description of the key event.
11194     * @return If you handled the event, return true. If you want to allow the
11195     *         event to be handled by the next receiver, return false.
11196     */
11197    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
11198        return false;
11199    }
11200
11201    /**
11202     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
11203     * KeyEvent.Callback.onKeyDown()}: perform press of the view
11204     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
11205     * is released, if the view is enabled and clickable.
11206     * <p>
11207     * Key presses in software keyboards will generally NOT trigger this
11208     * listener, although some may elect to do so in some situations. Do not
11209     * rely on this to catch software key presses.
11210     *
11211     * @param keyCode a key code that represents the button pressed, from
11212     *                {@link android.view.KeyEvent}
11213     * @param event the KeyEvent object that defines the button action
11214     */
11215    public boolean onKeyDown(int keyCode, KeyEvent event) {
11216        if (KeyEvent.isConfirmKey(keyCode)) {
11217            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11218                return true;
11219            }
11220
11221            if (event.getRepeatCount() == 0) {
11222                // Long clickable items don't necessarily have to be clickable.
11223                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
11224                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
11225                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
11226                    // For the purposes of menu anchoring and drawable hotspots,
11227                    // key events are considered to be at the center of the view.
11228                    final float x = getWidth() / 2f;
11229                    final float y = getHeight() / 2f;
11230                    if (clickable) {
11231                        setPressed(true, x, y);
11232                    }
11233                    checkForLongClick(0, x, y);
11234                    return true;
11235                }
11236            }
11237        }
11238
11239        return false;
11240    }
11241
11242    /**
11243     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
11244     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
11245     * the event).
11246     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11247     * although some may elect to do so in some situations. Do not rely on this to
11248     * catch software key presses.
11249     */
11250    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
11251        return false;
11252    }
11253
11254    /**
11255     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
11256     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
11257     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
11258     * or {@link KeyEvent#KEYCODE_SPACE} is released.
11259     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11260     * although some may elect to do so in some situations. Do not rely on this to
11261     * catch software key presses.
11262     *
11263     * @param keyCode A key code that represents the button pressed, from
11264     *                {@link android.view.KeyEvent}.
11265     * @param event   The KeyEvent object that defines the button action.
11266     */
11267    public boolean onKeyUp(int keyCode, KeyEvent event) {
11268        if (KeyEvent.isConfirmKey(keyCode)) {
11269            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11270                return true;
11271            }
11272            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
11273                setPressed(false);
11274
11275                if (!mHasPerformedLongPress) {
11276                    // This is a tap, so remove the longpress check
11277                    removeLongPressCallback();
11278                    return performClick();
11279                }
11280            }
11281        }
11282        return false;
11283    }
11284
11285    /**
11286     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
11287     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
11288     * the event).
11289     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11290     * although some may elect to do so in some situations. Do not rely on this to
11291     * catch software key presses.
11292     *
11293     * @param keyCode     A key code that represents the button pressed, from
11294     *                    {@link android.view.KeyEvent}.
11295     * @param repeatCount The number of times the action was made.
11296     * @param event       The KeyEvent object that defines the button action.
11297     */
11298    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
11299        return false;
11300    }
11301
11302    /**
11303     * Called on the focused view when a key shortcut event is not handled.
11304     * Override this method to implement local key shortcuts for the View.
11305     * Key shortcuts can also be implemented by setting the
11306     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
11307     *
11308     * @param keyCode The value in event.getKeyCode().
11309     * @param event Description of the key event.
11310     * @return If you handled the event, return true. If you want to allow the
11311     *         event to be handled by the next receiver, return false.
11312     */
11313    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
11314        return false;
11315    }
11316
11317    /**
11318     * Check whether the called view is a text editor, in which case it
11319     * would make sense to automatically display a soft input window for
11320     * it.  Subclasses should override this if they implement
11321     * {@link #onCreateInputConnection(EditorInfo)} to return true if
11322     * a call on that method would return a non-null InputConnection, and
11323     * they are really a first-class editor that the user would normally
11324     * start typing on when the go into a window containing your view.
11325     *
11326     * <p>The default implementation always returns false.  This does
11327     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
11328     * will not be called or the user can not otherwise perform edits on your
11329     * view; it is just a hint to the system that this is not the primary
11330     * purpose of this view.
11331     *
11332     * @return Returns true if this view is a text editor, else false.
11333     */
11334    public boolean onCheckIsTextEditor() {
11335        return false;
11336    }
11337
11338    /**
11339     * Create a new InputConnection for an InputMethod to interact
11340     * with the view.  The default implementation returns null, since it doesn't
11341     * support input methods.  You can override this to implement such support.
11342     * This is only needed for views that take focus and text input.
11343     *
11344     * <p>When implementing this, you probably also want to implement
11345     * {@link #onCheckIsTextEditor()} to indicate you will return a
11346     * non-null InputConnection.</p>
11347     *
11348     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
11349     * object correctly and in its entirety, so that the connected IME can rely
11350     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
11351     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
11352     * must be filled in with the correct cursor position for IMEs to work correctly
11353     * with your application.</p>
11354     *
11355     * @param outAttrs Fill in with attribute information about the connection.
11356     */
11357    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
11358        return null;
11359    }
11360
11361    /**
11362     * Called by the {@link android.view.inputmethod.InputMethodManager}
11363     * when a view who is not the current
11364     * input connection target is trying to make a call on the manager.  The
11365     * default implementation returns false; you can override this to return
11366     * true for certain views if you are performing InputConnection proxying
11367     * to them.
11368     * @param view The View that is making the InputMethodManager call.
11369     * @return Return true to allow the call, false to reject.
11370     */
11371    public boolean checkInputConnectionProxy(View view) {
11372        return false;
11373    }
11374
11375    /**
11376     * Show the context menu for this view. It is not safe to hold on to the
11377     * menu after returning from this method.
11378     *
11379     * You should normally not overload this method. Overload
11380     * {@link #onCreateContextMenu(ContextMenu)} or define an
11381     * {@link OnCreateContextMenuListener} to add items to the context menu.
11382     *
11383     * @param menu The context menu to populate
11384     */
11385    public void createContextMenu(ContextMenu menu) {
11386        ContextMenuInfo menuInfo = getContextMenuInfo();
11387
11388        // Sets the current menu info so all items added to menu will have
11389        // my extra info set.
11390        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
11391
11392        onCreateContextMenu(menu);
11393        ListenerInfo li = mListenerInfo;
11394        if (li != null && li.mOnCreateContextMenuListener != null) {
11395            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
11396        }
11397
11398        // Clear the extra information so subsequent items that aren't mine don't
11399        // have my extra info.
11400        ((MenuBuilder)menu).setCurrentMenuInfo(null);
11401
11402        if (mParent != null) {
11403            mParent.createContextMenu(menu);
11404        }
11405    }
11406
11407    /**
11408     * Views should implement this if they have extra information to associate
11409     * with the context menu. The return result is supplied as a parameter to
11410     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
11411     * callback.
11412     *
11413     * @return Extra information about the item for which the context menu
11414     *         should be shown. This information will vary across different
11415     *         subclasses of View.
11416     */
11417    protected ContextMenuInfo getContextMenuInfo() {
11418        return null;
11419    }
11420
11421    /**
11422     * Views should implement this if the view itself is going to add items to
11423     * the context menu.
11424     *
11425     * @param menu the context menu to populate
11426     */
11427    protected void onCreateContextMenu(ContextMenu menu) {
11428    }
11429
11430    /**
11431     * Implement this method to handle trackball motion events.  The
11432     * <em>relative</em> movement of the trackball since the last event
11433     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
11434     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
11435     * that a movement of 1 corresponds to the user pressing one DPAD key (so
11436     * they will often be fractional values, representing the more fine-grained
11437     * movement information available from a trackball).
11438     *
11439     * @param event The motion event.
11440     * @return True if the event was handled, false otherwise.
11441     */
11442    public boolean onTrackballEvent(MotionEvent event) {
11443        return false;
11444    }
11445
11446    /**
11447     * Implement this method to handle generic motion events.
11448     * <p>
11449     * Generic motion events describe joystick movements, mouse hovers, track pad
11450     * touches, scroll wheel movements and other input events.  The
11451     * {@link MotionEvent#getSource() source} of the motion event specifies
11452     * the class of input that was received.  Implementations of this method
11453     * must examine the bits in the source before processing the event.
11454     * The following code example shows how this is done.
11455     * </p><p>
11456     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
11457     * are delivered to the view under the pointer.  All other generic motion events are
11458     * delivered to the focused view.
11459     * </p>
11460     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
11461     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
11462     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
11463     *             // process the joystick movement...
11464     *             return true;
11465     *         }
11466     *     }
11467     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
11468     *         switch (event.getAction()) {
11469     *             case MotionEvent.ACTION_HOVER_MOVE:
11470     *                 // process the mouse hover movement...
11471     *                 return true;
11472     *             case MotionEvent.ACTION_SCROLL:
11473     *                 // process the scroll wheel movement...
11474     *                 return true;
11475     *         }
11476     *     }
11477     *     return super.onGenericMotionEvent(event);
11478     * }</pre>
11479     *
11480     * @param event The generic motion event being processed.
11481     * @return True if the event was handled, false otherwise.
11482     */
11483    public boolean onGenericMotionEvent(MotionEvent event) {
11484        return false;
11485    }
11486
11487    /**
11488     * Implement this method to handle hover events.
11489     * <p>
11490     * This method is called whenever a pointer is hovering into, over, or out of the
11491     * bounds of a view and the view is not currently being touched.
11492     * Hover events are represented as pointer events with action
11493     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
11494     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
11495     * </p>
11496     * <ul>
11497     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
11498     * when the pointer enters the bounds of the view.</li>
11499     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
11500     * when the pointer has already entered the bounds of the view and has moved.</li>
11501     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
11502     * when the pointer has exited the bounds of the view or when the pointer is
11503     * about to go down due to a button click, tap, or similar user action that
11504     * causes the view to be touched.</li>
11505     * </ul>
11506     * <p>
11507     * The view should implement this method to return true to indicate that it is
11508     * handling the hover event, such as by changing its drawable state.
11509     * </p><p>
11510     * The default implementation calls {@link #setHovered} to update the hovered state
11511     * of the view when a hover enter or hover exit event is received, if the view
11512     * is enabled and is clickable.  The default implementation also sends hover
11513     * accessibility events.
11514     * </p>
11515     *
11516     * @param event The motion event that describes the hover.
11517     * @return True if the view handled the hover event.
11518     *
11519     * @see #isHovered
11520     * @see #setHovered
11521     * @see #onHoverChanged
11522     */
11523    public boolean onHoverEvent(MotionEvent event) {
11524        // The root view may receive hover (or touch) events that are outside the bounds of
11525        // the window.  This code ensures that we only send accessibility events for
11526        // hovers that are actually within the bounds of the root view.
11527        final int action = event.getActionMasked();
11528        if (!mSendingHoverAccessibilityEvents) {
11529            if ((action == MotionEvent.ACTION_HOVER_ENTER
11530                    || action == MotionEvent.ACTION_HOVER_MOVE)
11531                    && !hasHoveredChild()
11532                    && pointInView(event.getX(), event.getY())) {
11533                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
11534                mSendingHoverAccessibilityEvents = true;
11535            }
11536        } else {
11537            if (action == MotionEvent.ACTION_HOVER_EXIT
11538                    || (action == MotionEvent.ACTION_MOVE
11539                            && !pointInView(event.getX(), event.getY()))) {
11540                mSendingHoverAccessibilityEvents = false;
11541                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
11542            }
11543        }
11544
11545        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
11546                && event.isFromSource(InputDevice.SOURCE_MOUSE)
11547                && isOnScrollbar(event.getX(), event.getY())) {
11548            awakenScrollBars();
11549        }
11550        if (isHoverable()) {
11551            switch (action) {
11552                case MotionEvent.ACTION_HOVER_ENTER:
11553                    setHovered(true);
11554                    break;
11555                case MotionEvent.ACTION_HOVER_EXIT:
11556                    setHovered(false);
11557                    break;
11558            }
11559
11560            // Dispatch the event to onGenericMotionEvent before returning true.
11561            // This is to provide compatibility with existing applications that
11562            // handled HOVER_MOVE events in onGenericMotionEvent and that would
11563            // break because of the new default handling for hoverable views
11564            // in onHoverEvent.
11565            // Note that onGenericMotionEvent will be called by default when
11566            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
11567            dispatchGenericMotionEventInternal(event);
11568            // The event was already handled by calling setHovered(), so always
11569            // return true.
11570            return true;
11571        }
11572
11573        return false;
11574    }
11575
11576    /**
11577     * Returns true if the view should handle {@link #onHoverEvent}
11578     * by calling {@link #setHovered} to change its hovered state.
11579     *
11580     * @return True if the view is hoverable.
11581     */
11582    private boolean isHoverable() {
11583        final int viewFlags = mViewFlags;
11584        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11585            return false;
11586        }
11587
11588        return (viewFlags & CLICKABLE) == CLICKABLE
11589                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
11590                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11591    }
11592
11593    /**
11594     * Returns true if the view is currently hovered.
11595     *
11596     * @return True if the view is currently hovered.
11597     *
11598     * @see #setHovered
11599     * @see #onHoverChanged
11600     */
11601    @ViewDebug.ExportedProperty
11602    public boolean isHovered() {
11603        return (mPrivateFlags & PFLAG_HOVERED) != 0;
11604    }
11605
11606    /**
11607     * Sets whether the view is currently hovered.
11608     * <p>
11609     * Calling this method also changes the drawable state of the view.  This
11610     * enables the view to react to hover by using different drawable resources
11611     * to change its appearance.
11612     * </p><p>
11613     * The {@link #onHoverChanged} method is called when the hovered state changes.
11614     * </p>
11615     *
11616     * @param hovered True if the view is hovered.
11617     *
11618     * @see #isHovered
11619     * @see #onHoverChanged
11620     */
11621    public void setHovered(boolean hovered) {
11622        if (hovered) {
11623            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
11624                mPrivateFlags |= PFLAG_HOVERED;
11625                refreshDrawableState();
11626                onHoverChanged(true);
11627            }
11628        } else {
11629            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
11630                mPrivateFlags &= ~PFLAG_HOVERED;
11631                refreshDrawableState();
11632                onHoverChanged(false);
11633            }
11634        }
11635    }
11636
11637    /**
11638     * Implement this method to handle hover state changes.
11639     * <p>
11640     * This method is called whenever the hover state changes as a result of a
11641     * call to {@link #setHovered}.
11642     * </p>
11643     *
11644     * @param hovered The current hover state, as returned by {@link #isHovered}.
11645     *
11646     * @see #isHovered
11647     * @see #setHovered
11648     */
11649    public void onHoverChanged(boolean hovered) {
11650    }
11651
11652    /**
11653     * Handles scroll bar dragging by mouse input.
11654     *
11655     * @hide
11656     * @param event The motion event.
11657     *
11658     * @return true if the event was handled as a scroll bar dragging, false otherwise.
11659     */
11660    protected boolean handleScrollBarDragging(MotionEvent event) {
11661        if (mScrollCache == null) {
11662            return false;
11663        }
11664        final float x = event.getX();
11665        final float y = event.getY();
11666        final int action = event.getAction();
11667        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
11668                && action != MotionEvent.ACTION_DOWN)
11669                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
11670                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
11671            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11672            return false;
11673        }
11674
11675        switch (action) {
11676            case MotionEvent.ACTION_MOVE:
11677                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
11678                    return false;
11679                }
11680                if (mScrollCache.mScrollBarDraggingState
11681                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
11682                    final Rect bounds = mScrollCache.mScrollBarBounds;
11683                    getVerticalScrollBarBounds(bounds);
11684                    final int range = computeVerticalScrollRange();
11685                    final int offset = computeVerticalScrollOffset();
11686                    final int extent = computeVerticalScrollExtent();
11687
11688                    final int thumbLength = ScrollBarUtils.getThumbLength(
11689                            bounds.height(), bounds.width(), extent, range);
11690                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11691                            bounds.height(), thumbLength, extent, range, offset);
11692
11693                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
11694                    final float maxThumbOffset = bounds.height() - thumbLength;
11695                    final float newThumbOffset =
11696                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11697                    final int height = getHeight();
11698                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11699                            && height > 0 && extent > 0) {
11700                        final int newY = Math.round((range - extent)
11701                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11702                        if (newY != getScrollY()) {
11703                            mScrollCache.mScrollBarDraggingPos = y;
11704                            setScrollY(newY);
11705                        }
11706                    }
11707                    return true;
11708                }
11709                if (mScrollCache.mScrollBarDraggingState
11710                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11711                    final Rect bounds = mScrollCache.mScrollBarBounds;
11712                    getHorizontalScrollBarBounds(bounds);
11713                    final int range = computeHorizontalScrollRange();
11714                    final int offset = computeHorizontalScrollOffset();
11715                    final int extent = computeHorizontalScrollExtent();
11716
11717                    final int thumbLength = ScrollBarUtils.getThumbLength(
11718                            bounds.width(), bounds.height(), extent, range);
11719                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11720                            bounds.width(), thumbLength, extent, range, offset);
11721
11722                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11723                    final float maxThumbOffset = bounds.width() - thumbLength;
11724                    final float newThumbOffset =
11725                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11726                    final int width = getWidth();
11727                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11728                            && width > 0 && extent > 0) {
11729                        final int newX = Math.round((range - extent)
11730                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11731                        if (newX != getScrollX()) {
11732                            mScrollCache.mScrollBarDraggingPos = x;
11733                            setScrollX(newX);
11734                        }
11735                    }
11736                    return true;
11737                }
11738            case MotionEvent.ACTION_DOWN:
11739                if (mScrollCache.state == ScrollabilityCache.OFF) {
11740                    return false;
11741                }
11742                if (isOnVerticalScrollbarThumb(x, y)) {
11743                    mScrollCache.mScrollBarDraggingState =
11744                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11745                    mScrollCache.mScrollBarDraggingPos = y;
11746                    return true;
11747                }
11748                if (isOnHorizontalScrollbarThumb(x, y)) {
11749                    mScrollCache.mScrollBarDraggingState =
11750                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11751                    mScrollCache.mScrollBarDraggingPos = x;
11752                    return true;
11753                }
11754        }
11755        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11756        return false;
11757    }
11758
11759    /**
11760     * Implement this method to handle touch screen motion events.
11761     * <p>
11762     * If this method is used to detect click actions, it is recommended that
11763     * the actions be performed by implementing and calling
11764     * {@link #performClick()}. This will ensure consistent system behavior,
11765     * including:
11766     * <ul>
11767     * <li>obeying click sound preferences
11768     * <li>dispatching OnClickListener calls
11769     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11770     * accessibility features are enabled
11771     * </ul>
11772     *
11773     * @param event The motion event.
11774     * @return True if the event was handled, false otherwise.
11775     */
11776    public boolean onTouchEvent(MotionEvent event) {
11777        final float x = event.getX();
11778        final float y = event.getY();
11779        final int viewFlags = mViewFlags;
11780        final int action = event.getAction();
11781
11782        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
11783                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11784                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11785
11786        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11787            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11788                setPressed(false);
11789            }
11790            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11791            // A disabled view that is clickable still consumes the touch
11792            // events, it just doesn't respond to them.
11793            return clickable;
11794        }
11795        if (mTouchDelegate != null) {
11796            if (mTouchDelegate.onTouchEvent(event)) {
11797                return true;
11798            }
11799        }
11800
11801        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
11802            switch (action) {
11803                case MotionEvent.ACTION_UP:
11804                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11805                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
11806                        handleTooltipUp();
11807                    }
11808                    if (!clickable) {
11809                        removeTapCallback();
11810                        removeLongPressCallback();
11811                        mInContextButtonPress = false;
11812                        mHasPerformedLongPress = false;
11813                        mIgnoreNextUpEvent = false;
11814                        break;
11815                    }
11816                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11817                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11818                        // take focus if we don't have it already and we should in
11819                        // touch mode.
11820                        boolean focusTaken = false;
11821                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11822                            focusTaken = requestFocus();
11823                        }
11824
11825                        if (prepressed) {
11826                            // The button is being released before we actually
11827                            // showed it as pressed.  Make it show the pressed
11828                            // state now (before scheduling the click) to ensure
11829                            // the user sees it.
11830                            setPressed(true, x, y);
11831                        }
11832
11833                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11834                            // This is a tap, so remove the longpress check
11835                            removeLongPressCallback();
11836
11837                            // Only perform take click actions if we were in the pressed state
11838                            if (!focusTaken) {
11839                                // Use a Runnable and post this rather than calling
11840                                // performClick directly. This lets other visual state
11841                                // of the view update before click actions start.
11842                                if (mPerformClick == null) {
11843                                    mPerformClick = new PerformClick();
11844                                }
11845                                if (!post(mPerformClick)) {
11846                                    performClick();
11847                                }
11848                            }
11849                        }
11850
11851                        if (mUnsetPressedState == null) {
11852                            mUnsetPressedState = new UnsetPressedState();
11853                        }
11854
11855                        if (prepressed) {
11856                            postDelayed(mUnsetPressedState,
11857                                    ViewConfiguration.getPressedStateDuration());
11858                        } else if (!post(mUnsetPressedState)) {
11859                            // If the post failed, unpress right now
11860                            mUnsetPressedState.run();
11861                        }
11862
11863                        removeTapCallback();
11864                    }
11865                    mIgnoreNextUpEvent = false;
11866                    break;
11867
11868                case MotionEvent.ACTION_DOWN:
11869                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
11870                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
11871                    }
11872                    mHasPerformedLongPress = false;
11873
11874                    if (!clickable) {
11875                        checkForLongClick(0, x, y);
11876                        break;
11877                    }
11878
11879                    if (performButtonActionOnTouchDown(event)) {
11880                        break;
11881                    }
11882
11883                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11884                    boolean isInScrollingContainer = isInScrollingContainer();
11885
11886                    // For views inside a scrolling container, delay the pressed feedback for
11887                    // a short period in case this is a scroll.
11888                    if (isInScrollingContainer) {
11889                        mPrivateFlags |= PFLAG_PREPRESSED;
11890                        if (mPendingCheckForTap == null) {
11891                            mPendingCheckForTap = new CheckForTap();
11892                        }
11893                        mPendingCheckForTap.x = event.getX();
11894                        mPendingCheckForTap.y = event.getY();
11895                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11896                    } else {
11897                        // Not inside a scrolling container, so show the feedback right away
11898                        setPressed(true, x, y);
11899                        checkForLongClick(0, x, y);
11900                    }
11901                    break;
11902
11903                case MotionEvent.ACTION_CANCEL:
11904                    if (clickable) {
11905                        setPressed(false);
11906                    }
11907                    removeTapCallback();
11908                    removeLongPressCallback();
11909                    mInContextButtonPress = false;
11910                    mHasPerformedLongPress = false;
11911                    mIgnoreNextUpEvent = false;
11912                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11913                    break;
11914
11915                case MotionEvent.ACTION_MOVE:
11916                    if (clickable) {
11917                        drawableHotspotChanged(x, y);
11918                    }
11919
11920                    // Be lenient about moving outside of buttons
11921                    if (!pointInView(x, y, mTouchSlop)) {
11922                        // Outside button
11923                        // Remove any future long press/tap checks
11924                        removeTapCallback();
11925                        removeLongPressCallback();
11926                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11927                            setPressed(false);
11928                        }
11929                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11930                    }
11931                    break;
11932            }
11933
11934            return true;
11935        }
11936
11937        return false;
11938    }
11939
11940    /**
11941     * @hide
11942     */
11943    public boolean isInScrollingContainer() {
11944        ViewParent p = getParent();
11945        while (p != null && p instanceof ViewGroup) {
11946            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11947                return true;
11948            }
11949            p = p.getParent();
11950        }
11951        return false;
11952    }
11953
11954    /**
11955     * Remove the longpress detection timer.
11956     */
11957    private void removeLongPressCallback() {
11958        if (mPendingCheckForLongPress != null) {
11959            removeCallbacks(mPendingCheckForLongPress);
11960        }
11961    }
11962
11963    /**
11964     * Remove the pending click action
11965     */
11966    private void removePerformClickCallback() {
11967        if (mPerformClick != null) {
11968            removeCallbacks(mPerformClick);
11969        }
11970    }
11971
11972    /**
11973     * Remove the prepress detection timer.
11974     */
11975    private void removeUnsetPressCallback() {
11976        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11977            setPressed(false);
11978            removeCallbacks(mUnsetPressedState);
11979        }
11980    }
11981
11982    /**
11983     * Remove the tap detection timer.
11984     */
11985    private void removeTapCallback() {
11986        if (mPendingCheckForTap != null) {
11987            mPrivateFlags &= ~PFLAG_PREPRESSED;
11988            removeCallbacks(mPendingCheckForTap);
11989        }
11990    }
11991
11992    /**
11993     * Cancels a pending long press.  Your subclass can use this if you
11994     * want the context menu to come up if the user presses and holds
11995     * at the same place, but you don't want it to come up if they press
11996     * and then move around enough to cause scrolling.
11997     */
11998    public void cancelLongPress() {
11999        removeLongPressCallback();
12000
12001        /*
12002         * The prepressed state handled by the tap callback is a display
12003         * construct, but the tap callback will post a long press callback
12004         * less its own timeout. Remove it here.
12005         */
12006        removeTapCallback();
12007    }
12008
12009    /**
12010     * Remove the pending callback for sending a
12011     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
12012     */
12013    private void removeSendViewScrolledAccessibilityEventCallback() {
12014        if (mSendViewScrolledAccessibilityEvent != null) {
12015            removeCallbacks(mSendViewScrolledAccessibilityEvent);
12016            mSendViewScrolledAccessibilityEvent.mIsPending = false;
12017        }
12018    }
12019
12020    /**
12021     * Sets the TouchDelegate for this View.
12022     */
12023    public void setTouchDelegate(TouchDelegate delegate) {
12024        mTouchDelegate = delegate;
12025    }
12026
12027    /**
12028     * Gets the TouchDelegate for this View.
12029     */
12030    public TouchDelegate getTouchDelegate() {
12031        return mTouchDelegate;
12032    }
12033
12034    /**
12035     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
12036     *
12037     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
12038     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
12039     * available. This method should only be called for touch events.
12040     *
12041     * <p class="note">This api is not intended for most applications. Buffered dispatch
12042     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
12043     * streams will not improve your input latency. Side effects include: increased latency,
12044     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
12045     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
12046     * you.</p>
12047     */
12048    public final void requestUnbufferedDispatch(MotionEvent event) {
12049        final int action = event.getAction();
12050        if (mAttachInfo == null
12051                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
12052                || !event.isTouchEvent()) {
12053            return;
12054        }
12055        mAttachInfo.mUnbufferedDispatchRequested = true;
12056    }
12057
12058    /**
12059     * Set flags controlling behavior of this view.
12060     *
12061     * @param flags Constant indicating the value which should be set
12062     * @param mask Constant indicating the bit range that should be changed
12063     */
12064    void setFlags(int flags, int mask) {
12065        final boolean accessibilityEnabled =
12066                AccessibilityManager.getInstance(mContext).isEnabled();
12067        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
12068
12069        int old = mViewFlags;
12070        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
12071
12072        int changed = mViewFlags ^ old;
12073        if (changed == 0) {
12074            return;
12075        }
12076        int privateFlags = mPrivateFlags;
12077
12078        // If focusable is auto, update the FOCUSABLE bit.
12079        if (((mViewFlags & FOCUSABLE_AUTO) != 0)
12080                && (changed & (FOCUSABLE_MASK | CLICKABLE | FOCUSABLE_IN_TOUCH_MODE)) != 0) {
12081            int newFocus = NOT_FOCUSABLE;
12082            if ((mViewFlags & (CLICKABLE | FOCUSABLE_IN_TOUCH_MODE)) != 0) {
12083                newFocus = FOCUSABLE;
12084            } else {
12085                mViewFlags = (mViewFlags & ~FOCUSABLE_IN_TOUCH_MODE);
12086            }
12087            mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
12088            int focusChanged = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
12089            changed = (changed & ~FOCUSABLE) | focusChanged;
12090        }
12091
12092        /* Check if the FOCUSABLE bit has changed */
12093        if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
12094            if (((old & FOCUSABLE) == FOCUSABLE)
12095                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
12096                /* Give up focus if we are no longer focusable */
12097                clearFocus();
12098            } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
12099                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
12100                /*
12101                 * Tell the view system that we are now available to take focus
12102                 * if no one else already has it.
12103                 */
12104                if (mParent != null) mParent.focusableViewAvailable(this);
12105            }
12106        }
12107
12108        final int newVisibility = flags & VISIBILITY_MASK;
12109        if (newVisibility == VISIBLE) {
12110            if ((changed & VISIBILITY_MASK) != 0) {
12111                /*
12112                 * If this view is becoming visible, invalidate it in case it changed while
12113                 * it was not visible. Marking it drawn ensures that the invalidation will
12114                 * go through.
12115                 */
12116                mPrivateFlags |= PFLAG_DRAWN;
12117                invalidate(true);
12118
12119                needGlobalAttributesUpdate(true);
12120
12121                // a view becoming visible is worth notifying the parent
12122                // about in case nothing has focus.  even if this specific view
12123                // isn't focusable, it may contain something that is, so let
12124                // the root view try to give this focus if nothing else does.
12125                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
12126                    mParent.focusableViewAvailable(this);
12127                }
12128            }
12129        }
12130
12131        /* Check if the GONE bit has changed */
12132        if ((changed & GONE) != 0) {
12133            needGlobalAttributesUpdate(false);
12134            requestLayout();
12135
12136            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
12137                if (hasFocus()) clearFocus();
12138                clearAccessibilityFocus();
12139                destroyDrawingCache();
12140                if (mParent instanceof View) {
12141                    // GONE views noop invalidation, so invalidate the parent
12142                    ((View) mParent).invalidate(true);
12143                }
12144                // Mark the view drawn to ensure that it gets invalidated properly the next
12145                // time it is visible and gets invalidated
12146                mPrivateFlags |= PFLAG_DRAWN;
12147            }
12148            if (mAttachInfo != null) {
12149                mAttachInfo.mViewVisibilityChanged = true;
12150            }
12151        }
12152
12153        /* Check if the VISIBLE bit has changed */
12154        if ((changed & INVISIBLE) != 0) {
12155            needGlobalAttributesUpdate(false);
12156            /*
12157             * If this view is becoming invisible, set the DRAWN flag so that
12158             * the next invalidate() will not be skipped.
12159             */
12160            mPrivateFlags |= PFLAG_DRAWN;
12161
12162            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
12163                // root view becoming invisible shouldn't clear focus and accessibility focus
12164                if (getRootView() != this) {
12165                    if (hasFocus()) clearFocus();
12166                    clearAccessibilityFocus();
12167                }
12168            }
12169            if (mAttachInfo != null) {
12170                mAttachInfo.mViewVisibilityChanged = true;
12171            }
12172        }
12173
12174        if ((changed & VISIBILITY_MASK) != 0) {
12175            // If the view is invisible, cleanup its display list to free up resources
12176            if (newVisibility != VISIBLE && mAttachInfo != null) {
12177                cleanupDraw();
12178            }
12179
12180            if (mParent instanceof ViewGroup) {
12181                ((ViewGroup) mParent).onChildVisibilityChanged(this,
12182                        (changed & VISIBILITY_MASK), newVisibility);
12183                ((View) mParent).invalidate(true);
12184            } else if (mParent != null) {
12185                mParent.invalidateChild(this, null);
12186            }
12187
12188            if (mAttachInfo != null) {
12189                dispatchVisibilityChanged(this, newVisibility);
12190
12191                // Aggregated visibility changes are dispatched to attached views
12192                // in visible windows where the parent is currently shown/drawn
12193                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
12194                // discounting clipping or overlapping. This makes it a good place
12195                // to change animation states.
12196                if (mParent != null && getWindowVisibility() == VISIBLE &&
12197                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
12198                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
12199                }
12200                notifySubtreeAccessibilityStateChangedIfNeeded();
12201            }
12202        }
12203
12204        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
12205            destroyDrawingCache();
12206        }
12207
12208        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
12209            destroyDrawingCache();
12210            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12211            invalidateParentCaches();
12212        }
12213
12214        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
12215            destroyDrawingCache();
12216            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12217        }
12218
12219        if ((changed & DRAW_MASK) != 0) {
12220            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
12221                if (mBackground != null
12222                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
12223                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12224                } else {
12225                    mPrivateFlags |= PFLAG_SKIP_DRAW;
12226                }
12227            } else {
12228                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12229            }
12230            requestLayout();
12231            invalidate(true);
12232        }
12233
12234        if ((changed & KEEP_SCREEN_ON) != 0) {
12235            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12236                mParent.recomputeViewAttributes(this);
12237            }
12238        }
12239
12240        if (accessibilityEnabled) {
12241            if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
12242                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
12243                    || (changed & CONTEXT_CLICKABLE) != 0) {
12244                if (oldIncludeForAccessibility != includeForAccessibility()) {
12245                    notifySubtreeAccessibilityStateChangedIfNeeded();
12246                } else {
12247                    notifyViewAccessibilityStateChangedIfNeeded(
12248                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12249                }
12250            } else if ((changed & ENABLED_MASK) != 0) {
12251                notifyViewAccessibilityStateChangedIfNeeded(
12252                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12253            }
12254        }
12255    }
12256
12257    /**
12258     * Change the view's z order in the tree, so it's on top of other sibling
12259     * views. This ordering change may affect layout, if the parent container
12260     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
12261     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
12262     * method should be followed by calls to {@link #requestLayout()} and
12263     * {@link View#invalidate()} on the view's parent to force the parent to redraw
12264     * with the new child ordering.
12265     *
12266     * @see ViewGroup#bringChildToFront(View)
12267     */
12268    public void bringToFront() {
12269        if (mParent != null) {
12270            mParent.bringChildToFront(this);
12271        }
12272    }
12273
12274    /**
12275     * This is called in response to an internal scroll in this view (i.e., the
12276     * view scrolled its own contents). This is typically as a result of
12277     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
12278     * called.
12279     *
12280     * @param l Current horizontal scroll origin.
12281     * @param t Current vertical scroll origin.
12282     * @param oldl Previous horizontal scroll origin.
12283     * @param oldt Previous vertical scroll origin.
12284     */
12285    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
12286        notifySubtreeAccessibilityStateChangedIfNeeded();
12287
12288        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
12289            postSendViewScrolledAccessibilityEventCallback();
12290        }
12291
12292        mBackgroundSizeChanged = true;
12293        if (mForegroundInfo != null) {
12294            mForegroundInfo.mBoundsChanged = true;
12295        }
12296
12297        final AttachInfo ai = mAttachInfo;
12298        if (ai != null) {
12299            ai.mViewScrollChanged = true;
12300        }
12301
12302        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
12303            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
12304        }
12305    }
12306
12307    /**
12308     * Interface definition for a callback to be invoked when the scroll
12309     * X or Y positions of a view change.
12310     * <p>
12311     * <b>Note:</b> Some views handle scrolling independently from View and may
12312     * have their own separate listeners for scroll-type events. For example,
12313     * {@link android.widget.ListView ListView} allows clients to register an
12314     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
12315     * to listen for changes in list scroll position.
12316     *
12317     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
12318     */
12319    public interface OnScrollChangeListener {
12320        /**
12321         * Called when the scroll position of a view changes.
12322         *
12323         * @param v The view whose scroll position has changed.
12324         * @param scrollX Current horizontal scroll origin.
12325         * @param scrollY Current vertical scroll origin.
12326         * @param oldScrollX Previous horizontal scroll origin.
12327         * @param oldScrollY Previous vertical scroll origin.
12328         */
12329        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
12330    }
12331
12332    /**
12333     * Interface definition for a callback to be invoked when the layout bounds of a view
12334     * changes due to layout processing.
12335     */
12336    public interface OnLayoutChangeListener {
12337        /**
12338         * Called when the layout bounds of a view changes due to layout processing.
12339         *
12340         * @param v The view whose bounds have changed.
12341         * @param left The new value of the view's left property.
12342         * @param top The new value of the view's top property.
12343         * @param right The new value of the view's right property.
12344         * @param bottom The new value of the view's bottom property.
12345         * @param oldLeft The previous value of the view's left property.
12346         * @param oldTop The previous value of the view's top property.
12347         * @param oldRight The previous value of the view's right property.
12348         * @param oldBottom The previous value of the view's bottom property.
12349         */
12350        void onLayoutChange(View v, int left, int top, int right, int bottom,
12351            int oldLeft, int oldTop, int oldRight, int oldBottom);
12352    }
12353
12354    /**
12355     * This is called during layout when the size of this view has changed. If
12356     * you were just added to the view hierarchy, you're called with the old
12357     * values of 0.
12358     *
12359     * @param w Current width of this view.
12360     * @param h Current height of this view.
12361     * @param oldw Old width of this view.
12362     * @param oldh Old height of this view.
12363     */
12364    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
12365    }
12366
12367    /**
12368     * Called by draw to draw the child views. This may be overridden
12369     * by derived classes to gain control just before its children are drawn
12370     * (but after its own view has been drawn).
12371     * @param canvas the canvas on which to draw the view
12372     */
12373    protected void dispatchDraw(Canvas canvas) {
12374
12375    }
12376
12377    /**
12378     * Gets the parent of this view. Note that the parent is a
12379     * ViewParent and not necessarily a View.
12380     *
12381     * @return Parent of this view.
12382     */
12383    public final ViewParent getParent() {
12384        return mParent;
12385    }
12386
12387    /**
12388     * Set the horizontal scrolled position of your view. This will cause a call to
12389     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12390     * invalidated.
12391     * @param value the x position to scroll to
12392     */
12393    public void setScrollX(int value) {
12394        scrollTo(value, mScrollY);
12395    }
12396
12397    /**
12398     * Set the vertical scrolled position of your view. This will cause a call to
12399     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12400     * invalidated.
12401     * @param value the y position to scroll to
12402     */
12403    public void setScrollY(int value) {
12404        scrollTo(mScrollX, value);
12405    }
12406
12407    /**
12408     * Return the scrolled left position of this view. This is the left edge of
12409     * the displayed part of your view. You do not need to draw any pixels
12410     * farther left, since those are outside of the frame of your view on
12411     * screen.
12412     *
12413     * @return The left edge of the displayed part of your view, in pixels.
12414     */
12415    public final int getScrollX() {
12416        return mScrollX;
12417    }
12418
12419    /**
12420     * Return the scrolled top position of this view. This is the top edge of
12421     * the displayed part of your view. You do not need to draw any pixels above
12422     * it, since those are outside of the frame of your view on screen.
12423     *
12424     * @return The top edge of the displayed part of your view, in pixels.
12425     */
12426    public final int getScrollY() {
12427        return mScrollY;
12428    }
12429
12430    /**
12431     * Return the width of the your view.
12432     *
12433     * @return The width of your view, in pixels.
12434     */
12435    @ViewDebug.ExportedProperty(category = "layout")
12436    public final int getWidth() {
12437        return mRight - mLeft;
12438    }
12439
12440    /**
12441     * Return the height of your view.
12442     *
12443     * @return The height of your view, in pixels.
12444     */
12445    @ViewDebug.ExportedProperty(category = "layout")
12446    public final int getHeight() {
12447        return mBottom - mTop;
12448    }
12449
12450    /**
12451     * Return the visible drawing bounds of your view. Fills in the output
12452     * rectangle with the values from getScrollX(), getScrollY(),
12453     * getWidth(), and getHeight(). These bounds do not account for any
12454     * transformation properties currently set on the view, such as
12455     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
12456     *
12457     * @param outRect The (scrolled) drawing bounds of the view.
12458     */
12459    public void getDrawingRect(Rect outRect) {
12460        outRect.left = mScrollX;
12461        outRect.top = mScrollY;
12462        outRect.right = mScrollX + (mRight - mLeft);
12463        outRect.bottom = mScrollY + (mBottom - mTop);
12464    }
12465
12466    /**
12467     * Like {@link #getMeasuredWidthAndState()}, but only returns the
12468     * raw width component (that is the result is masked by
12469     * {@link #MEASURED_SIZE_MASK}).
12470     *
12471     * @return The raw measured width of this view.
12472     */
12473    public final int getMeasuredWidth() {
12474        return mMeasuredWidth & MEASURED_SIZE_MASK;
12475    }
12476
12477    /**
12478     * Return the full width measurement information for this view as computed
12479     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12480     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12481     * This should be used during measurement and layout calculations only. Use
12482     * {@link #getWidth()} to see how wide a view is after layout.
12483     *
12484     * @return The measured width of this view as a bit mask.
12485     */
12486    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12487            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12488                    name = "MEASURED_STATE_TOO_SMALL"),
12489    })
12490    public final int getMeasuredWidthAndState() {
12491        return mMeasuredWidth;
12492    }
12493
12494    /**
12495     * Like {@link #getMeasuredHeightAndState()}, but only returns the
12496     * raw height component (that is the result is masked by
12497     * {@link #MEASURED_SIZE_MASK}).
12498     *
12499     * @return The raw measured height of this view.
12500     */
12501    public final int getMeasuredHeight() {
12502        return mMeasuredHeight & MEASURED_SIZE_MASK;
12503    }
12504
12505    /**
12506     * Return the full height measurement information for this view as computed
12507     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12508     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12509     * This should be used during measurement and layout calculations only. Use
12510     * {@link #getHeight()} to see how wide a view is after layout.
12511     *
12512     * @return The measured height of this view as a bit mask.
12513     */
12514    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12515            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12516                    name = "MEASURED_STATE_TOO_SMALL"),
12517    })
12518    public final int getMeasuredHeightAndState() {
12519        return mMeasuredHeight;
12520    }
12521
12522    /**
12523     * Return only the state bits of {@link #getMeasuredWidthAndState()}
12524     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
12525     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
12526     * and the height component is at the shifted bits
12527     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
12528     */
12529    public final int getMeasuredState() {
12530        return (mMeasuredWidth&MEASURED_STATE_MASK)
12531                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
12532                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
12533    }
12534
12535    /**
12536     * The transform matrix of this view, which is calculated based on the current
12537     * rotation, scale, and pivot properties.
12538     *
12539     * @see #getRotation()
12540     * @see #getScaleX()
12541     * @see #getScaleY()
12542     * @see #getPivotX()
12543     * @see #getPivotY()
12544     * @return The current transform matrix for the view
12545     */
12546    public Matrix getMatrix() {
12547        ensureTransformationInfo();
12548        final Matrix matrix = mTransformationInfo.mMatrix;
12549        mRenderNode.getMatrix(matrix);
12550        return matrix;
12551    }
12552
12553    /**
12554     * Returns true if the transform matrix is the identity matrix.
12555     * Recomputes the matrix if necessary.
12556     *
12557     * @return True if the transform matrix is the identity matrix, false otherwise.
12558     */
12559    final boolean hasIdentityMatrix() {
12560        return mRenderNode.hasIdentityMatrix();
12561    }
12562
12563    void ensureTransformationInfo() {
12564        if (mTransformationInfo == null) {
12565            mTransformationInfo = new TransformationInfo();
12566        }
12567    }
12568
12569    /**
12570     * Utility method to retrieve the inverse of the current mMatrix property.
12571     * We cache the matrix to avoid recalculating it when transform properties
12572     * have not changed.
12573     *
12574     * @return The inverse of the current matrix of this view.
12575     * @hide
12576     */
12577    public final Matrix getInverseMatrix() {
12578        ensureTransformationInfo();
12579        if (mTransformationInfo.mInverseMatrix == null) {
12580            mTransformationInfo.mInverseMatrix = new Matrix();
12581        }
12582        final Matrix matrix = mTransformationInfo.mInverseMatrix;
12583        mRenderNode.getInverseMatrix(matrix);
12584        return matrix;
12585    }
12586
12587    /**
12588     * Gets the distance along the Z axis from the camera to this view.
12589     *
12590     * @see #setCameraDistance(float)
12591     *
12592     * @return The distance along the Z axis.
12593     */
12594    public float getCameraDistance() {
12595        final float dpi = mResources.getDisplayMetrics().densityDpi;
12596        return -(mRenderNode.getCameraDistance() * dpi);
12597    }
12598
12599    /**
12600     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
12601     * views are drawn) from the camera to this view. The camera's distance
12602     * affects 3D transformations, for instance rotations around the X and Y
12603     * axis. If the rotationX or rotationY properties are changed and this view is
12604     * large (more than half the size of the screen), it is recommended to always
12605     * use a camera distance that's greater than the height (X axis rotation) or
12606     * the width (Y axis rotation) of this view.</p>
12607     *
12608     * <p>The distance of the camera from the view plane can have an affect on the
12609     * perspective distortion of the view when it is rotated around the x or y axis.
12610     * For example, a large distance will result in a large viewing angle, and there
12611     * will not be much perspective distortion of the view as it rotates. A short
12612     * distance may cause much more perspective distortion upon rotation, and can
12613     * also result in some drawing artifacts if the rotated view ends up partially
12614     * behind the camera (which is why the recommendation is to use a distance at
12615     * least as far as the size of the view, if the view is to be rotated.)</p>
12616     *
12617     * <p>The distance is expressed in "depth pixels." The default distance depends
12618     * on the screen density. For instance, on a medium density display, the
12619     * default distance is 1280. On a high density display, the default distance
12620     * is 1920.</p>
12621     *
12622     * <p>If you want to specify a distance that leads to visually consistent
12623     * results across various densities, use the following formula:</p>
12624     * <pre>
12625     * float scale = context.getResources().getDisplayMetrics().density;
12626     * view.setCameraDistance(distance * scale);
12627     * </pre>
12628     *
12629     * <p>The density scale factor of a high density display is 1.5,
12630     * and 1920 = 1280 * 1.5.</p>
12631     *
12632     * @param distance The distance in "depth pixels", if negative the opposite
12633     *        value is used
12634     *
12635     * @see #setRotationX(float)
12636     * @see #setRotationY(float)
12637     */
12638    public void setCameraDistance(float distance) {
12639        final float dpi = mResources.getDisplayMetrics().densityDpi;
12640
12641        invalidateViewProperty(true, false);
12642        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
12643        invalidateViewProperty(false, false);
12644
12645        invalidateParentIfNeededAndWasQuickRejected();
12646    }
12647
12648    /**
12649     * The degrees that the view is rotated around the pivot point.
12650     *
12651     * @see #setRotation(float)
12652     * @see #getPivotX()
12653     * @see #getPivotY()
12654     *
12655     * @return The degrees of rotation.
12656     */
12657    @ViewDebug.ExportedProperty(category = "drawing")
12658    public float getRotation() {
12659        return mRenderNode.getRotation();
12660    }
12661
12662    /**
12663     * Sets the degrees that the view is rotated around the pivot point. Increasing values
12664     * result in clockwise rotation.
12665     *
12666     * @param rotation The degrees of rotation.
12667     *
12668     * @see #getRotation()
12669     * @see #getPivotX()
12670     * @see #getPivotY()
12671     * @see #setRotationX(float)
12672     * @see #setRotationY(float)
12673     *
12674     * @attr ref android.R.styleable#View_rotation
12675     */
12676    public void setRotation(float rotation) {
12677        if (rotation != getRotation()) {
12678            // Double-invalidation is necessary to capture view's old and new areas
12679            invalidateViewProperty(true, false);
12680            mRenderNode.setRotation(rotation);
12681            invalidateViewProperty(false, true);
12682
12683            invalidateParentIfNeededAndWasQuickRejected();
12684            notifySubtreeAccessibilityStateChangedIfNeeded();
12685        }
12686    }
12687
12688    /**
12689     * The degrees that the view is rotated around the vertical axis through the pivot point.
12690     *
12691     * @see #getPivotX()
12692     * @see #getPivotY()
12693     * @see #setRotationY(float)
12694     *
12695     * @return The degrees of Y rotation.
12696     */
12697    @ViewDebug.ExportedProperty(category = "drawing")
12698    public float getRotationY() {
12699        return mRenderNode.getRotationY();
12700    }
12701
12702    /**
12703     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
12704     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
12705     * down the y axis.
12706     *
12707     * When rotating large views, it is recommended to adjust the camera distance
12708     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12709     *
12710     * @param rotationY The degrees of Y rotation.
12711     *
12712     * @see #getRotationY()
12713     * @see #getPivotX()
12714     * @see #getPivotY()
12715     * @see #setRotation(float)
12716     * @see #setRotationX(float)
12717     * @see #setCameraDistance(float)
12718     *
12719     * @attr ref android.R.styleable#View_rotationY
12720     */
12721    public void setRotationY(float rotationY) {
12722        if (rotationY != getRotationY()) {
12723            invalidateViewProperty(true, false);
12724            mRenderNode.setRotationY(rotationY);
12725            invalidateViewProperty(false, true);
12726
12727            invalidateParentIfNeededAndWasQuickRejected();
12728            notifySubtreeAccessibilityStateChangedIfNeeded();
12729        }
12730    }
12731
12732    /**
12733     * The degrees that the view is rotated around the horizontal axis through the pivot point.
12734     *
12735     * @see #getPivotX()
12736     * @see #getPivotY()
12737     * @see #setRotationX(float)
12738     *
12739     * @return The degrees of X rotation.
12740     */
12741    @ViewDebug.ExportedProperty(category = "drawing")
12742    public float getRotationX() {
12743        return mRenderNode.getRotationX();
12744    }
12745
12746    /**
12747     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12748     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12749     * x axis.
12750     *
12751     * When rotating large views, it is recommended to adjust the camera distance
12752     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12753     *
12754     * @param rotationX The degrees of X rotation.
12755     *
12756     * @see #getRotationX()
12757     * @see #getPivotX()
12758     * @see #getPivotY()
12759     * @see #setRotation(float)
12760     * @see #setRotationY(float)
12761     * @see #setCameraDistance(float)
12762     *
12763     * @attr ref android.R.styleable#View_rotationX
12764     */
12765    public void setRotationX(float rotationX) {
12766        if (rotationX != getRotationX()) {
12767            invalidateViewProperty(true, false);
12768            mRenderNode.setRotationX(rotationX);
12769            invalidateViewProperty(false, true);
12770
12771            invalidateParentIfNeededAndWasQuickRejected();
12772            notifySubtreeAccessibilityStateChangedIfNeeded();
12773        }
12774    }
12775
12776    /**
12777     * The amount that the view is scaled in x around the pivot point, as a proportion of
12778     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12779     *
12780     * <p>By default, this is 1.0f.
12781     *
12782     * @see #getPivotX()
12783     * @see #getPivotY()
12784     * @return The scaling factor.
12785     */
12786    @ViewDebug.ExportedProperty(category = "drawing")
12787    public float getScaleX() {
12788        return mRenderNode.getScaleX();
12789    }
12790
12791    /**
12792     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12793     * the view's unscaled width. A value of 1 means that no scaling is applied.
12794     *
12795     * @param scaleX The scaling factor.
12796     * @see #getPivotX()
12797     * @see #getPivotY()
12798     *
12799     * @attr ref android.R.styleable#View_scaleX
12800     */
12801    public void setScaleX(float scaleX) {
12802        if (scaleX != getScaleX()) {
12803            invalidateViewProperty(true, false);
12804            mRenderNode.setScaleX(scaleX);
12805            invalidateViewProperty(false, true);
12806
12807            invalidateParentIfNeededAndWasQuickRejected();
12808            notifySubtreeAccessibilityStateChangedIfNeeded();
12809        }
12810    }
12811
12812    /**
12813     * The amount that the view is scaled in y around the pivot point, as a proportion of
12814     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12815     *
12816     * <p>By default, this is 1.0f.
12817     *
12818     * @see #getPivotX()
12819     * @see #getPivotY()
12820     * @return The scaling factor.
12821     */
12822    @ViewDebug.ExportedProperty(category = "drawing")
12823    public float getScaleY() {
12824        return mRenderNode.getScaleY();
12825    }
12826
12827    /**
12828     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12829     * the view's unscaled width. A value of 1 means that no scaling is applied.
12830     *
12831     * @param scaleY The scaling factor.
12832     * @see #getPivotX()
12833     * @see #getPivotY()
12834     *
12835     * @attr ref android.R.styleable#View_scaleY
12836     */
12837    public void setScaleY(float scaleY) {
12838        if (scaleY != getScaleY()) {
12839            invalidateViewProperty(true, false);
12840            mRenderNode.setScaleY(scaleY);
12841            invalidateViewProperty(false, true);
12842
12843            invalidateParentIfNeededAndWasQuickRejected();
12844            notifySubtreeAccessibilityStateChangedIfNeeded();
12845        }
12846    }
12847
12848    /**
12849     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12850     * and {@link #setScaleX(float) scaled}.
12851     *
12852     * @see #getRotation()
12853     * @see #getScaleX()
12854     * @see #getScaleY()
12855     * @see #getPivotY()
12856     * @return The x location of the pivot point.
12857     *
12858     * @attr ref android.R.styleable#View_transformPivotX
12859     */
12860    @ViewDebug.ExportedProperty(category = "drawing")
12861    public float getPivotX() {
12862        return mRenderNode.getPivotX();
12863    }
12864
12865    /**
12866     * Sets the x location of the point around which the view is
12867     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12868     * By default, the pivot point is centered on the object.
12869     * Setting this property disables this behavior and causes the view to use only the
12870     * explicitly set pivotX and pivotY values.
12871     *
12872     * @param pivotX The x location of the pivot point.
12873     * @see #getRotation()
12874     * @see #getScaleX()
12875     * @see #getScaleY()
12876     * @see #getPivotY()
12877     *
12878     * @attr ref android.R.styleable#View_transformPivotX
12879     */
12880    public void setPivotX(float pivotX) {
12881        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12882            invalidateViewProperty(true, false);
12883            mRenderNode.setPivotX(pivotX);
12884            invalidateViewProperty(false, true);
12885
12886            invalidateParentIfNeededAndWasQuickRejected();
12887        }
12888    }
12889
12890    /**
12891     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12892     * and {@link #setScaleY(float) scaled}.
12893     *
12894     * @see #getRotation()
12895     * @see #getScaleX()
12896     * @see #getScaleY()
12897     * @see #getPivotY()
12898     * @return The y location of the pivot point.
12899     *
12900     * @attr ref android.R.styleable#View_transformPivotY
12901     */
12902    @ViewDebug.ExportedProperty(category = "drawing")
12903    public float getPivotY() {
12904        return mRenderNode.getPivotY();
12905    }
12906
12907    /**
12908     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12909     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12910     * Setting this property disables this behavior and causes the view to use only the
12911     * explicitly set pivotX and pivotY values.
12912     *
12913     * @param pivotY The y location of the pivot point.
12914     * @see #getRotation()
12915     * @see #getScaleX()
12916     * @see #getScaleY()
12917     * @see #getPivotY()
12918     *
12919     * @attr ref android.R.styleable#View_transformPivotY
12920     */
12921    public void setPivotY(float pivotY) {
12922        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12923            invalidateViewProperty(true, false);
12924            mRenderNode.setPivotY(pivotY);
12925            invalidateViewProperty(false, true);
12926
12927            invalidateParentIfNeededAndWasQuickRejected();
12928        }
12929    }
12930
12931    /**
12932     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12933     * completely transparent and 1 means the view is completely opaque.
12934     *
12935     * <p>By default this is 1.0f.
12936     * @return The opacity of the view.
12937     */
12938    @ViewDebug.ExportedProperty(category = "drawing")
12939    public float getAlpha() {
12940        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12941    }
12942
12943    /**
12944     * Sets the behavior for overlapping rendering for this view (see {@link
12945     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12946     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12947     * providing the value which is then used internally. That is, when {@link
12948     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12949     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12950     * instead.
12951     *
12952     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12953     * instead of that returned by {@link #hasOverlappingRendering()}.
12954     *
12955     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12956     */
12957    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12958        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12959        if (hasOverlappingRendering) {
12960            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12961        } else {
12962            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12963        }
12964    }
12965
12966    /**
12967     * Returns the value for overlapping rendering that is used internally. This is either
12968     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12969     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12970     *
12971     * @return The value for overlapping rendering being used internally.
12972     */
12973    public final boolean getHasOverlappingRendering() {
12974        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12975                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12976                hasOverlappingRendering();
12977    }
12978
12979    /**
12980     * Returns whether this View has content which overlaps.
12981     *
12982     * <p>This function, intended to be overridden by specific View types, is an optimization when
12983     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12984     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12985     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12986     * directly. An example of overlapping rendering is a TextView with a background image, such as
12987     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12988     * ImageView with only the foreground image. The default implementation returns true; subclasses
12989     * should override if they have cases which can be optimized.</p>
12990     *
12991     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12992     * necessitates that a View return true if it uses the methods internally without passing the
12993     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12994     *
12995     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12996     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12997     *
12998     * @return true if the content in this view might overlap, false otherwise.
12999     */
13000    @ViewDebug.ExportedProperty(category = "drawing")
13001    public boolean hasOverlappingRendering() {
13002        return true;
13003    }
13004
13005    /**
13006     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
13007     * completely transparent and 1 means the view is completely opaque.
13008     *
13009     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
13010     * can have significant performance implications, especially for large views. It is best to use
13011     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
13012     *
13013     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
13014     * strongly recommended for performance reasons to either override
13015     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
13016     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
13017     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
13018     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
13019     * of rendering cost, even for simple or small views. Starting with
13020     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
13021     * applied to the view at the rendering level.</p>
13022     *
13023     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
13024     * responsible for applying the opacity itself.</p>
13025     *
13026     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
13027     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
13028     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
13029     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
13030     *
13031     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
13032     * value will clip a View to its bounds, unless the View returns <code>false</code> from
13033     * {@link #hasOverlappingRendering}.</p>
13034     *
13035     * @param alpha The opacity of the view.
13036     *
13037     * @see #hasOverlappingRendering()
13038     * @see #setLayerType(int, android.graphics.Paint)
13039     *
13040     * @attr ref android.R.styleable#View_alpha
13041     */
13042    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
13043        ensureTransformationInfo();
13044        if (mTransformationInfo.mAlpha != alpha) {
13045            // Report visibility changes, which can affect children, to accessibility
13046            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
13047                notifySubtreeAccessibilityStateChangedIfNeeded();
13048            }
13049            mTransformationInfo.mAlpha = alpha;
13050            if (onSetAlpha((int) (alpha * 255))) {
13051                mPrivateFlags |= PFLAG_ALPHA_SET;
13052                // subclass is handling alpha - don't optimize rendering cache invalidation
13053                invalidateParentCaches();
13054                invalidate(true);
13055            } else {
13056                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13057                invalidateViewProperty(true, false);
13058                mRenderNode.setAlpha(getFinalAlpha());
13059            }
13060        }
13061    }
13062
13063    /**
13064     * Faster version of setAlpha() which performs the same steps except there are
13065     * no calls to invalidate(). The caller of this function should perform proper invalidation
13066     * on the parent and this object. The return value indicates whether the subclass handles
13067     * alpha (the return value for onSetAlpha()).
13068     *
13069     * @param alpha The new value for the alpha property
13070     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
13071     *         the new value for the alpha property is different from the old value
13072     */
13073    boolean setAlphaNoInvalidation(float alpha) {
13074        ensureTransformationInfo();
13075        if (mTransformationInfo.mAlpha != alpha) {
13076            mTransformationInfo.mAlpha = alpha;
13077            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
13078            if (subclassHandlesAlpha) {
13079                mPrivateFlags |= PFLAG_ALPHA_SET;
13080                return true;
13081            } else {
13082                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13083                mRenderNode.setAlpha(getFinalAlpha());
13084            }
13085        }
13086        return false;
13087    }
13088
13089    /**
13090     * This property is hidden and intended only for use by the Fade transition, which
13091     * animates it to produce a visual translucency that does not side-effect (or get
13092     * affected by) the real alpha property. This value is composited with the other
13093     * alpha value (and the AlphaAnimation value, when that is present) to produce
13094     * a final visual translucency result, which is what is passed into the DisplayList.
13095     *
13096     * @hide
13097     */
13098    public void setTransitionAlpha(float alpha) {
13099        ensureTransformationInfo();
13100        if (mTransformationInfo.mTransitionAlpha != alpha) {
13101            mTransformationInfo.mTransitionAlpha = alpha;
13102            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13103            invalidateViewProperty(true, false);
13104            mRenderNode.setAlpha(getFinalAlpha());
13105        }
13106    }
13107
13108    /**
13109     * Calculates the visual alpha of this view, which is a combination of the actual
13110     * alpha value and the transitionAlpha value (if set).
13111     */
13112    private float getFinalAlpha() {
13113        if (mTransformationInfo != null) {
13114            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
13115        }
13116        return 1;
13117    }
13118
13119    /**
13120     * This property is hidden and intended only for use by the Fade transition, which
13121     * animates it to produce a visual translucency that does not side-effect (or get
13122     * affected by) the real alpha property. This value is composited with the other
13123     * alpha value (and the AlphaAnimation value, when that is present) to produce
13124     * a final visual translucency result, which is what is passed into the DisplayList.
13125     *
13126     * @hide
13127     */
13128    @ViewDebug.ExportedProperty(category = "drawing")
13129    public float getTransitionAlpha() {
13130        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
13131    }
13132
13133    /**
13134     * Top position of this view relative to its parent.
13135     *
13136     * @return The top of this view, in pixels.
13137     */
13138    @ViewDebug.CapturedViewProperty
13139    public final int getTop() {
13140        return mTop;
13141    }
13142
13143    /**
13144     * Sets the top position of this view relative to its parent. This method is meant to be called
13145     * by the layout system and should not generally be called otherwise, because the property
13146     * may be changed at any time by the layout.
13147     *
13148     * @param top The top of this view, in pixels.
13149     */
13150    public final void setTop(int top) {
13151        if (top != mTop) {
13152            final boolean matrixIsIdentity = hasIdentityMatrix();
13153            if (matrixIsIdentity) {
13154                if (mAttachInfo != null) {
13155                    int minTop;
13156                    int yLoc;
13157                    if (top < mTop) {
13158                        minTop = top;
13159                        yLoc = top - mTop;
13160                    } else {
13161                        minTop = mTop;
13162                        yLoc = 0;
13163                    }
13164                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
13165                }
13166            } else {
13167                // Double-invalidation is necessary to capture view's old and new areas
13168                invalidate(true);
13169            }
13170
13171            int width = mRight - mLeft;
13172            int oldHeight = mBottom - mTop;
13173
13174            mTop = top;
13175            mRenderNode.setTop(mTop);
13176
13177            sizeChange(width, mBottom - mTop, width, oldHeight);
13178
13179            if (!matrixIsIdentity) {
13180                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13181                invalidate(true);
13182            }
13183            mBackgroundSizeChanged = true;
13184            if (mForegroundInfo != null) {
13185                mForegroundInfo.mBoundsChanged = true;
13186            }
13187            invalidateParentIfNeeded();
13188            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13189                // View was rejected last time it was drawn by its parent; this may have changed
13190                invalidateParentIfNeeded();
13191            }
13192        }
13193    }
13194
13195    /**
13196     * Bottom position of this view relative to its parent.
13197     *
13198     * @return The bottom of this view, in pixels.
13199     */
13200    @ViewDebug.CapturedViewProperty
13201    public final int getBottom() {
13202        return mBottom;
13203    }
13204
13205    /**
13206     * True if this view has changed since the last time being drawn.
13207     *
13208     * @return The dirty state of this view.
13209     */
13210    public boolean isDirty() {
13211        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
13212    }
13213
13214    /**
13215     * Sets the bottom position of this view relative to its parent. This method is meant to be
13216     * called by the layout system and should not generally be called otherwise, because the
13217     * property may be changed at any time by the layout.
13218     *
13219     * @param bottom The bottom of this view, in pixels.
13220     */
13221    public final void setBottom(int bottom) {
13222        if (bottom != mBottom) {
13223            final boolean matrixIsIdentity = hasIdentityMatrix();
13224            if (matrixIsIdentity) {
13225                if (mAttachInfo != null) {
13226                    int maxBottom;
13227                    if (bottom < mBottom) {
13228                        maxBottom = mBottom;
13229                    } else {
13230                        maxBottom = bottom;
13231                    }
13232                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
13233                }
13234            } else {
13235                // Double-invalidation is necessary to capture view's old and new areas
13236                invalidate(true);
13237            }
13238
13239            int width = mRight - mLeft;
13240            int oldHeight = mBottom - mTop;
13241
13242            mBottom = bottom;
13243            mRenderNode.setBottom(mBottom);
13244
13245            sizeChange(width, mBottom - mTop, width, oldHeight);
13246
13247            if (!matrixIsIdentity) {
13248                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13249                invalidate(true);
13250            }
13251            mBackgroundSizeChanged = true;
13252            if (mForegroundInfo != null) {
13253                mForegroundInfo.mBoundsChanged = true;
13254            }
13255            invalidateParentIfNeeded();
13256            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13257                // View was rejected last time it was drawn by its parent; this may have changed
13258                invalidateParentIfNeeded();
13259            }
13260        }
13261    }
13262
13263    /**
13264     * Left position of this view relative to its parent.
13265     *
13266     * @return The left edge of this view, in pixels.
13267     */
13268    @ViewDebug.CapturedViewProperty
13269    public final int getLeft() {
13270        return mLeft;
13271    }
13272
13273    /**
13274     * Sets the left position of this view relative to its parent. This method is meant to be called
13275     * by the layout system and should not generally be called otherwise, because the property
13276     * may be changed at any time by the layout.
13277     *
13278     * @param left The left of this view, in pixels.
13279     */
13280    public final void setLeft(int left) {
13281        if (left != mLeft) {
13282            final boolean matrixIsIdentity = hasIdentityMatrix();
13283            if (matrixIsIdentity) {
13284                if (mAttachInfo != null) {
13285                    int minLeft;
13286                    int xLoc;
13287                    if (left < mLeft) {
13288                        minLeft = left;
13289                        xLoc = left - mLeft;
13290                    } else {
13291                        minLeft = mLeft;
13292                        xLoc = 0;
13293                    }
13294                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
13295                }
13296            } else {
13297                // Double-invalidation is necessary to capture view's old and new areas
13298                invalidate(true);
13299            }
13300
13301            int oldWidth = mRight - mLeft;
13302            int height = mBottom - mTop;
13303
13304            mLeft = left;
13305            mRenderNode.setLeft(left);
13306
13307            sizeChange(mRight - mLeft, height, oldWidth, height);
13308
13309            if (!matrixIsIdentity) {
13310                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13311                invalidate(true);
13312            }
13313            mBackgroundSizeChanged = true;
13314            if (mForegroundInfo != null) {
13315                mForegroundInfo.mBoundsChanged = true;
13316            }
13317            invalidateParentIfNeeded();
13318            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13319                // View was rejected last time it was drawn by its parent; this may have changed
13320                invalidateParentIfNeeded();
13321            }
13322        }
13323    }
13324
13325    /**
13326     * Right position of this view relative to its parent.
13327     *
13328     * @return The right edge of this view, in pixels.
13329     */
13330    @ViewDebug.CapturedViewProperty
13331    public final int getRight() {
13332        return mRight;
13333    }
13334
13335    /**
13336     * Sets the right position of this view relative to its parent. This method is meant to be called
13337     * by the layout system and should not generally be called otherwise, because the property
13338     * may be changed at any time by the layout.
13339     *
13340     * @param right The right of this view, in pixels.
13341     */
13342    public final void setRight(int right) {
13343        if (right != mRight) {
13344            final boolean matrixIsIdentity = hasIdentityMatrix();
13345            if (matrixIsIdentity) {
13346                if (mAttachInfo != null) {
13347                    int maxRight;
13348                    if (right < mRight) {
13349                        maxRight = mRight;
13350                    } else {
13351                        maxRight = right;
13352                    }
13353                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
13354                }
13355            } else {
13356                // Double-invalidation is necessary to capture view's old and new areas
13357                invalidate(true);
13358            }
13359
13360            int oldWidth = mRight - mLeft;
13361            int height = mBottom - mTop;
13362
13363            mRight = right;
13364            mRenderNode.setRight(mRight);
13365
13366            sizeChange(mRight - mLeft, height, oldWidth, height);
13367
13368            if (!matrixIsIdentity) {
13369                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13370                invalidate(true);
13371            }
13372            mBackgroundSizeChanged = true;
13373            if (mForegroundInfo != null) {
13374                mForegroundInfo.mBoundsChanged = true;
13375            }
13376            invalidateParentIfNeeded();
13377            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13378                // View was rejected last time it was drawn by its parent; this may have changed
13379                invalidateParentIfNeeded();
13380            }
13381        }
13382    }
13383
13384    /**
13385     * The visual x position of this view, in pixels. This is equivalent to the
13386     * {@link #setTranslationX(float) translationX} property plus the current
13387     * {@link #getLeft() left} property.
13388     *
13389     * @return The visual x position of this view, in pixels.
13390     */
13391    @ViewDebug.ExportedProperty(category = "drawing")
13392    public float getX() {
13393        return mLeft + getTranslationX();
13394    }
13395
13396    /**
13397     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
13398     * {@link #setTranslationX(float) translationX} property to be the difference between
13399     * the x value passed in and the current {@link #getLeft() left} property.
13400     *
13401     * @param x The visual x position of this view, in pixels.
13402     */
13403    public void setX(float x) {
13404        setTranslationX(x - mLeft);
13405    }
13406
13407    /**
13408     * The visual y position of this view, in pixels. This is equivalent to the
13409     * {@link #setTranslationY(float) translationY} property plus the current
13410     * {@link #getTop() top} property.
13411     *
13412     * @return The visual y position of this view, in pixels.
13413     */
13414    @ViewDebug.ExportedProperty(category = "drawing")
13415    public float getY() {
13416        return mTop + getTranslationY();
13417    }
13418
13419    /**
13420     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
13421     * {@link #setTranslationY(float) translationY} property to be the difference between
13422     * the y value passed in and the current {@link #getTop() top} property.
13423     *
13424     * @param y The visual y position of this view, in pixels.
13425     */
13426    public void setY(float y) {
13427        setTranslationY(y - mTop);
13428    }
13429
13430    /**
13431     * The visual z position of this view, in pixels. This is equivalent to the
13432     * {@link #setTranslationZ(float) translationZ} property plus the current
13433     * {@link #getElevation() elevation} property.
13434     *
13435     * @return The visual z position of this view, in pixels.
13436     */
13437    @ViewDebug.ExportedProperty(category = "drawing")
13438    public float getZ() {
13439        return getElevation() + getTranslationZ();
13440    }
13441
13442    /**
13443     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
13444     * {@link #setTranslationZ(float) translationZ} property to be the difference between
13445     * the x value passed in and the current {@link #getElevation() elevation} property.
13446     *
13447     * @param z The visual z position of this view, in pixels.
13448     */
13449    public void setZ(float z) {
13450        setTranslationZ(z - getElevation());
13451    }
13452
13453    /**
13454     * The base elevation of this view relative to its parent, in pixels.
13455     *
13456     * @return The base depth position of the view, in pixels.
13457     */
13458    @ViewDebug.ExportedProperty(category = "drawing")
13459    public float getElevation() {
13460        return mRenderNode.getElevation();
13461    }
13462
13463    /**
13464     * Sets the base elevation of this view, in pixels.
13465     *
13466     * @attr ref android.R.styleable#View_elevation
13467     */
13468    public void setElevation(float elevation) {
13469        if (elevation != getElevation()) {
13470            invalidateViewProperty(true, false);
13471            mRenderNode.setElevation(elevation);
13472            invalidateViewProperty(false, true);
13473
13474            invalidateParentIfNeededAndWasQuickRejected();
13475        }
13476    }
13477
13478    /**
13479     * The horizontal location of this view relative to its {@link #getLeft() left} position.
13480     * This position is post-layout, in addition to wherever the object's
13481     * layout placed it.
13482     *
13483     * @return The horizontal position of this view relative to its left position, in pixels.
13484     */
13485    @ViewDebug.ExportedProperty(category = "drawing")
13486    public float getTranslationX() {
13487        return mRenderNode.getTranslationX();
13488    }
13489
13490    /**
13491     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
13492     * This effectively positions the object post-layout, in addition to wherever the object's
13493     * layout placed it.
13494     *
13495     * @param translationX The horizontal position of this view relative to its left position,
13496     * in pixels.
13497     *
13498     * @attr ref android.R.styleable#View_translationX
13499     */
13500    public void setTranslationX(float translationX) {
13501        if (translationX != getTranslationX()) {
13502            invalidateViewProperty(true, false);
13503            mRenderNode.setTranslationX(translationX);
13504            invalidateViewProperty(false, true);
13505
13506            invalidateParentIfNeededAndWasQuickRejected();
13507            notifySubtreeAccessibilityStateChangedIfNeeded();
13508        }
13509    }
13510
13511    /**
13512     * The vertical location of this view relative to its {@link #getTop() top} position.
13513     * This position is post-layout, in addition to wherever the object's
13514     * layout placed it.
13515     *
13516     * @return The vertical position of this view relative to its top position,
13517     * in pixels.
13518     */
13519    @ViewDebug.ExportedProperty(category = "drawing")
13520    public float getTranslationY() {
13521        return mRenderNode.getTranslationY();
13522    }
13523
13524    /**
13525     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
13526     * This effectively positions the object post-layout, in addition to wherever the object's
13527     * layout placed it.
13528     *
13529     * @param translationY The vertical position of this view relative to its top position,
13530     * in pixels.
13531     *
13532     * @attr ref android.R.styleable#View_translationY
13533     */
13534    public void setTranslationY(float translationY) {
13535        if (translationY != getTranslationY()) {
13536            invalidateViewProperty(true, false);
13537            mRenderNode.setTranslationY(translationY);
13538            invalidateViewProperty(false, true);
13539
13540            invalidateParentIfNeededAndWasQuickRejected();
13541            notifySubtreeAccessibilityStateChangedIfNeeded();
13542        }
13543    }
13544
13545    /**
13546     * The depth location of this view relative to its {@link #getElevation() elevation}.
13547     *
13548     * @return The depth of this view relative to its elevation.
13549     */
13550    @ViewDebug.ExportedProperty(category = "drawing")
13551    public float getTranslationZ() {
13552        return mRenderNode.getTranslationZ();
13553    }
13554
13555    /**
13556     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
13557     *
13558     * @attr ref android.R.styleable#View_translationZ
13559     */
13560    public void setTranslationZ(float translationZ) {
13561        if (translationZ != getTranslationZ()) {
13562            invalidateViewProperty(true, false);
13563            mRenderNode.setTranslationZ(translationZ);
13564            invalidateViewProperty(false, true);
13565
13566            invalidateParentIfNeededAndWasQuickRejected();
13567        }
13568    }
13569
13570    /** @hide */
13571    public void setAnimationMatrix(Matrix matrix) {
13572        invalidateViewProperty(true, false);
13573        mRenderNode.setAnimationMatrix(matrix);
13574        invalidateViewProperty(false, true);
13575
13576        invalidateParentIfNeededAndWasQuickRejected();
13577    }
13578
13579    /**
13580     * Returns the current StateListAnimator if exists.
13581     *
13582     * @return StateListAnimator or null if it does not exists
13583     * @see    #setStateListAnimator(android.animation.StateListAnimator)
13584     */
13585    public StateListAnimator getStateListAnimator() {
13586        return mStateListAnimator;
13587    }
13588
13589    /**
13590     * Attaches the provided StateListAnimator to this View.
13591     * <p>
13592     * Any previously attached StateListAnimator will be detached.
13593     *
13594     * @param stateListAnimator The StateListAnimator to update the view
13595     * @see android.animation.StateListAnimator
13596     */
13597    public void setStateListAnimator(StateListAnimator stateListAnimator) {
13598        if (mStateListAnimator == stateListAnimator) {
13599            return;
13600        }
13601        if (mStateListAnimator != null) {
13602            mStateListAnimator.setTarget(null);
13603        }
13604        mStateListAnimator = stateListAnimator;
13605        if (stateListAnimator != null) {
13606            stateListAnimator.setTarget(this);
13607            if (isAttachedToWindow()) {
13608                stateListAnimator.setState(getDrawableState());
13609            }
13610        }
13611    }
13612
13613    /**
13614     * Returns whether the Outline should be used to clip the contents of the View.
13615     * <p>
13616     * Note that this flag will only be respected if the View's Outline returns true from
13617     * {@link Outline#canClip()}.
13618     *
13619     * @see #setOutlineProvider(ViewOutlineProvider)
13620     * @see #setClipToOutline(boolean)
13621     */
13622    public final boolean getClipToOutline() {
13623        return mRenderNode.getClipToOutline();
13624    }
13625
13626    /**
13627     * Sets whether the View's Outline should be used to clip the contents of the View.
13628     * <p>
13629     * Only a single non-rectangular clip can be applied on a View at any time.
13630     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
13631     * circular reveal} animation take priority over Outline clipping, and
13632     * child Outline clipping takes priority over Outline clipping done by a
13633     * parent.
13634     * <p>
13635     * Note that this flag will only be respected if the View's Outline returns true from
13636     * {@link Outline#canClip()}.
13637     *
13638     * @see #setOutlineProvider(ViewOutlineProvider)
13639     * @see #getClipToOutline()
13640     */
13641    public void setClipToOutline(boolean clipToOutline) {
13642        damageInParent();
13643        if (getClipToOutline() != clipToOutline) {
13644            mRenderNode.setClipToOutline(clipToOutline);
13645        }
13646    }
13647
13648    // correspond to the enum values of View_outlineProvider
13649    private static final int PROVIDER_BACKGROUND = 0;
13650    private static final int PROVIDER_NONE = 1;
13651    private static final int PROVIDER_BOUNDS = 2;
13652    private static final int PROVIDER_PADDED_BOUNDS = 3;
13653    private void setOutlineProviderFromAttribute(int providerInt) {
13654        switch (providerInt) {
13655            case PROVIDER_BACKGROUND:
13656                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
13657                break;
13658            case PROVIDER_NONE:
13659                setOutlineProvider(null);
13660                break;
13661            case PROVIDER_BOUNDS:
13662                setOutlineProvider(ViewOutlineProvider.BOUNDS);
13663                break;
13664            case PROVIDER_PADDED_BOUNDS:
13665                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
13666                break;
13667        }
13668    }
13669
13670    /**
13671     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
13672     * the shape of the shadow it casts, and enables outline clipping.
13673     * <p>
13674     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
13675     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
13676     * outline provider with this method allows this behavior to be overridden.
13677     * <p>
13678     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
13679     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
13680     * <p>
13681     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
13682     *
13683     * @see #setClipToOutline(boolean)
13684     * @see #getClipToOutline()
13685     * @see #getOutlineProvider()
13686     */
13687    public void setOutlineProvider(ViewOutlineProvider provider) {
13688        mOutlineProvider = provider;
13689        invalidateOutline();
13690    }
13691
13692    /**
13693     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
13694     * that defines the shape of the shadow it casts, and enables outline clipping.
13695     *
13696     * @see #setOutlineProvider(ViewOutlineProvider)
13697     */
13698    public ViewOutlineProvider getOutlineProvider() {
13699        return mOutlineProvider;
13700    }
13701
13702    /**
13703     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
13704     *
13705     * @see #setOutlineProvider(ViewOutlineProvider)
13706     */
13707    public void invalidateOutline() {
13708        rebuildOutline();
13709
13710        notifySubtreeAccessibilityStateChangedIfNeeded();
13711        invalidateViewProperty(false, false);
13712    }
13713
13714    /**
13715     * Internal version of {@link #invalidateOutline()} which invalidates the
13716     * outline without invalidating the view itself. This is intended to be called from
13717     * within methods in the View class itself which are the result of the view being
13718     * invalidated already. For example, when we are drawing the background of a View,
13719     * we invalidate the outline in case it changed in the meantime, but we do not
13720     * need to invalidate the view because we're already drawing the background as part
13721     * of drawing the view in response to an earlier invalidation of the view.
13722     */
13723    private void rebuildOutline() {
13724        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
13725        if (mAttachInfo == null) return;
13726
13727        if (mOutlineProvider == null) {
13728            // no provider, remove outline
13729            mRenderNode.setOutline(null);
13730        } else {
13731            final Outline outline = mAttachInfo.mTmpOutline;
13732            outline.setEmpty();
13733            outline.setAlpha(1.0f);
13734
13735            mOutlineProvider.getOutline(this, outline);
13736            mRenderNode.setOutline(outline);
13737        }
13738    }
13739
13740    /**
13741     * HierarchyViewer only
13742     *
13743     * @hide
13744     */
13745    @ViewDebug.ExportedProperty(category = "drawing")
13746    public boolean hasShadow() {
13747        return mRenderNode.hasShadow();
13748    }
13749
13750
13751    /** @hide */
13752    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13753        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13754        invalidateViewProperty(false, false);
13755    }
13756
13757    /**
13758     * Hit rectangle in parent's coordinates
13759     *
13760     * @param outRect The hit rectangle of the view.
13761     */
13762    public void getHitRect(Rect outRect) {
13763        if (hasIdentityMatrix() || mAttachInfo == null) {
13764            outRect.set(mLeft, mTop, mRight, mBottom);
13765        } else {
13766            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13767            tmpRect.set(0, 0, getWidth(), getHeight());
13768            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13769            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13770                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13771        }
13772    }
13773
13774    /**
13775     * Determines whether the given point, in local coordinates is inside the view.
13776     */
13777    /*package*/ final boolean pointInView(float localX, float localY) {
13778        return pointInView(localX, localY, 0);
13779    }
13780
13781    /**
13782     * Utility method to determine whether the given point, in local coordinates,
13783     * is inside the view, where the area of the view is expanded by the slop factor.
13784     * This method is called while processing touch-move events to determine if the event
13785     * is still within the view.
13786     *
13787     * @hide
13788     */
13789    public boolean pointInView(float localX, float localY, float slop) {
13790        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13791                localY < ((mBottom - mTop) + slop);
13792    }
13793
13794    /**
13795     * When a view has focus and the user navigates away from it, the next view is searched for
13796     * starting from the rectangle filled in by this method.
13797     *
13798     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13799     * of the view.  However, if your view maintains some idea of internal selection,
13800     * such as a cursor, or a selected row or column, you should override this method and
13801     * fill in a more specific rectangle.
13802     *
13803     * @param r The rectangle to fill in, in this view's coordinates.
13804     */
13805    public void getFocusedRect(Rect r) {
13806        getDrawingRect(r);
13807    }
13808
13809    /**
13810     * If some part of this view is not clipped by any of its parents, then
13811     * return that area in r in global (root) coordinates. To convert r to local
13812     * coordinates (without taking possible View rotations into account), offset
13813     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13814     * If the view is completely clipped or translated out, return false.
13815     *
13816     * @param r If true is returned, r holds the global coordinates of the
13817     *        visible portion of this view.
13818     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13819     *        between this view and its root. globalOffet may be null.
13820     * @return true if r is non-empty (i.e. part of the view is visible at the
13821     *         root level.
13822     */
13823    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13824        int width = mRight - mLeft;
13825        int height = mBottom - mTop;
13826        if (width > 0 && height > 0) {
13827            r.set(0, 0, width, height);
13828            if (globalOffset != null) {
13829                globalOffset.set(-mScrollX, -mScrollY);
13830            }
13831            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13832        }
13833        return false;
13834    }
13835
13836    public final boolean getGlobalVisibleRect(Rect r) {
13837        return getGlobalVisibleRect(r, null);
13838    }
13839
13840    public final boolean getLocalVisibleRect(Rect r) {
13841        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13842        if (getGlobalVisibleRect(r, offset)) {
13843            r.offset(-offset.x, -offset.y); // make r local
13844            return true;
13845        }
13846        return false;
13847    }
13848
13849    /**
13850     * Offset this view's vertical location by the specified number of pixels.
13851     *
13852     * @param offset the number of pixels to offset the view by
13853     */
13854    public void offsetTopAndBottom(int offset) {
13855        if (offset != 0) {
13856            final boolean matrixIsIdentity = hasIdentityMatrix();
13857            if (matrixIsIdentity) {
13858                if (isHardwareAccelerated()) {
13859                    invalidateViewProperty(false, false);
13860                } else {
13861                    final ViewParent p = mParent;
13862                    if (p != null && mAttachInfo != null) {
13863                        final Rect r = mAttachInfo.mTmpInvalRect;
13864                        int minTop;
13865                        int maxBottom;
13866                        int yLoc;
13867                        if (offset < 0) {
13868                            minTop = mTop + offset;
13869                            maxBottom = mBottom;
13870                            yLoc = offset;
13871                        } else {
13872                            minTop = mTop;
13873                            maxBottom = mBottom + offset;
13874                            yLoc = 0;
13875                        }
13876                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13877                        p.invalidateChild(this, r);
13878                    }
13879                }
13880            } else {
13881                invalidateViewProperty(false, false);
13882            }
13883
13884            mTop += offset;
13885            mBottom += offset;
13886            mRenderNode.offsetTopAndBottom(offset);
13887            if (isHardwareAccelerated()) {
13888                invalidateViewProperty(false, false);
13889                invalidateParentIfNeededAndWasQuickRejected();
13890            } else {
13891                if (!matrixIsIdentity) {
13892                    invalidateViewProperty(false, true);
13893                }
13894                invalidateParentIfNeeded();
13895            }
13896            notifySubtreeAccessibilityStateChangedIfNeeded();
13897        }
13898    }
13899
13900    /**
13901     * Offset this view's horizontal location by the specified amount of pixels.
13902     *
13903     * @param offset the number of pixels to offset the view by
13904     */
13905    public void offsetLeftAndRight(int offset) {
13906        if (offset != 0) {
13907            final boolean matrixIsIdentity = hasIdentityMatrix();
13908            if (matrixIsIdentity) {
13909                if (isHardwareAccelerated()) {
13910                    invalidateViewProperty(false, false);
13911                } else {
13912                    final ViewParent p = mParent;
13913                    if (p != null && mAttachInfo != null) {
13914                        final Rect r = mAttachInfo.mTmpInvalRect;
13915                        int minLeft;
13916                        int maxRight;
13917                        if (offset < 0) {
13918                            minLeft = mLeft + offset;
13919                            maxRight = mRight;
13920                        } else {
13921                            minLeft = mLeft;
13922                            maxRight = mRight + offset;
13923                        }
13924                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13925                        p.invalidateChild(this, r);
13926                    }
13927                }
13928            } else {
13929                invalidateViewProperty(false, false);
13930            }
13931
13932            mLeft += offset;
13933            mRight += offset;
13934            mRenderNode.offsetLeftAndRight(offset);
13935            if (isHardwareAccelerated()) {
13936                invalidateViewProperty(false, false);
13937                invalidateParentIfNeededAndWasQuickRejected();
13938            } else {
13939                if (!matrixIsIdentity) {
13940                    invalidateViewProperty(false, true);
13941                }
13942                invalidateParentIfNeeded();
13943            }
13944            notifySubtreeAccessibilityStateChangedIfNeeded();
13945        }
13946    }
13947
13948    /**
13949     * Get the LayoutParams associated with this view. All views should have
13950     * layout parameters. These supply parameters to the <i>parent</i> of this
13951     * view specifying how it should be arranged. There are many subclasses of
13952     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13953     * of ViewGroup that are responsible for arranging their children.
13954     *
13955     * This method may return null if this View is not attached to a parent
13956     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13957     * was not invoked successfully. When a View is attached to a parent
13958     * ViewGroup, this method must not return null.
13959     *
13960     * @return The LayoutParams associated with this view, or null if no
13961     *         parameters have been set yet
13962     */
13963    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13964    public ViewGroup.LayoutParams getLayoutParams() {
13965        return mLayoutParams;
13966    }
13967
13968    /**
13969     * Set the layout parameters associated with this view. These supply
13970     * parameters to the <i>parent</i> of this view specifying how it should be
13971     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13972     * correspond to the different subclasses of ViewGroup that are responsible
13973     * for arranging their children.
13974     *
13975     * @param params The layout parameters for this view, cannot be null
13976     */
13977    public void setLayoutParams(ViewGroup.LayoutParams params) {
13978        if (params == null) {
13979            throw new NullPointerException("Layout parameters cannot be null");
13980        }
13981        mLayoutParams = params;
13982        resolveLayoutParams();
13983        if (mParent instanceof ViewGroup) {
13984            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13985        }
13986        requestLayout();
13987    }
13988
13989    /**
13990     * Resolve the layout parameters depending on the resolved layout direction
13991     *
13992     * @hide
13993     */
13994    public void resolveLayoutParams() {
13995        if (mLayoutParams != null) {
13996            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13997        }
13998    }
13999
14000    /**
14001     * Set the scrolled position of your view. This will cause a call to
14002     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14003     * invalidated.
14004     * @param x the x position to scroll to
14005     * @param y the y position to scroll to
14006     */
14007    public void scrollTo(int x, int y) {
14008        if (mScrollX != x || mScrollY != y) {
14009            int oldX = mScrollX;
14010            int oldY = mScrollY;
14011            mScrollX = x;
14012            mScrollY = y;
14013            invalidateParentCaches();
14014            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
14015            if (!awakenScrollBars()) {
14016                postInvalidateOnAnimation();
14017            }
14018        }
14019    }
14020
14021    /**
14022     * Move the scrolled position of your view. This will cause a call to
14023     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14024     * invalidated.
14025     * @param x the amount of pixels to scroll by horizontally
14026     * @param y the amount of pixels to scroll by vertically
14027     */
14028    public void scrollBy(int x, int y) {
14029        scrollTo(mScrollX + x, mScrollY + y);
14030    }
14031
14032    /**
14033     * <p>Trigger the scrollbars to draw. When invoked this method starts an
14034     * animation to fade the scrollbars out after a default delay. If a subclass
14035     * provides animated scrolling, the start delay should equal the duration
14036     * of the scrolling animation.</p>
14037     *
14038     * <p>The animation starts only if at least one of the scrollbars is
14039     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
14040     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14041     * this method returns true, and false otherwise. If the animation is
14042     * started, this method calls {@link #invalidate()}; in that case the
14043     * caller should not call {@link #invalidate()}.</p>
14044     *
14045     * <p>This method should be invoked every time a subclass directly updates
14046     * the scroll parameters.</p>
14047     *
14048     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
14049     * and {@link #scrollTo(int, int)}.</p>
14050     *
14051     * @return true if the animation is played, false otherwise
14052     *
14053     * @see #awakenScrollBars(int)
14054     * @see #scrollBy(int, int)
14055     * @see #scrollTo(int, int)
14056     * @see #isHorizontalScrollBarEnabled()
14057     * @see #isVerticalScrollBarEnabled()
14058     * @see #setHorizontalScrollBarEnabled(boolean)
14059     * @see #setVerticalScrollBarEnabled(boolean)
14060     */
14061    protected boolean awakenScrollBars() {
14062        return mScrollCache != null &&
14063                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
14064    }
14065
14066    /**
14067     * Trigger the scrollbars to draw.
14068     * This method differs from awakenScrollBars() only in its default duration.
14069     * initialAwakenScrollBars() will show the scroll bars for longer than
14070     * usual to give the user more of a chance to notice them.
14071     *
14072     * @return true if the animation is played, false otherwise.
14073     */
14074    private boolean initialAwakenScrollBars() {
14075        return mScrollCache != null &&
14076                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
14077    }
14078
14079    /**
14080     * <p>
14081     * Trigger the scrollbars to draw. When invoked this method starts an
14082     * animation to fade the scrollbars out after a fixed delay. If a subclass
14083     * provides animated scrolling, the start delay should equal the duration of
14084     * the scrolling animation.
14085     * </p>
14086     *
14087     * <p>
14088     * The animation starts only if at least one of the scrollbars is enabled,
14089     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14090     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14091     * this method returns true, and false otherwise. If the animation is
14092     * started, this method calls {@link #invalidate()}; in that case the caller
14093     * should not call {@link #invalidate()}.
14094     * </p>
14095     *
14096     * <p>
14097     * This method should be invoked every time a subclass directly updates the
14098     * scroll parameters.
14099     * </p>
14100     *
14101     * @param startDelay the delay, in milliseconds, after which the animation
14102     *        should start; when the delay is 0, the animation starts
14103     *        immediately
14104     * @return true if the animation is played, false otherwise
14105     *
14106     * @see #scrollBy(int, int)
14107     * @see #scrollTo(int, int)
14108     * @see #isHorizontalScrollBarEnabled()
14109     * @see #isVerticalScrollBarEnabled()
14110     * @see #setHorizontalScrollBarEnabled(boolean)
14111     * @see #setVerticalScrollBarEnabled(boolean)
14112     */
14113    protected boolean awakenScrollBars(int startDelay) {
14114        return awakenScrollBars(startDelay, true);
14115    }
14116
14117    /**
14118     * <p>
14119     * Trigger the scrollbars to draw. When invoked this method starts an
14120     * animation to fade the scrollbars out after a fixed delay. If a subclass
14121     * provides animated scrolling, the start delay should equal the duration of
14122     * the scrolling animation.
14123     * </p>
14124     *
14125     * <p>
14126     * The animation starts only if at least one of the scrollbars is enabled,
14127     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14128     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14129     * this method returns true, and false otherwise. If the animation is
14130     * started, this method calls {@link #invalidate()} if the invalidate parameter
14131     * is set to true; in that case the caller
14132     * should not call {@link #invalidate()}.
14133     * </p>
14134     *
14135     * <p>
14136     * This method should be invoked every time a subclass directly updates the
14137     * scroll parameters.
14138     * </p>
14139     *
14140     * @param startDelay the delay, in milliseconds, after which the animation
14141     *        should start; when the delay is 0, the animation starts
14142     *        immediately
14143     *
14144     * @param invalidate Whether this method should call invalidate
14145     *
14146     * @return true if the animation is played, false otherwise
14147     *
14148     * @see #scrollBy(int, int)
14149     * @see #scrollTo(int, int)
14150     * @see #isHorizontalScrollBarEnabled()
14151     * @see #isVerticalScrollBarEnabled()
14152     * @see #setHorizontalScrollBarEnabled(boolean)
14153     * @see #setVerticalScrollBarEnabled(boolean)
14154     */
14155    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
14156        final ScrollabilityCache scrollCache = mScrollCache;
14157
14158        if (scrollCache == null || !scrollCache.fadeScrollBars) {
14159            return false;
14160        }
14161
14162        if (scrollCache.scrollBar == null) {
14163            scrollCache.scrollBar = new ScrollBarDrawable();
14164            scrollCache.scrollBar.setState(getDrawableState());
14165            scrollCache.scrollBar.setCallback(this);
14166        }
14167
14168        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
14169
14170            if (invalidate) {
14171                // Invalidate to show the scrollbars
14172                postInvalidateOnAnimation();
14173            }
14174
14175            if (scrollCache.state == ScrollabilityCache.OFF) {
14176                // FIXME: this is copied from WindowManagerService.
14177                // We should get this value from the system when it
14178                // is possible to do so.
14179                final int KEY_REPEAT_FIRST_DELAY = 750;
14180                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
14181            }
14182
14183            // Tell mScrollCache when we should start fading. This may
14184            // extend the fade start time if one was already scheduled
14185            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
14186            scrollCache.fadeStartTime = fadeStartTime;
14187            scrollCache.state = ScrollabilityCache.ON;
14188
14189            // Schedule our fader to run, unscheduling any old ones first
14190            if (mAttachInfo != null) {
14191                mAttachInfo.mHandler.removeCallbacks(scrollCache);
14192                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
14193            }
14194
14195            return true;
14196        }
14197
14198        return false;
14199    }
14200
14201    /**
14202     * Do not invalidate views which are not visible and which are not running an animation. They
14203     * will not get drawn and they should not set dirty flags as if they will be drawn
14204     */
14205    private boolean skipInvalidate() {
14206        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
14207                (!(mParent instanceof ViewGroup) ||
14208                        !((ViewGroup) mParent).isViewTransitioning(this));
14209    }
14210
14211    /**
14212     * Mark the area defined by dirty as needing to be drawn. If the view is
14213     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14214     * point in the future.
14215     * <p>
14216     * This must be called from a UI thread. To call from a non-UI thread, call
14217     * {@link #postInvalidate()}.
14218     * <p>
14219     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
14220     * {@code dirty}.
14221     *
14222     * @param dirty the rectangle representing the bounds of the dirty region
14223     */
14224    public void invalidate(Rect dirty) {
14225        final int scrollX = mScrollX;
14226        final int scrollY = mScrollY;
14227        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
14228                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
14229    }
14230
14231    /**
14232     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
14233     * coordinates of the dirty rect are relative to the view. If the view is
14234     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14235     * point in the future.
14236     * <p>
14237     * This must be called from a UI thread. To call from a non-UI thread, call
14238     * {@link #postInvalidate()}.
14239     *
14240     * @param l the left position of the dirty region
14241     * @param t the top position of the dirty region
14242     * @param r the right position of the dirty region
14243     * @param b the bottom position of the dirty region
14244     */
14245    public void invalidate(int l, int t, int r, int b) {
14246        final int scrollX = mScrollX;
14247        final int scrollY = mScrollY;
14248        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
14249    }
14250
14251    /**
14252     * Invalidate the whole view. If the view is visible,
14253     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
14254     * the future.
14255     * <p>
14256     * This must be called from a UI thread. To call from a non-UI thread, call
14257     * {@link #postInvalidate()}.
14258     */
14259    public void invalidate() {
14260        invalidate(true);
14261    }
14262
14263    /**
14264     * This is where the invalidate() work actually happens. A full invalidate()
14265     * causes the drawing cache to be invalidated, but this function can be
14266     * called with invalidateCache set to false to skip that invalidation step
14267     * for cases that do not need it (for example, a component that remains at
14268     * the same dimensions with the same content).
14269     *
14270     * @param invalidateCache Whether the drawing cache for this view should be
14271     *            invalidated as well. This is usually true for a full
14272     *            invalidate, but may be set to false if the View's contents or
14273     *            dimensions have not changed.
14274     * @hide
14275     */
14276    public void invalidate(boolean invalidateCache) {
14277        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
14278    }
14279
14280    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
14281            boolean fullInvalidate) {
14282        if (mGhostView != null) {
14283            mGhostView.invalidate(true);
14284            return;
14285        }
14286
14287        if (skipInvalidate()) {
14288            return;
14289        }
14290
14291        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
14292                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
14293                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
14294                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
14295            if (fullInvalidate) {
14296                mLastIsOpaque = isOpaque();
14297                mPrivateFlags &= ~PFLAG_DRAWN;
14298            }
14299
14300            mPrivateFlags |= PFLAG_DIRTY;
14301
14302            if (invalidateCache) {
14303                mPrivateFlags |= PFLAG_INVALIDATED;
14304                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14305            }
14306
14307            // Propagate the damage rectangle to the parent view.
14308            final AttachInfo ai = mAttachInfo;
14309            final ViewParent p = mParent;
14310            if (p != null && ai != null && l < r && t < b) {
14311                final Rect damage = ai.mTmpInvalRect;
14312                damage.set(l, t, r, b);
14313                p.invalidateChild(this, damage);
14314            }
14315
14316            // Damage the entire projection receiver, if necessary.
14317            if (mBackground != null && mBackground.isProjected()) {
14318                final View receiver = getProjectionReceiver();
14319                if (receiver != null) {
14320                    receiver.damageInParent();
14321                }
14322            }
14323        }
14324    }
14325
14326    /**
14327     * @return this view's projection receiver, or {@code null} if none exists
14328     */
14329    private View getProjectionReceiver() {
14330        ViewParent p = getParent();
14331        while (p != null && p instanceof View) {
14332            final View v = (View) p;
14333            if (v.isProjectionReceiver()) {
14334                return v;
14335            }
14336            p = p.getParent();
14337        }
14338
14339        return null;
14340    }
14341
14342    /**
14343     * @return whether the view is a projection receiver
14344     */
14345    private boolean isProjectionReceiver() {
14346        return mBackground != null;
14347    }
14348
14349    /**
14350     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
14351     * set any flags or handle all of the cases handled by the default invalidation methods.
14352     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
14353     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
14354     * walk up the hierarchy, transforming the dirty rect as necessary.
14355     *
14356     * The method also handles normal invalidation logic if display list properties are not
14357     * being used in this view. The invalidateParent and forceRedraw flags are used by that
14358     * backup approach, to handle these cases used in the various property-setting methods.
14359     *
14360     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
14361     * are not being used in this view
14362     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
14363     * list properties are not being used in this view
14364     */
14365    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
14366        if (!isHardwareAccelerated()
14367                || !mRenderNode.isValid()
14368                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
14369            if (invalidateParent) {
14370                invalidateParentCaches();
14371            }
14372            if (forceRedraw) {
14373                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14374            }
14375            invalidate(false);
14376        } else {
14377            damageInParent();
14378        }
14379    }
14380
14381    /**
14382     * Tells the parent view to damage this view's bounds.
14383     *
14384     * @hide
14385     */
14386    protected void damageInParent() {
14387        if (mParent != null && mAttachInfo != null) {
14388            mParent.onDescendantInvalidated(this, this);
14389        }
14390    }
14391
14392    /**
14393     * Utility method to transform a given Rect by the current matrix of this view.
14394     */
14395    void transformRect(final Rect rect) {
14396        if (!getMatrix().isIdentity()) {
14397            RectF boundingRect = mAttachInfo.mTmpTransformRect;
14398            boundingRect.set(rect);
14399            getMatrix().mapRect(boundingRect);
14400            rect.set((int) Math.floor(boundingRect.left),
14401                    (int) Math.floor(boundingRect.top),
14402                    (int) Math.ceil(boundingRect.right),
14403                    (int) Math.ceil(boundingRect.bottom));
14404        }
14405    }
14406
14407    /**
14408     * Used to indicate that the parent of this view should clear its caches. This functionality
14409     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14410     * which is necessary when various parent-managed properties of the view change, such as
14411     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
14412     * clears the parent caches and does not causes an invalidate event.
14413     *
14414     * @hide
14415     */
14416    protected void invalidateParentCaches() {
14417        if (mParent instanceof View) {
14418            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
14419        }
14420    }
14421
14422    /**
14423     * Used to indicate that the parent of this view should be invalidated. This functionality
14424     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14425     * which is necessary when various parent-managed properties of the view change, such as
14426     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
14427     * an invalidation event to the parent.
14428     *
14429     * @hide
14430     */
14431    protected void invalidateParentIfNeeded() {
14432        if (isHardwareAccelerated() && mParent instanceof View) {
14433            ((View) mParent).invalidate(true);
14434        }
14435    }
14436
14437    /**
14438     * @hide
14439     */
14440    protected void invalidateParentIfNeededAndWasQuickRejected() {
14441        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
14442            // View was rejected last time it was drawn by its parent; this may have changed
14443            invalidateParentIfNeeded();
14444        }
14445    }
14446
14447    /**
14448     * Indicates whether this View is opaque. An opaque View guarantees that it will
14449     * draw all the pixels overlapping its bounds using a fully opaque color.
14450     *
14451     * Subclasses of View should override this method whenever possible to indicate
14452     * whether an instance is opaque. Opaque Views are treated in a special way by
14453     * the View hierarchy, possibly allowing it to perform optimizations during
14454     * invalidate/draw passes.
14455     *
14456     * @return True if this View is guaranteed to be fully opaque, false otherwise.
14457     */
14458    @ViewDebug.ExportedProperty(category = "drawing")
14459    public boolean isOpaque() {
14460        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
14461                getFinalAlpha() >= 1.0f;
14462    }
14463
14464    /**
14465     * @hide
14466     */
14467    protected void computeOpaqueFlags() {
14468        // Opaque if:
14469        //   - Has a background
14470        //   - Background is opaque
14471        //   - Doesn't have scrollbars or scrollbars overlay
14472
14473        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
14474            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
14475        } else {
14476            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
14477        }
14478
14479        final int flags = mViewFlags;
14480        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
14481                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
14482                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
14483            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
14484        } else {
14485            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
14486        }
14487    }
14488
14489    /**
14490     * @hide
14491     */
14492    protected boolean hasOpaqueScrollbars() {
14493        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
14494    }
14495
14496    /**
14497     * @return A handler associated with the thread running the View. This
14498     * handler can be used to pump events in the UI events queue.
14499     */
14500    public Handler getHandler() {
14501        final AttachInfo attachInfo = mAttachInfo;
14502        if (attachInfo != null) {
14503            return attachInfo.mHandler;
14504        }
14505        return null;
14506    }
14507
14508    /**
14509     * Returns the queue of runnable for this view.
14510     *
14511     * @return the queue of runnables for this view
14512     */
14513    private HandlerActionQueue getRunQueue() {
14514        if (mRunQueue == null) {
14515            mRunQueue = new HandlerActionQueue();
14516        }
14517        return mRunQueue;
14518    }
14519
14520    /**
14521     * Gets the view root associated with the View.
14522     * @return The view root, or null if none.
14523     * @hide
14524     */
14525    public ViewRootImpl getViewRootImpl() {
14526        if (mAttachInfo != null) {
14527            return mAttachInfo.mViewRootImpl;
14528        }
14529        return null;
14530    }
14531
14532    /**
14533     * @hide
14534     */
14535    public ThreadedRenderer getThreadedRenderer() {
14536        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
14537    }
14538
14539    /**
14540     * <p>Causes the Runnable to be added to the message queue.
14541     * The runnable will be run on the user interface thread.</p>
14542     *
14543     * @param action The Runnable that will be executed.
14544     *
14545     * @return Returns true if the Runnable was successfully placed in to the
14546     *         message queue.  Returns false on failure, usually because the
14547     *         looper processing the message queue is exiting.
14548     *
14549     * @see #postDelayed
14550     * @see #removeCallbacks
14551     */
14552    public boolean post(Runnable action) {
14553        final AttachInfo attachInfo = mAttachInfo;
14554        if (attachInfo != null) {
14555            return attachInfo.mHandler.post(action);
14556        }
14557
14558        // Postpone the runnable until we know on which thread it needs to run.
14559        // Assume that the runnable will be successfully placed after attach.
14560        getRunQueue().post(action);
14561        return true;
14562    }
14563
14564    /**
14565     * <p>Causes the Runnable to be added to the message queue, to be run
14566     * after the specified amount of time elapses.
14567     * The runnable will be run on the user interface thread.</p>
14568     *
14569     * @param action The Runnable that will be executed.
14570     * @param delayMillis The delay (in milliseconds) until the Runnable
14571     *        will be executed.
14572     *
14573     * @return true if the Runnable was successfully placed in to the
14574     *         message queue.  Returns false on failure, usually because the
14575     *         looper processing the message queue is exiting.  Note that a
14576     *         result of true does not mean the Runnable will be processed --
14577     *         if the looper is quit before the delivery time of the message
14578     *         occurs then the message will be dropped.
14579     *
14580     * @see #post
14581     * @see #removeCallbacks
14582     */
14583    public boolean postDelayed(Runnable action, long delayMillis) {
14584        final AttachInfo attachInfo = mAttachInfo;
14585        if (attachInfo != null) {
14586            return attachInfo.mHandler.postDelayed(action, delayMillis);
14587        }
14588
14589        // Postpone the runnable until we know on which thread it needs to run.
14590        // Assume that the runnable will be successfully placed after attach.
14591        getRunQueue().postDelayed(action, delayMillis);
14592        return true;
14593    }
14594
14595    /**
14596     * <p>Causes the Runnable to execute on the next animation time step.
14597     * The runnable will be run on the user interface thread.</p>
14598     *
14599     * @param action The Runnable that will be executed.
14600     *
14601     * @see #postOnAnimationDelayed
14602     * @see #removeCallbacks
14603     */
14604    public void postOnAnimation(Runnable action) {
14605        final AttachInfo attachInfo = mAttachInfo;
14606        if (attachInfo != null) {
14607            attachInfo.mViewRootImpl.mChoreographer.postCallback(
14608                    Choreographer.CALLBACK_ANIMATION, action, null);
14609        } else {
14610            // Postpone the runnable until we know
14611            // on which thread it needs to run.
14612            getRunQueue().post(action);
14613        }
14614    }
14615
14616    /**
14617     * <p>Causes the Runnable to execute on the next animation time step,
14618     * after the specified amount of time elapses.
14619     * The runnable will be run on the user interface thread.</p>
14620     *
14621     * @param action The Runnable that will be executed.
14622     * @param delayMillis The delay (in milliseconds) until the Runnable
14623     *        will be executed.
14624     *
14625     * @see #postOnAnimation
14626     * @see #removeCallbacks
14627     */
14628    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14629        final AttachInfo attachInfo = mAttachInfo;
14630        if (attachInfo != null) {
14631            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14632                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14633        } else {
14634            // Postpone the runnable until we know
14635            // on which thread it needs to run.
14636            getRunQueue().postDelayed(action, delayMillis);
14637        }
14638    }
14639
14640    /**
14641     * <p>Removes the specified Runnable from the message queue.</p>
14642     *
14643     * @param action The Runnable to remove from the message handling queue
14644     *
14645     * @return true if this view could ask the Handler to remove the Runnable,
14646     *         false otherwise. When the returned value is true, the Runnable
14647     *         may or may not have been actually removed from the message queue
14648     *         (for instance, if the Runnable was not in the queue already.)
14649     *
14650     * @see #post
14651     * @see #postDelayed
14652     * @see #postOnAnimation
14653     * @see #postOnAnimationDelayed
14654     */
14655    public boolean removeCallbacks(Runnable action) {
14656        if (action != null) {
14657            final AttachInfo attachInfo = mAttachInfo;
14658            if (attachInfo != null) {
14659                attachInfo.mHandler.removeCallbacks(action);
14660                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14661                        Choreographer.CALLBACK_ANIMATION, action, null);
14662            }
14663            getRunQueue().removeCallbacks(action);
14664        }
14665        return true;
14666    }
14667
14668    /**
14669     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14670     * Use this to invalidate the View from a non-UI thread.</p>
14671     *
14672     * <p>This method can be invoked from outside of the UI thread
14673     * only when this View is attached to a window.</p>
14674     *
14675     * @see #invalidate()
14676     * @see #postInvalidateDelayed(long)
14677     */
14678    public void postInvalidate() {
14679        postInvalidateDelayed(0);
14680    }
14681
14682    /**
14683     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14684     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14685     *
14686     * <p>This method can be invoked from outside of the UI thread
14687     * only when this View is attached to a window.</p>
14688     *
14689     * @param left The left coordinate of the rectangle to invalidate.
14690     * @param top The top coordinate of the rectangle to invalidate.
14691     * @param right The right coordinate of the rectangle to invalidate.
14692     * @param bottom The bottom coordinate of the rectangle to invalidate.
14693     *
14694     * @see #invalidate(int, int, int, int)
14695     * @see #invalidate(Rect)
14696     * @see #postInvalidateDelayed(long, int, int, int, int)
14697     */
14698    public void postInvalidate(int left, int top, int right, int bottom) {
14699        postInvalidateDelayed(0, left, top, right, bottom);
14700    }
14701
14702    /**
14703     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14704     * loop. Waits for the specified amount of time.</p>
14705     *
14706     * <p>This method can be invoked from outside of the UI thread
14707     * only when this View is attached to a window.</p>
14708     *
14709     * @param delayMilliseconds the duration in milliseconds to delay the
14710     *         invalidation by
14711     *
14712     * @see #invalidate()
14713     * @see #postInvalidate()
14714     */
14715    public void postInvalidateDelayed(long delayMilliseconds) {
14716        // We try only with the AttachInfo because there's no point in invalidating
14717        // if we are not attached to our window
14718        final AttachInfo attachInfo = mAttachInfo;
14719        if (attachInfo != null) {
14720            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14721        }
14722    }
14723
14724    /**
14725     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14726     * through the event loop. Waits for the specified amount of time.</p>
14727     *
14728     * <p>This method can be invoked from outside of the UI thread
14729     * only when this View is attached to a window.</p>
14730     *
14731     * @param delayMilliseconds the duration in milliseconds to delay the
14732     *         invalidation by
14733     * @param left The left coordinate of the rectangle to invalidate.
14734     * @param top The top coordinate of the rectangle to invalidate.
14735     * @param right The right coordinate of the rectangle to invalidate.
14736     * @param bottom The bottom coordinate of the rectangle to invalidate.
14737     *
14738     * @see #invalidate(int, int, int, int)
14739     * @see #invalidate(Rect)
14740     * @see #postInvalidate(int, int, int, int)
14741     */
14742    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14743            int right, int bottom) {
14744
14745        // We try only with the AttachInfo because there's no point in invalidating
14746        // if we are not attached to our window
14747        final AttachInfo attachInfo = mAttachInfo;
14748        if (attachInfo != null) {
14749            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14750            info.target = this;
14751            info.left = left;
14752            info.top = top;
14753            info.right = right;
14754            info.bottom = bottom;
14755
14756            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14757        }
14758    }
14759
14760    /**
14761     * <p>Cause an invalidate to happen on the next animation time step, typically the
14762     * next display frame.</p>
14763     *
14764     * <p>This method can be invoked from outside of the UI thread
14765     * only when this View is attached to a window.</p>
14766     *
14767     * @see #invalidate()
14768     */
14769    public void postInvalidateOnAnimation() {
14770        // We try only with the AttachInfo because there's no point in invalidating
14771        // if we are not attached to our window
14772        final AttachInfo attachInfo = mAttachInfo;
14773        if (attachInfo != null) {
14774            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14775        }
14776    }
14777
14778    /**
14779     * <p>Cause an invalidate of the specified area to happen on the next animation
14780     * time step, typically the next display frame.</p>
14781     *
14782     * <p>This method can be invoked from outside of the UI thread
14783     * only when this View is attached to a window.</p>
14784     *
14785     * @param left The left coordinate of the rectangle to invalidate.
14786     * @param top The top coordinate of the rectangle to invalidate.
14787     * @param right The right coordinate of the rectangle to invalidate.
14788     * @param bottom The bottom coordinate of the rectangle to invalidate.
14789     *
14790     * @see #invalidate(int, int, int, int)
14791     * @see #invalidate(Rect)
14792     */
14793    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14794        // We try only with the AttachInfo because there's no point in invalidating
14795        // if we are not attached to our window
14796        final AttachInfo attachInfo = mAttachInfo;
14797        if (attachInfo != null) {
14798            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14799            info.target = this;
14800            info.left = left;
14801            info.top = top;
14802            info.right = right;
14803            info.bottom = bottom;
14804
14805            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14806        }
14807    }
14808
14809    /**
14810     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14811     * This event is sent at most once every
14812     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14813     */
14814    private void postSendViewScrolledAccessibilityEventCallback() {
14815        if (mSendViewScrolledAccessibilityEvent == null) {
14816            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14817        }
14818        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14819            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14820            postDelayed(mSendViewScrolledAccessibilityEvent,
14821                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14822        }
14823    }
14824
14825    /**
14826     * Called by a parent to request that a child update its values for mScrollX
14827     * and mScrollY if necessary. This will typically be done if the child is
14828     * animating a scroll using a {@link android.widget.Scroller Scroller}
14829     * object.
14830     */
14831    public void computeScroll() {
14832    }
14833
14834    /**
14835     * <p>Indicate whether the horizontal edges are faded when the view is
14836     * scrolled horizontally.</p>
14837     *
14838     * @return true if the horizontal edges should are faded on scroll, false
14839     *         otherwise
14840     *
14841     * @see #setHorizontalFadingEdgeEnabled(boolean)
14842     *
14843     * @attr ref android.R.styleable#View_requiresFadingEdge
14844     */
14845    public boolean isHorizontalFadingEdgeEnabled() {
14846        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14847    }
14848
14849    /**
14850     * <p>Define whether the horizontal edges should be faded when this view
14851     * is scrolled horizontally.</p>
14852     *
14853     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14854     *                                    be faded when the view is scrolled
14855     *                                    horizontally
14856     *
14857     * @see #isHorizontalFadingEdgeEnabled()
14858     *
14859     * @attr ref android.R.styleable#View_requiresFadingEdge
14860     */
14861    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14862        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14863            if (horizontalFadingEdgeEnabled) {
14864                initScrollCache();
14865            }
14866
14867            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14868        }
14869    }
14870
14871    /**
14872     * <p>Indicate whether the vertical edges are faded when the view is
14873     * scrolled horizontally.</p>
14874     *
14875     * @return true if the vertical edges should are faded on scroll, false
14876     *         otherwise
14877     *
14878     * @see #setVerticalFadingEdgeEnabled(boolean)
14879     *
14880     * @attr ref android.R.styleable#View_requiresFadingEdge
14881     */
14882    public boolean isVerticalFadingEdgeEnabled() {
14883        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14884    }
14885
14886    /**
14887     * <p>Define whether the vertical edges should be faded when this view
14888     * is scrolled vertically.</p>
14889     *
14890     * @param verticalFadingEdgeEnabled true if the vertical edges should
14891     *                                  be faded when the view is scrolled
14892     *                                  vertically
14893     *
14894     * @see #isVerticalFadingEdgeEnabled()
14895     *
14896     * @attr ref android.R.styleable#View_requiresFadingEdge
14897     */
14898    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14899        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14900            if (verticalFadingEdgeEnabled) {
14901                initScrollCache();
14902            }
14903
14904            mViewFlags ^= FADING_EDGE_VERTICAL;
14905        }
14906    }
14907
14908    /**
14909     * Returns the strength, or intensity, of the top faded edge. The strength is
14910     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14911     * returns 0.0 or 1.0 but no value in between.
14912     *
14913     * Subclasses should override this method to provide a smoother fade transition
14914     * when scrolling occurs.
14915     *
14916     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14917     */
14918    protected float getTopFadingEdgeStrength() {
14919        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14920    }
14921
14922    /**
14923     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14924     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14925     * returns 0.0 or 1.0 but no value in between.
14926     *
14927     * Subclasses should override this method to provide a smoother fade transition
14928     * when scrolling occurs.
14929     *
14930     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14931     */
14932    protected float getBottomFadingEdgeStrength() {
14933        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14934                computeVerticalScrollRange() ? 1.0f : 0.0f;
14935    }
14936
14937    /**
14938     * Returns the strength, or intensity, of the left faded edge. The strength is
14939     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14940     * returns 0.0 or 1.0 but no value in between.
14941     *
14942     * Subclasses should override this method to provide a smoother fade transition
14943     * when scrolling occurs.
14944     *
14945     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14946     */
14947    protected float getLeftFadingEdgeStrength() {
14948        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14949    }
14950
14951    /**
14952     * Returns the strength, or intensity, of the right faded edge. The strength is
14953     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14954     * returns 0.0 or 1.0 but no value in between.
14955     *
14956     * Subclasses should override this method to provide a smoother fade transition
14957     * when scrolling occurs.
14958     *
14959     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14960     */
14961    protected float getRightFadingEdgeStrength() {
14962        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14963                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14964    }
14965
14966    /**
14967     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14968     * scrollbar is not drawn by default.</p>
14969     *
14970     * @return true if the horizontal scrollbar should be painted, false
14971     *         otherwise
14972     *
14973     * @see #setHorizontalScrollBarEnabled(boolean)
14974     */
14975    public boolean isHorizontalScrollBarEnabled() {
14976        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14977    }
14978
14979    /**
14980     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14981     * scrollbar is not drawn by default.</p>
14982     *
14983     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14984     *                                   be painted
14985     *
14986     * @see #isHorizontalScrollBarEnabled()
14987     */
14988    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14989        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14990            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14991            computeOpaqueFlags();
14992            resolvePadding();
14993        }
14994    }
14995
14996    /**
14997     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14998     * scrollbar is not drawn by default.</p>
14999     *
15000     * @return true if the vertical scrollbar should be painted, false
15001     *         otherwise
15002     *
15003     * @see #setVerticalScrollBarEnabled(boolean)
15004     */
15005    public boolean isVerticalScrollBarEnabled() {
15006        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
15007    }
15008
15009    /**
15010     * <p>Define whether the vertical scrollbar should be drawn or not. The
15011     * scrollbar is not drawn by default.</p>
15012     *
15013     * @param verticalScrollBarEnabled true if the vertical scrollbar should
15014     *                                 be painted
15015     *
15016     * @see #isVerticalScrollBarEnabled()
15017     */
15018    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
15019        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
15020            mViewFlags ^= SCROLLBARS_VERTICAL;
15021            computeOpaqueFlags();
15022            resolvePadding();
15023        }
15024    }
15025
15026    /**
15027     * @hide
15028     */
15029    protected void recomputePadding() {
15030        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15031    }
15032
15033    /**
15034     * Define whether scrollbars will fade when the view is not scrolling.
15035     *
15036     * @param fadeScrollbars whether to enable fading
15037     *
15038     * @attr ref android.R.styleable#View_fadeScrollbars
15039     */
15040    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
15041        initScrollCache();
15042        final ScrollabilityCache scrollabilityCache = mScrollCache;
15043        scrollabilityCache.fadeScrollBars = fadeScrollbars;
15044        if (fadeScrollbars) {
15045            scrollabilityCache.state = ScrollabilityCache.OFF;
15046        } else {
15047            scrollabilityCache.state = ScrollabilityCache.ON;
15048        }
15049    }
15050
15051    /**
15052     *
15053     * Returns true if scrollbars will fade when this view is not scrolling
15054     *
15055     * @return true if scrollbar fading is enabled
15056     *
15057     * @attr ref android.R.styleable#View_fadeScrollbars
15058     */
15059    public boolean isScrollbarFadingEnabled() {
15060        return mScrollCache != null && mScrollCache.fadeScrollBars;
15061    }
15062
15063    /**
15064     *
15065     * Returns the delay before scrollbars fade.
15066     *
15067     * @return the delay before scrollbars fade
15068     *
15069     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15070     */
15071    public int getScrollBarDefaultDelayBeforeFade() {
15072        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
15073                mScrollCache.scrollBarDefaultDelayBeforeFade;
15074    }
15075
15076    /**
15077     * Define the delay before scrollbars fade.
15078     *
15079     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
15080     *
15081     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15082     */
15083    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
15084        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
15085    }
15086
15087    /**
15088     *
15089     * Returns the scrollbar fade duration.
15090     *
15091     * @return the scrollbar fade duration, in milliseconds
15092     *
15093     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15094     */
15095    public int getScrollBarFadeDuration() {
15096        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
15097                mScrollCache.scrollBarFadeDuration;
15098    }
15099
15100    /**
15101     * Define the scrollbar fade duration.
15102     *
15103     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
15104     *
15105     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15106     */
15107    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
15108        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
15109    }
15110
15111    /**
15112     *
15113     * Returns the scrollbar size.
15114     *
15115     * @return the scrollbar size
15116     *
15117     * @attr ref android.R.styleable#View_scrollbarSize
15118     */
15119    public int getScrollBarSize() {
15120        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
15121                mScrollCache.scrollBarSize;
15122    }
15123
15124    /**
15125     * Define the scrollbar size.
15126     *
15127     * @param scrollBarSize - the scrollbar size
15128     *
15129     * @attr ref android.R.styleable#View_scrollbarSize
15130     */
15131    public void setScrollBarSize(int scrollBarSize) {
15132        getScrollCache().scrollBarSize = scrollBarSize;
15133    }
15134
15135    /**
15136     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
15137     * inset. When inset, they add to the padding of the view. And the scrollbars
15138     * can be drawn inside the padding area or on the edge of the view. For example,
15139     * if a view has a background drawable and you want to draw the scrollbars
15140     * inside the padding specified by the drawable, you can use
15141     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
15142     * appear at the edge of the view, ignoring the padding, then you can use
15143     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
15144     * @param style the style of the scrollbars. Should be one of
15145     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
15146     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
15147     * @see #SCROLLBARS_INSIDE_OVERLAY
15148     * @see #SCROLLBARS_INSIDE_INSET
15149     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15150     * @see #SCROLLBARS_OUTSIDE_INSET
15151     *
15152     * @attr ref android.R.styleable#View_scrollbarStyle
15153     */
15154    public void setScrollBarStyle(@ScrollBarStyle int style) {
15155        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
15156            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
15157            computeOpaqueFlags();
15158            resolvePadding();
15159        }
15160    }
15161
15162    /**
15163     * <p>Returns the current scrollbar style.</p>
15164     * @return the current scrollbar style
15165     * @see #SCROLLBARS_INSIDE_OVERLAY
15166     * @see #SCROLLBARS_INSIDE_INSET
15167     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15168     * @see #SCROLLBARS_OUTSIDE_INSET
15169     *
15170     * @attr ref android.R.styleable#View_scrollbarStyle
15171     */
15172    @ViewDebug.ExportedProperty(mapping = {
15173            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
15174            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
15175            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
15176            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
15177    })
15178    @ScrollBarStyle
15179    public int getScrollBarStyle() {
15180        return mViewFlags & SCROLLBARS_STYLE_MASK;
15181    }
15182
15183    /**
15184     * <p>Compute the horizontal range that the horizontal scrollbar
15185     * represents.</p>
15186     *
15187     * <p>The range is expressed in arbitrary units that must be the same as the
15188     * units used by {@link #computeHorizontalScrollExtent()} and
15189     * {@link #computeHorizontalScrollOffset()}.</p>
15190     *
15191     * <p>The default range is the drawing width of this view.</p>
15192     *
15193     * @return the total horizontal range represented by the horizontal
15194     *         scrollbar
15195     *
15196     * @see #computeHorizontalScrollExtent()
15197     * @see #computeHorizontalScrollOffset()
15198     * @see android.widget.ScrollBarDrawable
15199     */
15200    protected int computeHorizontalScrollRange() {
15201        return getWidth();
15202    }
15203
15204    /**
15205     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
15206     * within the horizontal range. This value is used to compute the position
15207     * of the thumb within the scrollbar's track.</p>
15208     *
15209     * <p>The range is expressed in arbitrary units that must be the same as the
15210     * units used by {@link #computeHorizontalScrollRange()} and
15211     * {@link #computeHorizontalScrollExtent()}.</p>
15212     *
15213     * <p>The default offset is the scroll offset of this view.</p>
15214     *
15215     * @return the horizontal offset of the scrollbar's thumb
15216     *
15217     * @see #computeHorizontalScrollRange()
15218     * @see #computeHorizontalScrollExtent()
15219     * @see android.widget.ScrollBarDrawable
15220     */
15221    protected int computeHorizontalScrollOffset() {
15222        return mScrollX;
15223    }
15224
15225    /**
15226     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
15227     * within the horizontal range. This value is used to compute the length
15228     * of the thumb within the scrollbar's track.</p>
15229     *
15230     * <p>The range is expressed in arbitrary units that must be the same as the
15231     * units used by {@link #computeHorizontalScrollRange()} and
15232     * {@link #computeHorizontalScrollOffset()}.</p>
15233     *
15234     * <p>The default extent is the drawing width of this view.</p>
15235     *
15236     * @return the horizontal extent of the scrollbar's thumb
15237     *
15238     * @see #computeHorizontalScrollRange()
15239     * @see #computeHorizontalScrollOffset()
15240     * @see android.widget.ScrollBarDrawable
15241     */
15242    protected int computeHorizontalScrollExtent() {
15243        return getWidth();
15244    }
15245
15246    /**
15247     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
15248     *
15249     * <p>The range is expressed in arbitrary units that must be the same as the
15250     * units used by {@link #computeVerticalScrollExtent()} and
15251     * {@link #computeVerticalScrollOffset()}.</p>
15252     *
15253     * @return the total vertical range represented by the vertical scrollbar
15254     *
15255     * <p>The default range is the drawing height of this view.</p>
15256     *
15257     * @see #computeVerticalScrollExtent()
15258     * @see #computeVerticalScrollOffset()
15259     * @see android.widget.ScrollBarDrawable
15260     */
15261    protected int computeVerticalScrollRange() {
15262        return getHeight();
15263    }
15264
15265    /**
15266     * <p>Compute the vertical offset of the vertical scrollbar's thumb
15267     * within the horizontal range. This value is used to compute the position
15268     * of the thumb within the scrollbar's track.</p>
15269     *
15270     * <p>The range is expressed in arbitrary units that must be the same as the
15271     * units used by {@link #computeVerticalScrollRange()} and
15272     * {@link #computeVerticalScrollExtent()}.</p>
15273     *
15274     * <p>The default offset is the scroll offset of this view.</p>
15275     *
15276     * @return the vertical offset of the scrollbar's thumb
15277     *
15278     * @see #computeVerticalScrollRange()
15279     * @see #computeVerticalScrollExtent()
15280     * @see android.widget.ScrollBarDrawable
15281     */
15282    protected int computeVerticalScrollOffset() {
15283        return mScrollY;
15284    }
15285
15286    /**
15287     * <p>Compute the vertical extent of the vertical scrollbar's thumb
15288     * within the vertical range. This value is used to compute the length
15289     * of the thumb within the scrollbar's track.</p>
15290     *
15291     * <p>The range is expressed in arbitrary units that must be the same as the
15292     * units used by {@link #computeVerticalScrollRange()} and
15293     * {@link #computeVerticalScrollOffset()}.</p>
15294     *
15295     * <p>The default extent is the drawing height of this view.</p>
15296     *
15297     * @return the vertical extent of the scrollbar's thumb
15298     *
15299     * @see #computeVerticalScrollRange()
15300     * @see #computeVerticalScrollOffset()
15301     * @see android.widget.ScrollBarDrawable
15302     */
15303    protected int computeVerticalScrollExtent() {
15304        return getHeight();
15305    }
15306
15307    /**
15308     * Check if this view can be scrolled horizontally in a certain direction.
15309     *
15310     * @param direction Negative to check scrolling left, positive to check scrolling right.
15311     * @return true if this view can be scrolled in the specified direction, false otherwise.
15312     */
15313    public boolean canScrollHorizontally(int direction) {
15314        final int offset = computeHorizontalScrollOffset();
15315        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
15316        if (range == 0) return false;
15317        if (direction < 0) {
15318            return offset > 0;
15319        } else {
15320            return offset < range - 1;
15321        }
15322    }
15323
15324    /**
15325     * Check if this view can be scrolled vertically in a certain direction.
15326     *
15327     * @param direction Negative to check scrolling up, positive to check scrolling down.
15328     * @return true if this view can be scrolled in the specified direction, false otherwise.
15329     */
15330    public boolean canScrollVertically(int direction) {
15331        final int offset = computeVerticalScrollOffset();
15332        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
15333        if (range == 0) return false;
15334        if (direction < 0) {
15335            return offset > 0;
15336        } else {
15337            return offset < range - 1;
15338        }
15339    }
15340
15341    void getScrollIndicatorBounds(@NonNull Rect out) {
15342        out.left = mScrollX;
15343        out.right = mScrollX + mRight - mLeft;
15344        out.top = mScrollY;
15345        out.bottom = mScrollY + mBottom - mTop;
15346    }
15347
15348    private void onDrawScrollIndicators(Canvas c) {
15349        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
15350            // No scroll indicators enabled.
15351            return;
15352        }
15353
15354        final Drawable dr = mScrollIndicatorDrawable;
15355        if (dr == null) {
15356            // Scroll indicators aren't supported here.
15357            return;
15358        }
15359
15360        final int h = dr.getIntrinsicHeight();
15361        final int w = dr.getIntrinsicWidth();
15362        final Rect rect = mAttachInfo.mTmpInvalRect;
15363        getScrollIndicatorBounds(rect);
15364
15365        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
15366            final boolean canScrollUp = canScrollVertically(-1);
15367            if (canScrollUp) {
15368                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
15369                dr.draw(c);
15370            }
15371        }
15372
15373        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
15374            final boolean canScrollDown = canScrollVertically(1);
15375            if (canScrollDown) {
15376                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
15377                dr.draw(c);
15378            }
15379        }
15380
15381        final int leftRtl;
15382        final int rightRtl;
15383        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15384            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
15385            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
15386        } else {
15387            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
15388            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
15389        }
15390
15391        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
15392        if ((mPrivateFlags3 & leftMask) != 0) {
15393            final boolean canScrollLeft = canScrollHorizontally(-1);
15394            if (canScrollLeft) {
15395                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
15396                dr.draw(c);
15397            }
15398        }
15399
15400        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
15401        if ((mPrivateFlags3 & rightMask) != 0) {
15402            final boolean canScrollRight = canScrollHorizontally(1);
15403            if (canScrollRight) {
15404                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
15405                dr.draw(c);
15406            }
15407        }
15408    }
15409
15410    private void getHorizontalScrollBarBounds(Rect bounds) {
15411        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15412        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15413                && !isVerticalScrollBarHidden();
15414        final int size = getHorizontalScrollbarHeight();
15415        final int verticalScrollBarGap = drawVerticalScrollBar ?
15416                getVerticalScrollbarWidth() : 0;
15417        final int width = mRight - mLeft;
15418        final int height = mBottom - mTop;
15419        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
15420        bounds.left = mScrollX + (mPaddingLeft & inside);
15421        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
15422        bounds.bottom = bounds.top + size;
15423    }
15424
15425    private void getVerticalScrollBarBounds(Rect bounds) {
15426        if (mRoundScrollbarRenderer == null) {
15427            getStraightVerticalScrollBarBounds(bounds);
15428        } else {
15429            getRoundVerticalScrollBarBounds(bounds);
15430        }
15431    }
15432
15433    private void getRoundVerticalScrollBarBounds(Rect bounds) {
15434        final int width = mRight - mLeft;
15435        final int height = mBottom - mTop;
15436        // Do not take padding into account as we always want the scrollbars
15437        // to hug the screen for round wearable devices.
15438        bounds.left = mScrollX;
15439        bounds.top = mScrollY;
15440        bounds.right = bounds.left + width;
15441        bounds.bottom = mScrollY + height;
15442    }
15443
15444    private void getStraightVerticalScrollBarBounds(Rect bounds) {
15445        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15446        final int size = getVerticalScrollbarWidth();
15447        int verticalScrollbarPosition = mVerticalScrollbarPosition;
15448        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
15449            verticalScrollbarPosition = isLayoutRtl() ?
15450                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
15451        }
15452        final int width = mRight - mLeft;
15453        final int height = mBottom - mTop;
15454        switch (verticalScrollbarPosition) {
15455            default:
15456            case SCROLLBAR_POSITION_RIGHT:
15457                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
15458                break;
15459            case SCROLLBAR_POSITION_LEFT:
15460                bounds.left = mScrollX + (mUserPaddingLeft & inside);
15461                break;
15462        }
15463        bounds.top = mScrollY + (mPaddingTop & inside);
15464        bounds.right = bounds.left + size;
15465        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
15466    }
15467
15468    /**
15469     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
15470     * scrollbars are painted only if they have been awakened first.</p>
15471     *
15472     * @param canvas the canvas on which to draw the scrollbars
15473     *
15474     * @see #awakenScrollBars(int)
15475     */
15476    protected final void onDrawScrollBars(Canvas canvas) {
15477        // scrollbars are drawn only when the animation is running
15478        final ScrollabilityCache cache = mScrollCache;
15479
15480        if (cache != null) {
15481
15482            int state = cache.state;
15483
15484            if (state == ScrollabilityCache.OFF) {
15485                return;
15486            }
15487
15488            boolean invalidate = false;
15489
15490            if (state == ScrollabilityCache.FADING) {
15491                // We're fading -- get our fade interpolation
15492                if (cache.interpolatorValues == null) {
15493                    cache.interpolatorValues = new float[1];
15494                }
15495
15496                float[] values = cache.interpolatorValues;
15497
15498                // Stops the animation if we're done
15499                if (cache.scrollBarInterpolator.timeToValues(values) ==
15500                        Interpolator.Result.FREEZE_END) {
15501                    cache.state = ScrollabilityCache.OFF;
15502                } else {
15503                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
15504                }
15505
15506                // This will make the scroll bars inval themselves after
15507                // drawing. We only want this when we're fading so that
15508                // we prevent excessive redraws
15509                invalidate = true;
15510            } else {
15511                // We're just on -- but we may have been fading before so
15512                // reset alpha
15513                cache.scrollBar.mutate().setAlpha(255);
15514            }
15515
15516            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
15517            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15518                    && !isVerticalScrollBarHidden();
15519
15520            // Fork out the scroll bar drawing for round wearable devices.
15521            if (mRoundScrollbarRenderer != null) {
15522                if (drawVerticalScrollBar) {
15523                    final Rect bounds = cache.mScrollBarBounds;
15524                    getVerticalScrollBarBounds(bounds);
15525                    mRoundScrollbarRenderer.drawRoundScrollbars(
15526                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
15527                    if (invalidate) {
15528                        invalidate();
15529                    }
15530                }
15531                // Do not draw horizontal scroll bars for round wearable devices.
15532            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
15533                final ScrollBarDrawable scrollBar = cache.scrollBar;
15534
15535                if (drawHorizontalScrollBar) {
15536                    scrollBar.setParameters(computeHorizontalScrollRange(),
15537                            computeHorizontalScrollOffset(),
15538                            computeHorizontalScrollExtent(), false);
15539                    final Rect bounds = cache.mScrollBarBounds;
15540                    getHorizontalScrollBarBounds(bounds);
15541                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15542                            bounds.right, bounds.bottom);
15543                    if (invalidate) {
15544                        invalidate(bounds);
15545                    }
15546                }
15547
15548                if (drawVerticalScrollBar) {
15549                    scrollBar.setParameters(computeVerticalScrollRange(),
15550                            computeVerticalScrollOffset(),
15551                            computeVerticalScrollExtent(), true);
15552                    final Rect bounds = cache.mScrollBarBounds;
15553                    getVerticalScrollBarBounds(bounds);
15554                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15555                            bounds.right, bounds.bottom);
15556                    if (invalidate) {
15557                        invalidate(bounds);
15558                    }
15559                }
15560            }
15561        }
15562    }
15563
15564    /**
15565     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
15566     * FastScroller is visible.
15567     * @return whether to temporarily hide the vertical scrollbar
15568     * @hide
15569     */
15570    protected boolean isVerticalScrollBarHidden() {
15571        return false;
15572    }
15573
15574    /**
15575     * <p>Draw the horizontal scrollbar if
15576     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
15577     *
15578     * @param canvas the canvas on which to draw the scrollbar
15579     * @param scrollBar the scrollbar's drawable
15580     *
15581     * @see #isHorizontalScrollBarEnabled()
15582     * @see #computeHorizontalScrollRange()
15583     * @see #computeHorizontalScrollExtent()
15584     * @see #computeHorizontalScrollOffset()
15585     * @see android.widget.ScrollBarDrawable
15586     * @hide
15587     */
15588    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
15589            int l, int t, int r, int b) {
15590        scrollBar.setBounds(l, t, r, b);
15591        scrollBar.draw(canvas);
15592    }
15593
15594    /**
15595     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
15596     * returns true.</p>
15597     *
15598     * @param canvas the canvas on which to draw the scrollbar
15599     * @param scrollBar the scrollbar's drawable
15600     *
15601     * @see #isVerticalScrollBarEnabled()
15602     * @see #computeVerticalScrollRange()
15603     * @see #computeVerticalScrollExtent()
15604     * @see #computeVerticalScrollOffset()
15605     * @see android.widget.ScrollBarDrawable
15606     * @hide
15607     */
15608    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
15609            int l, int t, int r, int b) {
15610        scrollBar.setBounds(l, t, r, b);
15611        scrollBar.draw(canvas);
15612    }
15613
15614    /**
15615     * Implement this to do your drawing.
15616     *
15617     * @param canvas the canvas on which the background will be drawn
15618     */
15619    protected void onDraw(Canvas canvas) {
15620    }
15621
15622    /*
15623     * Caller is responsible for calling requestLayout if necessary.
15624     * (This allows addViewInLayout to not request a new layout.)
15625     */
15626    void assignParent(ViewParent parent) {
15627        if (mParent == null) {
15628            mParent = parent;
15629        } else if (parent == null) {
15630            mParent = null;
15631        } else {
15632            throw new RuntimeException("view " + this + " being added, but"
15633                    + " it already has a parent");
15634        }
15635    }
15636
15637    /**
15638     * This is called when the view is attached to a window.  At this point it
15639     * has a Surface and will start drawing.  Note that this function is
15640     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15641     * however it may be called any time before the first onDraw -- including
15642     * before or after {@link #onMeasure(int, int)}.
15643     *
15644     * @see #onDetachedFromWindow()
15645     */
15646    @CallSuper
15647    protected void onAttachedToWindow() {
15648        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15649            mParent.requestTransparentRegion(this);
15650        }
15651
15652        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15653
15654        jumpDrawablesToCurrentState();
15655
15656        resetSubtreeAccessibilityStateChanged();
15657
15658        // rebuild, since Outline not maintained while View is detached
15659        rebuildOutline();
15660
15661        if (isFocused()) {
15662            InputMethodManager imm = InputMethodManager.peekInstance();
15663            if (imm != null) {
15664                imm.focusIn(this);
15665            }
15666        }
15667    }
15668
15669    /**
15670     * Resolve all RTL related properties.
15671     *
15672     * @return true if resolution of RTL properties has been done
15673     *
15674     * @hide
15675     */
15676    public boolean resolveRtlPropertiesIfNeeded() {
15677        if (!needRtlPropertiesResolution()) return false;
15678
15679        // Order is important here: LayoutDirection MUST be resolved first
15680        if (!isLayoutDirectionResolved()) {
15681            resolveLayoutDirection();
15682            resolveLayoutParams();
15683        }
15684        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15685        if (!isTextDirectionResolved()) {
15686            resolveTextDirection();
15687        }
15688        if (!isTextAlignmentResolved()) {
15689            resolveTextAlignment();
15690        }
15691        // Should resolve Drawables before Padding because we need the layout direction of the
15692        // Drawable to correctly resolve Padding.
15693        if (!areDrawablesResolved()) {
15694            resolveDrawables();
15695        }
15696        if (!isPaddingResolved()) {
15697            resolvePadding();
15698        }
15699        onRtlPropertiesChanged(getLayoutDirection());
15700        return true;
15701    }
15702
15703    /**
15704     * Reset resolution of all RTL related properties.
15705     *
15706     * @hide
15707     */
15708    public void resetRtlProperties() {
15709        resetResolvedLayoutDirection();
15710        resetResolvedTextDirection();
15711        resetResolvedTextAlignment();
15712        resetResolvedPadding();
15713        resetResolvedDrawables();
15714    }
15715
15716    /**
15717     * @see #onScreenStateChanged(int)
15718     */
15719    void dispatchScreenStateChanged(int screenState) {
15720        onScreenStateChanged(screenState);
15721    }
15722
15723    /**
15724     * This method is called whenever the state of the screen this view is
15725     * attached to changes. A state change will usually occurs when the screen
15726     * turns on or off (whether it happens automatically or the user does it
15727     * manually.)
15728     *
15729     * @param screenState The new state of the screen. Can be either
15730     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15731     */
15732    public void onScreenStateChanged(int screenState) {
15733    }
15734
15735    /**
15736     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
15737     */
15738    private boolean hasRtlSupport() {
15739        return mContext.getApplicationInfo().hasRtlSupport();
15740    }
15741
15742    /**
15743     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15744     * RTL not supported)
15745     */
15746    private boolean isRtlCompatibilityMode() {
15747        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15748        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15749    }
15750
15751    /**
15752     * @return true if RTL properties need resolution.
15753     *
15754     */
15755    private boolean needRtlPropertiesResolution() {
15756        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15757    }
15758
15759    /**
15760     * Called when any RTL property (layout direction or text direction or text alignment) has
15761     * been changed.
15762     *
15763     * Subclasses need to override this method to take care of cached information that depends on the
15764     * resolved layout direction, or to inform child views that inherit their layout direction.
15765     *
15766     * The default implementation does nothing.
15767     *
15768     * @param layoutDirection the direction of the layout
15769     *
15770     * @see #LAYOUT_DIRECTION_LTR
15771     * @see #LAYOUT_DIRECTION_RTL
15772     */
15773    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15774    }
15775
15776    /**
15777     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15778     * that the parent directionality can and will be resolved before its children.
15779     *
15780     * @return true if resolution has been done, false otherwise.
15781     *
15782     * @hide
15783     */
15784    public boolean resolveLayoutDirection() {
15785        // Clear any previous layout direction resolution
15786        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15787
15788        if (hasRtlSupport()) {
15789            // Set resolved depending on layout direction
15790            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15791                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15792                case LAYOUT_DIRECTION_INHERIT:
15793                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15794                    // later to get the correct resolved value
15795                    if (!canResolveLayoutDirection()) return false;
15796
15797                    // Parent has not yet resolved, LTR is still the default
15798                    try {
15799                        if (!mParent.isLayoutDirectionResolved()) return false;
15800
15801                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15802                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15803                        }
15804                    } catch (AbstractMethodError e) {
15805                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15806                                " does not fully implement ViewParent", e);
15807                    }
15808                    break;
15809                case LAYOUT_DIRECTION_RTL:
15810                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15811                    break;
15812                case LAYOUT_DIRECTION_LOCALE:
15813                    if((LAYOUT_DIRECTION_RTL ==
15814                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15815                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15816                    }
15817                    break;
15818                default:
15819                    // Nothing to do, LTR by default
15820            }
15821        }
15822
15823        // Set to resolved
15824        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15825        return true;
15826    }
15827
15828    /**
15829     * Check if layout direction resolution can be done.
15830     *
15831     * @return true if layout direction resolution can be done otherwise return false.
15832     */
15833    public boolean canResolveLayoutDirection() {
15834        switch (getRawLayoutDirection()) {
15835            case LAYOUT_DIRECTION_INHERIT:
15836                if (mParent != null) {
15837                    try {
15838                        return mParent.canResolveLayoutDirection();
15839                    } catch (AbstractMethodError e) {
15840                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15841                                " does not fully implement ViewParent", e);
15842                    }
15843                }
15844                return false;
15845
15846            default:
15847                return true;
15848        }
15849    }
15850
15851    /**
15852     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15853     * {@link #onMeasure(int, int)}.
15854     *
15855     * @hide
15856     */
15857    public void resetResolvedLayoutDirection() {
15858        // Reset the current resolved bits
15859        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15860    }
15861
15862    /**
15863     * @return true if the layout direction is inherited.
15864     *
15865     * @hide
15866     */
15867    public boolean isLayoutDirectionInherited() {
15868        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15869    }
15870
15871    /**
15872     * @return true if layout direction has been resolved.
15873     */
15874    public boolean isLayoutDirectionResolved() {
15875        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15876    }
15877
15878    /**
15879     * Return if padding has been resolved
15880     *
15881     * @hide
15882     */
15883    boolean isPaddingResolved() {
15884        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15885    }
15886
15887    /**
15888     * Resolves padding depending on layout direction, if applicable, and
15889     * recomputes internal padding values to adjust for scroll bars.
15890     *
15891     * @hide
15892     */
15893    public void resolvePadding() {
15894        final int resolvedLayoutDirection = getLayoutDirection();
15895
15896        if (!isRtlCompatibilityMode()) {
15897            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15898            // If start / end padding are defined, they will be resolved (hence overriding) to
15899            // left / right or right / left depending on the resolved layout direction.
15900            // If start / end padding are not defined, use the left / right ones.
15901            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15902                Rect padding = sThreadLocal.get();
15903                if (padding == null) {
15904                    padding = new Rect();
15905                    sThreadLocal.set(padding);
15906                }
15907                mBackground.getPadding(padding);
15908                if (!mLeftPaddingDefined) {
15909                    mUserPaddingLeftInitial = padding.left;
15910                }
15911                if (!mRightPaddingDefined) {
15912                    mUserPaddingRightInitial = padding.right;
15913                }
15914            }
15915            switch (resolvedLayoutDirection) {
15916                case LAYOUT_DIRECTION_RTL:
15917                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15918                        mUserPaddingRight = mUserPaddingStart;
15919                    } else {
15920                        mUserPaddingRight = mUserPaddingRightInitial;
15921                    }
15922                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15923                        mUserPaddingLeft = mUserPaddingEnd;
15924                    } else {
15925                        mUserPaddingLeft = mUserPaddingLeftInitial;
15926                    }
15927                    break;
15928                case LAYOUT_DIRECTION_LTR:
15929                default:
15930                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15931                        mUserPaddingLeft = mUserPaddingStart;
15932                    } else {
15933                        mUserPaddingLeft = mUserPaddingLeftInitial;
15934                    }
15935                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15936                        mUserPaddingRight = mUserPaddingEnd;
15937                    } else {
15938                        mUserPaddingRight = mUserPaddingRightInitial;
15939                    }
15940            }
15941
15942            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15943        }
15944
15945        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15946        onRtlPropertiesChanged(resolvedLayoutDirection);
15947
15948        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15949    }
15950
15951    /**
15952     * Reset the resolved layout direction.
15953     *
15954     * @hide
15955     */
15956    public void resetResolvedPadding() {
15957        resetResolvedPaddingInternal();
15958    }
15959
15960    /**
15961     * Used when we only want to reset *this* view's padding and not trigger overrides
15962     * in ViewGroup that reset children too.
15963     */
15964    void resetResolvedPaddingInternal() {
15965        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15966    }
15967
15968    /**
15969     * This is called when the view is detached from a window.  At this point it
15970     * no longer has a surface for drawing.
15971     *
15972     * @see #onAttachedToWindow()
15973     */
15974    @CallSuper
15975    protected void onDetachedFromWindow() {
15976    }
15977
15978    /**
15979     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15980     * after onDetachedFromWindow().
15981     *
15982     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15983     * The super method should be called at the end of the overridden method to ensure
15984     * subclasses are destroyed first
15985     *
15986     * @hide
15987     */
15988    @CallSuper
15989    protected void onDetachedFromWindowInternal() {
15990        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15991        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15992        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15993
15994        removeUnsetPressCallback();
15995        removeLongPressCallback();
15996        removePerformClickCallback();
15997        removeSendViewScrolledAccessibilityEventCallback();
15998        stopNestedScroll();
15999
16000        // Anything that started animating right before detach should already
16001        // be in its final state when re-attached.
16002        jumpDrawablesToCurrentState();
16003
16004        destroyDrawingCache();
16005
16006        cleanupDraw();
16007        mCurrentAnimation = null;
16008
16009        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
16010            hideTooltip();
16011        }
16012    }
16013
16014    private void cleanupDraw() {
16015        resetDisplayList();
16016        if (mAttachInfo != null) {
16017            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
16018        }
16019    }
16020
16021    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
16022    }
16023
16024    /**
16025     * @return The number of times this view has been attached to a window
16026     */
16027    protected int getWindowAttachCount() {
16028        return mWindowAttachCount;
16029    }
16030
16031    /**
16032     * Retrieve a unique token identifying the window this view is attached to.
16033     * @return Return the window's token for use in
16034     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
16035     */
16036    public IBinder getWindowToken() {
16037        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
16038    }
16039
16040    /**
16041     * Retrieve the {@link WindowId} for the window this view is
16042     * currently attached to.
16043     */
16044    public WindowId getWindowId() {
16045        if (mAttachInfo == null) {
16046            return null;
16047        }
16048        if (mAttachInfo.mWindowId == null) {
16049            try {
16050                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
16051                        mAttachInfo.mWindowToken);
16052                mAttachInfo.mWindowId = new WindowId(
16053                        mAttachInfo.mIWindowId);
16054            } catch (RemoteException e) {
16055            }
16056        }
16057        return mAttachInfo.mWindowId;
16058    }
16059
16060    /**
16061     * Retrieve a unique token identifying the top-level "real" window of
16062     * the window that this view is attached to.  That is, this is like
16063     * {@link #getWindowToken}, except if the window this view in is a panel
16064     * window (attached to another containing window), then the token of
16065     * the containing window is returned instead.
16066     *
16067     * @return Returns the associated window token, either
16068     * {@link #getWindowToken()} or the containing window's token.
16069     */
16070    public IBinder getApplicationWindowToken() {
16071        AttachInfo ai = mAttachInfo;
16072        if (ai != null) {
16073            IBinder appWindowToken = ai.mPanelParentWindowToken;
16074            if (appWindowToken == null) {
16075                appWindowToken = ai.mWindowToken;
16076            }
16077            return appWindowToken;
16078        }
16079        return null;
16080    }
16081
16082    /**
16083     * Gets the logical display to which the view's window has been attached.
16084     *
16085     * @return The logical display, or null if the view is not currently attached to a window.
16086     */
16087    public Display getDisplay() {
16088        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
16089    }
16090
16091    /**
16092     * Retrieve private session object this view hierarchy is using to
16093     * communicate with the window manager.
16094     * @return the session object to communicate with the window manager
16095     */
16096    /*package*/ IWindowSession getWindowSession() {
16097        return mAttachInfo != null ? mAttachInfo.mSession : null;
16098    }
16099
16100    /**
16101     * Return the visibility value of the least visible component passed.
16102     */
16103    int combineVisibility(int vis1, int vis2) {
16104        // This works because VISIBLE < INVISIBLE < GONE.
16105        return Math.max(vis1, vis2);
16106    }
16107
16108    /**
16109     * @param info the {@link android.view.View.AttachInfo} to associated with
16110     *        this view
16111     */
16112    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
16113        mAttachInfo = info;
16114        if (mOverlay != null) {
16115            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
16116        }
16117        mWindowAttachCount++;
16118        // We will need to evaluate the drawable state at least once.
16119        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16120        if (mFloatingTreeObserver != null) {
16121            info.mTreeObserver.merge(mFloatingTreeObserver);
16122            mFloatingTreeObserver = null;
16123        }
16124
16125        registerPendingFrameMetricsObservers();
16126
16127        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
16128            mAttachInfo.mScrollContainers.add(this);
16129            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
16130        }
16131        // Transfer all pending runnables.
16132        if (mRunQueue != null) {
16133            mRunQueue.executeActions(info.mHandler);
16134            mRunQueue = null;
16135        }
16136        performCollectViewAttributes(mAttachInfo, visibility);
16137        onAttachedToWindow();
16138
16139        ListenerInfo li = mListenerInfo;
16140        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16141                li != null ? li.mOnAttachStateChangeListeners : null;
16142        if (listeners != null && listeners.size() > 0) {
16143            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16144            // perform the dispatching. The iterator is a safe guard against listeners that
16145            // could mutate the list by calling the various add/remove methods. This prevents
16146            // the array from being modified while we iterate it.
16147            for (OnAttachStateChangeListener listener : listeners) {
16148                listener.onViewAttachedToWindow(this);
16149            }
16150        }
16151
16152        int vis = info.mWindowVisibility;
16153        if (vis != GONE) {
16154            onWindowVisibilityChanged(vis);
16155            if (isShown()) {
16156                // Calling onVisibilityAggregated directly here since the subtree will also
16157                // receive dispatchAttachedToWindow and this same call
16158                onVisibilityAggregated(vis == VISIBLE);
16159            }
16160        }
16161
16162        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
16163        // As all views in the subtree will already receive dispatchAttachedToWindow
16164        // traversing the subtree again here is not desired.
16165        onVisibilityChanged(this, visibility);
16166
16167        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
16168            // If nobody has evaluated the drawable state yet, then do it now.
16169            refreshDrawableState();
16170        }
16171        needGlobalAttributesUpdate(false);
16172    }
16173
16174    void dispatchDetachedFromWindow() {
16175        AttachInfo info = mAttachInfo;
16176        if (info != null) {
16177            int vis = info.mWindowVisibility;
16178            if (vis != GONE) {
16179                onWindowVisibilityChanged(GONE);
16180                if (isShown()) {
16181                    // Invoking onVisibilityAggregated directly here since the subtree
16182                    // will also receive detached from window
16183                    onVisibilityAggregated(false);
16184                }
16185            }
16186        }
16187
16188        onDetachedFromWindow();
16189        onDetachedFromWindowInternal();
16190
16191        InputMethodManager imm = InputMethodManager.peekInstance();
16192        if (imm != null) {
16193            imm.onViewDetachedFromWindow(this);
16194        }
16195
16196        ListenerInfo li = mListenerInfo;
16197        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16198                li != null ? li.mOnAttachStateChangeListeners : null;
16199        if (listeners != null && listeners.size() > 0) {
16200            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16201            // perform the dispatching. The iterator is a safe guard against listeners that
16202            // could mutate the list by calling the various add/remove methods. This prevents
16203            // the array from being modified while we iterate it.
16204            for (OnAttachStateChangeListener listener : listeners) {
16205                listener.onViewDetachedFromWindow(this);
16206            }
16207        }
16208
16209        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
16210            mAttachInfo.mScrollContainers.remove(this);
16211            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
16212        }
16213
16214        mAttachInfo = null;
16215        if (mOverlay != null) {
16216            mOverlay.getOverlayView().dispatchDetachedFromWindow();
16217        }
16218    }
16219
16220    /**
16221     * Cancel any deferred high-level input events that were previously posted to the event queue.
16222     *
16223     * <p>Many views post high-level events such as click handlers to the event queue
16224     * to run deferred in order to preserve a desired user experience - clearing visible
16225     * pressed states before executing, etc. This method will abort any events of this nature
16226     * that are currently in flight.</p>
16227     *
16228     * <p>Custom views that generate their own high-level deferred input events should override
16229     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
16230     *
16231     * <p>This will also cancel pending input events for any child views.</p>
16232     *
16233     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
16234     * This will not impact newer events posted after this call that may occur as a result of
16235     * lower-level input events still waiting in the queue. If you are trying to prevent
16236     * double-submitted  events for the duration of some sort of asynchronous transaction
16237     * you should also take other steps to protect against unexpected double inputs e.g. calling
16238     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
16239     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
16240     */
16241    public final void cancelPendingInputEvents() {
16242        dispatchCancelPendingInputEvents();
16243    }
16244
16245    /**
16246     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
16247     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
16248     */
16249    void dispatchCancelPendingInputEvents() {
16250        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
16251        onCancelPendingInputEvents();
16252        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
16253            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
16254                    " did not call through to super.onCancelPendingInputEvents()");
16255        }
16256    }
16257
16258    /**
16259     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
16260     * a parent view.
16261     *
16262     * <p>This method is responsible for removing any pending high-level input events that were
16263     * posted to the event queue to run later. Custom view classes that post their own deferred
16264     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
16265     * {@link android.os.Handler} should override this method, call
16266     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
16267     * </p>
16268     */
16269    public void onCancelPendingInputEvents() {
16270        removePerformClickCallback();
16271        cancelLongPress();
16272        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
16273    }
16274
16275    /**
16276     * Store this view hierarchy's frozen state into the given container.
16277     *
16278     * @param container The SparseArray in which to save the view's state.
16279     *
16280     * @see #restoreHierarchyState(android.util.SparseArray)
16281     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16282     * @see #onSaveInstanceState()
16283     */
16284    public void saveHierarchyState(SparseArray<Parcelable> container) {
16285        dispatchSaveInstanceState(container);
16286    }
16287
16288    /**
16289     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
16290     * this view and its children. May be overridden to modify how freezing happens to a
16291     * view's children; for example, some views may want to not store state for their children.
16292     *
16293     * @param container The SparseArray in which to save the view's state.
16294     *
16295     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16296     * @see #saveHierarchyState(android.util.SparseArray)
16297     * @see #onSaveInstanceState()
16298     */
16299    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
16300        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
16301            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16302            Parcelable state = onSaveInstanceState();
16303            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16304                throw new IllegalStateException(
16305                        "Derived class did not call super.onSaveInstanceState()");
16306            }
16307            if (state != null) {
16308                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
16309                // + ": " + state);
16310                container.put(mID, state);
16311            }
16312        }
16313    }
16314
16315    /**
16316     * Hook allowing a view to generate a representation of its internal state
16317     * that can later be used to create a new instance with that same state.
16318     * This state should only contain information that is not persistent or can
16319     * not be reconstructed later. For example, you will never store your
16320     * current position on screen because that will be computed again when a
16321     * new instance of the view is placed in its view hierarchy.
16322     * <p>
16323     * Some examples of things you may store here: the current cursor position
16324     * in a text view (but usually not the text itself since that is stored in a
16325     * content provider or other persistent storage), the currently selected
16326     * item in a list view.
16327     *
16328     * @return Returns a Parcelable object containing the view's current dynamic
16329     *         state, or null if there is nothing interesting to save. The
16330     *         default implementation returns null.
16331     * @see #onRestoreInstanceState(android.os.Parcelable)
16332     * @see #saveHierarchyState(android.util.SparseArray)
16333     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16334     * @see #setSaveEnabled(boolean)
16335     */
16336    @CallSuper
16337    protected Parcelable onSaveInstanceState() {
16338        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16339        if (mStartActivityRequestWho != null) {
16340            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
16341            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
16342            return state;
16343        }
16344        return BaseSavedState.EMPTY_STATE;
16345    }
16346
16347    /**
16348     * Restore this view hierarchy's frozen state from the given container.
16349     *
16350     * @param container The SparseArray which holds previously frozen states.
16351     *
16352     * @see #saveHierarchyState(android.util.SparseArray)
16353     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16354     * @see #onRestoreInstanceState(android.os.Parcelable)
16355     */
16356    public void restoreHierarchyState(SparseArray<Parcelable> container) {
16357        dispatchRestoreInstanceState(container);
16358    }
16359
16360    /**
16361     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
16362     * state for this view and its children. May be overridden to modify how restoring
16363     * happens to a view's children; for example, some views may want to not store state
16364     * for their children.
16365     *
16366     * @param container The SparseArray which holds previously saved state.
16367     *
16368     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16369     * @see #restoreHierarchyState(android.util.SparseArray)
16370     * @see #onRestoreInstanceState(android.os.Parcelable)
16371     */
16372    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
16373        if (mID != NO_ID) {
16374            Parcelable state = container.get(mID);
16375            if (state != null) {
16376                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
16377                // + ": " + state);
16378                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16379                onRestoreInstanceState(state);
16380                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16381                    throw new IllegalStateException(
16382                            "Derived class did not call super.onRestoreInstanceState()");
16383                }
16384            }
16385        }
16386    }
16387
16388    /**
16389     * Hook allowing a view to re-apply a representation of its internal state that had previously
16390     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
16391     * null state.
16392     *
16393     * @param state The frozen state that had previously been returned by
16394     *        {@link #onSaveInstanceState}.
16395     *
16396     * @see #onSaveInstanceState()
16397     * @see #restoreHierarchyState(android.util.SparseArray)
16398     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16399     */
16400    @CallSuper
16401    protected void onRestoreInstanceState(Parcelable state) {
16402        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16403        if (state != null && !(state instanceof AbsSavedState)) {
16404            throw new IllegalArgumentException("Wrong state class, expecting View State but "
16405                    + "received " + state.getClass().toString() + " instead. This usually happens "
16406                    + "when two views of different type have the same id in the same hierarchy. "
16407                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
16408                    + "other views do not use the same id.");
16409        }
16410        if (state != null && state instanceof BaseSavedState) {
16411            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
16412        }
16413    }
16414
16415    /**
16416     * <p>Return the time at which the drawing of the view hierarchy started.</p>
16417     *
16418     * @return the drawing start time in milliseconds
16419     */
16420    public long getDrawingTime() {
16421        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
16422    }
16423
16424    /**
16425     * <p>Enables or disables the duplication of the parent's state into this view. When
16426     * duplication is enabled, this view gets its drawable state from its parent rather
16427     * than from its own internal properties.</p>
16428     *
16429     * <p>Note: in the current implementation, setting this property to true after the
16430     * view was added to a ViewGroup might have no effect at all. This property should
16431     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
16432     *
16433     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
16434     * property is enabled, an exception will be thrown.</p>
16435     *
16436     * <p>Note: if the child view uses and updates additional states which are unknown to the
16437     * parent, these states should not be affected by this method.</p>
16438     *
16439     * @param enabled True to enable duplication of the parent's drawable state, false
16440     *                to disable it.
16441     *
16442     * @see #getDrawableState()
16443     * @see #isDuplicateParentStateEnabled()
16444     */
16445    public void setDuplicateParentStateEnabled(boolean enabled) {
16446        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
16447    }
16448
16449    /**
16450     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
16451     *
16452     * @return True if this view's drawable state is duplicated from the parent,
16453     *         false otherwise
16454     *
16455     * @see #getDrawableState()
16456     * @see #setDuplicateParentStateEnabled(boolean)
16457     */
16458    public boolean isDuplicateParentStateEnabled() {
16459        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
16460    }
16461
16462    /**
16463     * <p>Specifies the type of layer backing this view. The layer can be
16464     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16465     * {@link #LAYER_TYPE_HARDWARE}.</p>
16466     *
16467     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16468     * instance that controls how the layer is composed on screen. The following
16469     * properties of the paint are taken into account when composing the layer:</p>
16470     * <ul>
16471     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16472     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16473     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16474     * </ul>
16475     *
16476     * <p>If this view has an alpha value set to < 1.0 by calling
16477     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
16478     * by this view's alpha value.</p>
16479     *
16480     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
16481     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
16482     * for more information on when and how to use layers.</p>
16483     *
16484     * @param layerType The type of layer to use with this view, must be one of
16485     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16486     *        {@link #LAYER_TYPE_HARDWARE}
16487     * @param paint The paint used to compose the layer. This argument is optional
16488     *        and can be null. It is ignored when the layer type is
16489     *        {@link #LAYER_TYPE_NONE}
16490     *
16491     * @see #getLayerType()
16492     * @see #LAYER_TYPE_NONE
16493     * @see #LAYER_TYPE_SOFTWARE
16494     * @see #LAYER_TYPE_HARDWARE
16495     * @see #setAlpha(float)
16496     *
16497     * @attr ref android.R.styleable#View_layerType
16498     */
16499    public void setLayerType(int layerType, @Nullable Paint paint) {
16500        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
16501            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
16502                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
16503        }
16504
16505        boolean typeChanged = mRenderNode.setLayerType(layerType);
16506
16507        if (!typeChanged) {
16508            setLayerPaint(paint);
16509            return;
16510        }
16511
16512        if (layerType != LAYER_TYPE_SOFTWARE) {
16513            // Destroy any previous software drawing cache if present
16514            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
16515            // drawing cache created in View#draw when drawing to a SW canvas.
16516            destroyDrawingCache();
16517        }
16518
16519        mLayerType = layerType;
16520        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
16521        mRenderNode.setLayerPaint(mLayerPaint);
16522
16523        // draw() behaves differently if we are on a layer, so we need to
16524        // invalidate() here
16525        invalidateParentCaches();
16526        invalidate(true);
16527    }
16528
16529    /**
16530     * Updates the {@link Paint} object used with the current layer (used only if the current
16531     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
16532     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
16533     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
16534     * ensure that the view gets redrawn immediately.
16535     *
16536     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16537     * instance that controls how the layer is composed on screen. The following
16538     * properties of the paint are taken into account when composing the layer:</p>
16539     * <ul>
16540     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16541     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16542     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16543     * </ul>
16544     *
16545     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
16546     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
16547     *
16548     * @param paint The paint used to compose the layer. This argument is optional
16549     *        and can be null. It is ignored when the layer type is
16550     *        {@link #LAYER_TYPE_NONE}
16551     *
16552     * @see #setLayerType(int, android.graphics.Paint)
16553     */
16554    public void setLayerPaint(@Nullable Paint paint) {
16555        int layerType = getLayerType();
16556        if (layerType != LAYER_TYPE_NONE) {
16557            mLayerPaint = paint;
16558            if (layerType == LAYER_TYPE_HARDWARE) {
16559                if (mRenderNode.setLayerPaint(paint)) {
16560                    invalidateViewProperty(false, false);
16561                }
16562            } else {
16563                invalidate();
16564            }
16565        }
16566    }
16567
16568    /**
16569     * Indicates what type of layer is currently associated with this view. By default
16570     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
16571     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
16572     * for more information on the different types of layers.
16573     *
16574     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16575     *         {@link #LAYER_TYPE_HARDWARE}
16576     *
16577     * @see #setLayerType(int, android.graphics.Paint)
16578     * @see #buildLayer()
16579     * @see #LAYER_TYPE_NONE
16580     * @see #LAYER_TYPE_SOFTWARE
16581     * @see #LAYER_TYPE_HARDWARE
16582     */
16583    public int getLayerType() {
16584        return mLayerType;
16585    }
16586
16587    /**
16588     * Forces this view's layer to be created and this view to be rendered
16589     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
16590     * invoking this method will have no effect.
16591     *
16592     * This method can for instance be used to render a view into its layer before
16593     * starting an animation. If this view is complex, rendering into the layer
16594     * before starting the animation will avoid skipping frames.
16595     *
16596     * @throws IllegalStateException If this view is not attached to a window
16597     *
16598     * @see #setLayerType(int, android.graphics.Paint)
16599     */
16600    public void buildLayer() {
16601        if (mLayerType == LAYER_TYPE_NONE) return;
16602
16603        final AttachInfo attachInfo = mAttachInfo;
16604        if (attachInfo == null) {
16605            throw new IllegalStateException("This view must be attached to a window first");
16606        }
16607
16608        if (getWidth() == 0 || getHeight() == 0) {
16609            return;
16610        }
16611
16612        switch (mLayerType) {
16613            case LAYER_TYPE_HARDWARE:
16614                updateDisplayListIfDirty();
16615                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
16616                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
16617                }
16618                break;
16619            case LAYER_TYPE_SOFTWARE:
16620                buildDrawingCache(true);
16621                break;
16622        }
16623    }
16624
16625    /**
16626     * Destroys all hardware rendering resources. This method is invoked
16627     * when the system needs to reclaim resources. Upon execution of this
16628     * method, you should free any OpenGL resources created by the view.
16629     *
16630     * Note: you <strong>must</strong> call
16631     * <code>super.destroyHardwareResources()</code> when overriding
16632     * this method.
16633     *
16634     * @hide
16635     */
16636    @CallSuper
16637    protected void destroyHardwareResources() {
16638        if (mOverlay != null) {
16639            mOverlay.getOverlayView().destroyHardwareResources();
16640        }
16641        if (mGhostView != null) {
16642            mGhostView.destroyHardwareResources();
16643        }
16644    }
16645
16646    /**
16647     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16648     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16649     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16650     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16651     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16652     * null.</p>
16653     *
16654     * <p>Enabling the drawing cache is similar to
16655     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16656     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16657     * drawing cache has no effect on rendering because the system uses a different mechanism
16658     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16659     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16660     * for information on how to enable software and hardware layers.</p>
16661     *
16662     * <p>This API can be used to manually generate
16663     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16664     * {@link #getDrawingCache()}.</p>
16665     *
16666     * @param enabled true to enable the drawing cache, false otherwise
16667     *
16668     * @see #isDrawingCacheEnabled()
16669     * @see #getDrawingCache()
16670     * @see #buildDrawingCache()
16671     * @see #setLayerType(int, android.graphics.Paint)
16672     */
16673    public void setDrawingCacheEnabled(boolean enabled) {
16674        mCachingFailed = false;
16675        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16676    }
16677
16678    /**
16679     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16680     *
16681     * @return true if the drawing cache is enabled
16682     *
16683     * @see #setDrawingCacheEnabled(boolean)
16684     * @see #getDrawingCache()
16685     */
16686    @ViewDebug.ExportedProperty(category = "drawing")
16687    public boolean isDrawingCacheEnabled() {
16688        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16689    }
16690
16691    /**
16692     * Debugging utility which recursively outputs the dirty state of a view and its
16693     * descendants.
16694     *
16695     * @hide
16696     */
16697    @SuppressWarnings({"UnusedDeclaration"})
16698    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16699        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16700                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16701                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16702                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16703        if (clear) {
16704            mPrivateFlags &= clearMask;
16705        }
16706        if (this instanceof ViewGroup) {
16707            ViewGroup parent = (ViewGroup) this;
16708            final int count = parent.getChildCount();
16709            for (int i = 0; i < count; i++) {
16710                final View child = parent.getChildAt(i);
16711                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16712            }
16713        }
16714    }
16715
16716    /**
16717     * This method is used by ViewGroup to cause its children to restore or recreate their
16718     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16719     * to recreate its own display list, which would happen if it went through the normal
16720     * draw/dispatchDraw mechanisms.
16721     *
16722     * @hide
16723     */
16724    protected void dispatchGetDisplayList() {}
16725
16726    /**
16727     * A view that is not attached or hardware accelerated cannot create a display list.
16728     * This method checks these conditions and returns the appropriate result.
16729     *
16730     * @return true if view has the ability to create a display list, false otherwise.
16731     *
16732     * @hide
16733     */
16734    public boolean canHaveDisplayList() {
16735        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
16736    }
16737
16738    /**
16739     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
16740     * @hide
16741     */
16742    @NonNull
16743    public RenderNode updateDisplayListIfDirty() {
16744        final RenderNode renderNode = mRenderNode;
16745        if (!canHaveDisplayList()) {
16746            // can't populate RenderNode, don't try
16747            return renderNode;
16748        }
16749
16750        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16751                || !renderNode.isValid()
16752                || (mRecreateDisplayList)) {
16753            // Don't need to recreate the display list, just need to tell our
16754            // children to restore/recreate theirs
16755            if (renderNode.isValid()
16756                    && !mRecreateDisplayList) {
16757                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16758                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16759                dispatchGetDisplayList();
16760
16761                return renderNode; // no work needed
16762            }
16763
16764            // If we got here, we're recreating it. Mark it as such to ensure that
16765            // we copy in child display lists into ours in drawChild()
16766            mRecreateDisplayList = true;
16767
16768            int width = mRight - mLeft;
16769            int height = mBottom - mTop;
16770            int layerType = getLayerType();
16771
16772            final DisplayListCanvas canvas = renderNode.start(width, height);
16773            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16774
16775            try {
16776                if (layerType == LAYER_TYPE_SOFTWARE) {
16777                    buildDrawingCache(true);
16778                    Bitmap cache = getDrawingCache(true);
16779                    if (cache != null) {
16780                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16781                    }
16782                } else {
16783                    computeScroll();
16784
16785                    canvas.translate(-mScrollX, -mScrollY);
16786                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16787                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16788
16789                    // Fast path for layouts with no backgrounds
16790                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16791                        dispatchDraw(canvas);
16792                        if (mOverlay != null && !mOverlay.isEmpty()) {
16793                            mOverlay.getOverlayView().draw(canvas);
16794                        }
16795                        if (debugDraw()) {
16796                            debugDrawFocus(canvas);
16797                        }
16798                    } else {
16799                        draw(canvas);
16800                    }
16801                }
16802            } finally {
16803                renderNode.end(canvas);
16804                setDisplayListProperties(renderNode);
16805            }
16806        } else {
16807            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16808            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16809        }
16810        return renderNode;
16811    }
16812
16813    private void resetDisplayList() {
16814        mRenderNode.discardDisplayList();
16815        if (mBackgroundRenderNode != null) {
16816            mBackgroundRenderNode.discardDisplayList();
16817        }
16818    }
16819
16820    /**
16821     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16822     *
16823     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16824     *
16825     * @see #getDrawingCache(boolean)
16826     */
16827    public Bitmap getDrawingCache() {
16828        return getDrawingCache(false);
16829    }
16830
16831    /**
16832     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16833     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16834     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16835     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16836     * request the drawing cache by calling this method and draw it on screen if the
16837     * returned bitmap is not null.</p>
16838     *
16839     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16840     * this method will create a bitmap of the same size as this view. Because this bitmap
16841     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16842     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16843     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16844     * size than the view. This implies that your application must be able to handle this
16845     * size.</p>
16846     *
16847     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16848     *        the current density of the screen when the application is in compatibility
16849     *        mode.
16850     *
16851     * @return A bitmap representing this view or null if cache is disabled.
16852     *
16853     * @see #setDrawingCacheEnabled(boolean)
16854     * @see #isDrawingCacheEnabled()
16855     * @see #buildDrawingCache(boolean)
16856     * @see #destroyDrawingCache()
16857     */
16858    public Bitmap getDrawingCache(boolean autoScale) {
16859        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16860            return null;
16861        }
16862        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16863            buildDrawingCache(autoScale);
16864        }
16865        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16866    }
16867
16868    /**
16869     * <p>Frees the resources used by the drawing cache. If you call
16870     * {@link #buildDrawingCache()} manually without calling
16871     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16872     * should cleanup the cache with this method afterwards.</p>
16873     *
16874     * @see #setDrawingCacheEnabled(boolean)
16875     * @see #buildDrawingCache()
16876     * @see #getDrawingCache()
16877     */
16878    public void destroyDrawingCache() {
16879        if (mDrawingCache != null) {
16880            mDrawingCache.recycle();
16881            mDrawingCache = null;
16882        }
16883        if (mUnscaledDrawingCache != null) {
16884            mUnscaledDrawingCache.recycle();
16885            mUnscaledDrawingCache = null;
16886        }
16887    }
16888
16889    /**
16890     * Setting a solid background color for the drawing cache's bitmaps will improve
16891     * performance and memory usage. Note, though that this should only be used if this
16892     * view will always be drawn on top of a solid color.
16893     *
16894     * @param color The background color to use for the drawing cache's bitmap
16895     *
16896     * @see #setDrawingCacheEnabled(boolean)
16897     * @see #buildDrawingCache()
16898     * @see #getDrawingCache()
16899     */
16900    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16901        if (color != mDrawingCacheBackgroundColor) {
16902            mDrawingCacheBackgroundColor = color;
16903            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16904        }
16905    }
16906
16907    /**
16908     * @see #setDrawingCacheBackgroundColor(int)
16909     *
16910     * @return The background color to used for the drawing cache's bitmap
16911     */
16912    @ColorInt
16913    public int getDrawingCacheBackgroundColor() {
16914        return mDrawingCacheBackgroundColor;
16915    }
16916
16917    /**
16918     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16919     *
16920     * @see #buildDrawingCache(boolean)
16921     */
16922    public void buildDrawingCache() {
16923        buildDrawingCache(false);
16924    }
16925
16926    /**
16927     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16928     *
16929     * <p>If you call {@link #buildDrawingCache()} manually without calling
16930     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16931     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16932     *
16933     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16934     * this method will create a bitmap of the same size as this view. Because this bitmap
16935     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16936     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16937     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16938     * size than the view. This implies that your application must be able to handle this
16939     * size.</p>
16940     *
16941     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16942     * you do not need the drawing cache bitmap, calling this method will increase memory
16943     * usage and cause the view to be rendered in software once, thus negatively impacting
16944     * performance.</p>
16945     *
16946     * @see #getDrawingCache()
16947     * @see #destroyDrawingCache()
16948     */
16949    public void buildDrawingCache(boolean autoScale) {
16950        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16951                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16952            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16953                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16954                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16955            }
16956            try {
16957                buildDrawingCacheImpl(autoScale);
16958            } finally {
16959                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16960            }
16961        }
16962    }
16963
16964    /**
16965     * private, internal implementation of buildDrawingCache, used to enable tracing
16966     */
16967    private void buildDrawingCacheImpl(boolean autoScale) {
16968        mCachingFailed = false;
16969
16970        int width = mRight - mLeft;
16971        int height = mBottom - mTop;
16972
16973        final AttachInfo attachInfo = mAttachInfo;
16974        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16975
16976        if (autoScale && scalingRequired) {
16977            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16978            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16979        }
16980
16981        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16982        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16983        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16984
16985        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16986        final long drawingCacheSize =
16987                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16988        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16989            if (width > 0 && height > 0) {
16990                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16991                        + " too large to fit into a software layer (or drawing cache), needs "
16992                        + projectedBitmapSize + " bytes, only "
16993                        + drawingCacheSize + " available");
16994            }
16995            destroyDrawingCache();
16996            mCachingFailed = true;
16997            return;
16998        }
16999
17000        boolean clear = true;
17001        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
17002
17003        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
17004            Bitmap.Config quality;
17005            if (!opaque) {
17006                // Never pick ARGB_4444 because it looks awful
17007                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
17008                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
17009                    case DRAWING_CACHE_QUALITY_AUTO:
17010                    case DRAWING_CACHE_QUALITY_LOW:
17011                    case DRAWING_CACHE_QUALITY_HIGH:
17012                    default:
17013                        quality = Bitmap.Config.ARGB_8888;
17014                        break;
17015                }
17016            } else {
17017                // Optimization for translucent windows
17018                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
17019                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
17020            }
17021
17022            // Try to cleanup memory
17023            if (bitmap != null) bitmap.recycle();
17024
17025            try {
17026                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17027                        width, height, quality);
17028                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
17029                if (autoScale) {
17030                    mDrawingCache = bitmap;
17031                } else {
17032                    mUnscaledDrawingCache = bitmap;
17033                }
17034                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
17035            } catch (OutOfMemoryError e) {
17036                // If there is not enough memory to create the bitmap cache, just
17037                // ignore the issue as bitmap caches are not required to draw the
17038                // view hierarchy
17039                if (autoScale) {
17040                    mDrawingCache = null;
17041                } else {
17042                    mUnscaledDrawingCache = null;
17043                }
17044                mCachingFailed = true;
17045                return;
17046            }
17047
17048            clear = drawingCacheBackgroundColor != 0;
17049        }
17050
17051        Canvas canvas;
17052        if (attachInfo != null) {
17053            canvas = attachInfo.mCanvas;
17054            if (canvas == null) {
17055                canvas = new Canvas();
17056            }
17057            canvas.setBitmap(bitmap);
17058            // Temporarily clobber the cached Canvas in case one of our children
17059            // is also using a drawing cache. Without this, the children would
17060            // steal the canvas by attaching their own bitmap to it and bad, bad
17061            // thing would happen (invisible views, corrupted drawings, etc.)
17062            attachInfo.mCanvas = null;
17063        } else {
17064            // This case should hopefully never or seldom happen
17065            canvas = new Canvas(bitmap);
17066        }
17067
17068        if (clear) {
17069            bitmap.eraseColor(drawingCacheBackgroundColor);
17070        }
17071
17072        computeScroll();
17073        final int restoreCount = canvas.save();
17074
17075        if (autoScale && scalingRequired) {
17076            final float scale = attachInfo.mApplicationScale;
17077            canvas.scale(scale, scale);
17078        }
17079
17080        canvas.translate(-mScrollX, -mScrollY);
17081
17082        mPrivateFlags |= PFLAG_DRAWN;
17083        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
17084                mLayerType != LAYER_TYPE_NONE) {
17085            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
17086        }
17087
17088        // Fast path for layouts with no backgrounds
17089        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17090            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17091            dispatchDraw(canvas);
17092            if (mOverlay != null && !mOverlay.isEmpty()) {
17093                mOverlay.getOverlayView().draw(canvas);
17094            }
17095        } else {
17096            draw(canvas);
17097        }
17098
17099        canvas.restoreToCount(restoreCount);
17100        canvas.setBitmap(null);
17101
17102        if (attachInfo != null) {
17103            // Restore the cached Canvas for our siblings
17104            attachInfo.mCanvas = canvas;
17105        }
17106    }
17107
17108    /**
17109     * Create a snapshot of the view into a bitmap.  We should probably make
17110     * some form of this public, but should think about the API.
17111     *
17112     * @hide
17113     */
17114    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
17115        int width = mRight - mLeft;
17116        int height = mBottom - mTop;
17117
17118        final AttachInfo attachInfo = mAttachInfo;
17119        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
17120        width = (int) ((width * scale) + 0.5f);
17121        height = (int) ((height * scale) + 0.5f);
17122
17123        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17124                width > 0 ? width : 1, height > 0 ? height : 1, quality);
17125        if (bitmap == null) {
17126            throw new OutOfMemoryError();
17127        }
17128
17129        Resources resources = getResources();
17130        if (resources != null) {
17131            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
17132        }
17133
17134        Canvas canvas;
17135        if (attachInfo != null) {
17136            canvas = attachInfo.mCanvas;
17137            if (canvas == null) {
17138                canvas = new Canvas();
17139            }
17140            canvas.setBitmap(bitmap);
17141            // Temporarily clobber the cached Canvas in case one of our children
17142            // is also using a drawing cache. Without this, the children would
17143            // steal the canvas by attaching their own bitmap to it and bad, bad
17144            // things would happen (invisible views, corrupted drawings, etc.)
17145            attachInfo.mCanvas = null;
17146        } else {
17147            // This case should hopefully never or seldom happen
17148            canvas = new Canvas(bitmap);
17149        }
17150
17151        if ((backgroundColor & 0xff000000) != 0) {
17152            bitmap.eraseColor(backgroundColor);
17153        }
17154
17155        computeScroll();
17156        final int restoreCount = canvas.save();
17157        canvas.scale(scale, scale);
17158        canvas.translate(-mScrollX, -mScrollY);
17159
17160        // Temporarily remove the dirty mask
17161        int flags = mPrivateFlags;
17162        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17163
17164        // Fast path for layouts with no backgrounds
17165        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17166            dispatchDraw(canvas);
17167            if (mOverlay != null && !mOverlay.isEmpty()) {
17168                mOverlay.getOverlayView().draw(canvas);
17169            }
17170        } else {
17171            draw(canvas);
17172        }
17173
17174        mPrivateFlags = flags;
17175
17176        canvas.restoreToCount(restoreCount);
17177        canvas.setBitmap(null);
17178
17179        if (attachInfo != null) {
17180            // Restore the cached Canvas for our siblings
17181            attachInfo.mCanvas = canvas;
17182        }
17183
17184        return bitmap;
17185    }
17186
17187    /**
17188     * Indicates whether this View is currently in edit mode. A View is usually
17189     * in edit mode when displayed within a developer tool. For instance, if
17190     * this View is being drawn by a visual user interface builder, this method
17191     * should return true.
17192     *
17193     * Subclasses should check the return value of this method to provide
17194     * different behaviors if their normal behavior might interfere with the
17195     * host environment. For instance: the class spawns a thread in its
17196     * constructor, the drawing code relies on device-specific features, etc.
17197     *
17198     * This method is usually checked in the drawing code of custom widgets.
17199     *
17200     * @return True if this View is in edit mode, false otherwise.
17201     */
17202    public boolean isInEditMode() {
17203        return false;
17204    }
17205
17206    /**
17207     * If the View draws content inside its padding and enables fading edges,
17208     * it needs to support padding offsets. Padding offsets are added to the
17209     * fading edges to extend the length of the fade so that it covers pixels
17210     * drawn inside the padding.
17211     *
17212     * Subclasses of this class should override this method if they need
17213     * to draw content inside the padding.
17214     *
17215     * @return True if padding offset must be applied, false otherwise.
17216     *
17217     * @see #getLeftPaddingOffset()
17218     * @see #getRightPaddingOffset()
17219     * @see #getTopPaddingOffset()
17220     * @see #getBottomPaddingOffset()
17221     *
17222     * @since CURRENT
17223     */
17224    protected boolean isPaddingOffsetRequired() {
17225        return false;
17226    }
17227
17228    /**
17229     * Amount by which to extend the left fading region. Called only when
17230     * {@link #isPaddingOffsetRequired()} returns true.
17231     *
17232     * @return The left padding offset in pixels.
17233     *
17234     * @see #isPaddingOffsetRequired()
17235     *
17236     * @since CURRENT
17237     */
17238    protected int getLeftPaddingOffset() {
17239        return 0;
17240    }
17241
17242    /**
17243     * Amount by which to extend the right fading region. Called only when
17244     * {@link #isPaddingOffsetRequired()} returns true.
17245     *
17246     * @return The right padding offset in pixels.
17247     *
17248     * @see #isPaddingOffsetRequired()
17249     *
17250     * @since CURRENT
17251     */
17252    protected int getRightPaddingOffset() {
17253        return 0;
17254    }
17255
17256    /**
17257     * Amount by which to extend the top fading region. Called only when
17258     * {@link #isPaddingOffsetRequired()} returns true.
17259     *
17260     * @return The top padding offset in pixels.
17261     *
17262     * @see #isPaddingOffsetRequired()
17263     *
17264     * @since CURRENT
17265     */
17266    protected int getTopPaddingOffset() {
17267        return 0;
17268    }
17269
17270    /**
17271     * Amount by which to extend the bottom fading region. Called only when
17272     * {@link #isPaddingOffsetRequired()} returns true.
17273     *
17274     * @return The bottom padding offset in pixels.
17275     *
17276     * @see #isPaddingOffsetRequired()
17277     *
17278     * @since CURRENT
17279     */
17280    protected int getBottomPaddingOffset() {
17281        return 0;
17282    }
17283
17284    /**
17285     * @hide
17286     * @param offsetRequired
17287     */
17288    protected int getFadeTop(boolean offsetRequired) {
17289        int top = mPaddingTop;
17290        if (offsetRequired) top += getTopPaddingOffset();
17291        return top;
17292    }
17293
17294    /**
17295     * @hide
17296     * @param offsetRequired
17297     */
17298    protected int getFadeHeight(boolean offsetRequired) {
17299        int padding = mPaddingTop;
17300        if (offsetRequired) padding += getTopPaddingOffset();
17301        return mBottom - mTop - mPaddingBottom - padding;
17302    }
17303
17304    /**
17305     * <p>Indicates whether this view is attached to a hardware accelerated
17306     * window or not.</p>
17307     *
17308     * <p>Even if this method returns true, it does not mean that every call
17309     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
17310     * accelerated {@link android.graphics.Canvas}. For instance, if this view
17311     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
17312     * window is hardware accelerated,
17313     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
17314     * return false, and this method will return true.</p>
17315     *
17316     * @return True if the view is attached to a window and the window is
17317     *         hardware accelerated; false in any other case.
17318     */
17319    @ViewDebug.ExportedProperty(category = "drawing")
17320    public boolean isHardwareAccelerated() {
17321        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
17322    }
17323
17324    /**
17325     * Sets a rectangular area on this view to which the view will be clipped
17326     * when it is drawn. Setting the value to null will remove the clip bounds
17327     * and the view will draw normally, using its full bounds.
17328     *
17329     * @param clipBounds The rectangular area, in the local coordinates of
17330     * this view, to which future drawing operations will be clipped.
17331     */
17332    public void setClipBounds(Rect clipBounds) {
17333        if (clipBounds == mClipBounds
17334                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
17335            return;
17336        }
17337        if (clipBounds != null) {
17338            if (mClipBounds == null) {
17339                mClipBounds = new Rect(clipBounds);
17340            } else {
17341                mClipBounds.set(clipBounds);
17342            }
17343        } else {
17344            mClipBounds = null;
17345        }
17346        mRenderNode.setClipBounds(mClipBounds);
17347        invalidateViewProperty(false, false);
17348    }
17349
17350    /**
17351     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
17352     *
17353     * @return A copy of the current clip bounds if clip bounds are set,
17354     * otherwise null.
17355     */
17356    public Rect getClipBounds() {
17357        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
17358    }
17359
17360
17361    /**
17362     * Populates an output rectangle with the clip bounds of the view,
17363     * returning {@code true} if successful or {@code false} if the view's
17364     * clip bounds are {@code null}.
17365     *
17366     * @param outRect rectangle in which to place the clip bounds of the view
17367     * @return {@code true} if successful or {@code false} if the view's
17368     *         clip bounds are {@code null}
17369     */
17370    public boolean getClipBounds(Rect outRect) {
17371        if (mClipBounds != null) {
17372            outRect.set(mClipBounds);
17373            return true;
17374        }
17375        return false;
17376    }
17377
17378    /**
17379     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
17380     * case of an active Animation being run on the view.
17381     */
17382    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
17383            Animation a, boolean scalingRequired) {
17384        Transformation invalidationTransform;
17385        final int flags = parent.mGroupFlags;
17386        final boolean initialized = a.isInitialized();
17387        if (!initialized) {
17388            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
17389            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
17390            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
17391            onAnimationStart();
17392        }
17393
17394        final Transformation t = parent.getChildTransformation();
17395        boolean more = a.getTransformation(drawingTime, t, 1f);
17396        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
17397            if (parent.mInvalidationTransformation == null) {
17398                parent.mInvalidationTransformation = new Transformation();
17399            }
17400            invalidationTransform = parent.mInvalidationTransformation;
17401            a.getTransformation(drawingTime, invalidationTransform, 1f);
17402        } else {
17403            invalidationTransform = t;
17404        }
17405
17406        if (more) {
17407            if (!a.willChangeBounds()) {
17408                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
17409                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
17410                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
17411                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
17412                    // The child need to draw an animation, potentially offscreen, so
17413                    // make sure we do not cancel invalidate requests
17414                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17415                    parent.invalidate(mLeft, mTop, mRight, mBottom);
17416                }
17417            } else {
17418                if (parent.mInvalidateRegion == null) {
17419                    parent.mInvalidateRegion = new RectF();
17420                }
17421                final RectF region = parent.mInvalidateRegion;
17422                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
17423                        invalidationTransform);
17424
17425                // The child need to draw an animation, potentially offscreen, so
17426                // make sure we do not cancel invalidate requests
17427                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17428
17429                final int left = mLeft + (int) region.left;
17430                final int top = mTop + (int) region.top;
17431                parent.invalidate(left, top, left + (int) (region.width() + .5f),
17432                        top + (int) (region.height() + .5f));
17433            }
17434        }
17435        return more;
17436    }
17437
17438    /**
17439     * This method is called by getDisplayList() when a display list is recorded for a View.
17440     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
17441     */
17442    void setDisplayListProperties(RenderNode renderNode) {
17443        if (renderNode != null) {
17444            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
17445            renderNode.setClipToBounds(mParent instanceof ViewGroup
17446                    && ((ViewGroup) mParent).getClipChildren());
17447
17448            float alpha = 1;
17449            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
17450                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17451                ViewGroup parentVG = (ViewGroup) mParent;
17452                final Transformation t = parentVG.getChildTransformation();
17453                if (parentVG.getChildStaticTransformation(this, t)) {
17454                    final int transformType = t.getTransformationType();
17455                    if (transformType != Transformation.TYPE_IDENTITY) {
17456                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
17457                            alpha = t.getAlpha();
17458                        }
17459                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
17460                            renderNode.setStaticMatrix(t.getMatrix());
17461                        }
17462                    }
17463                }
17464            }
17465            if (mTransformationInfo != null) {
17466                alpha *= getFinalAlpha();
17467                if (alpha < 1) {
17468                    final int multipliedAlpha = (int) (255 * alpha);
17469                    if (onSetAlpha(multipliedAlpha)) {
17470                        alpha = 1;
17471                    }
17472                }
17473                renderNode.setAlpha(alpha);
17474            } else if (alpha < 1) {
17475                renderNode.setAlpha(alpha);
17476            }
17477        }
17478    }
17479
17480    /**
17481     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
17482     *
17483     * This is where the View specializes rendering behavior based on layer type,
17484     * and hardware acceleration.
17485     */
17486    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
17487        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
17488        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
17489         *
17490         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
17491         * HW accelerated, it can't handle drawing RenderNodes.
17492         */
17493        boolean drawingWithRenderNode = mAttachInfo != null
17494                && mAttachInfo.mHardwareAccelerated
17495                && hardwareAcceleratedCanvas;
17496
17497        boolean more = false;
17498        final boolean childHasIdentityMatrix = hasIdentityMatrix();
17499        final int parentFlags = parent.mGroupFlags;
17500
17501        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
17502            parent.getChildTransformation().clear();
17503            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17504        }
17505
17506        Transformation transformToApply = null;
17507        boolean concatMatrix = false;
17508        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
17509        final Animation a = getAnimation();
17510        if (a != null) {
17511            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
17512            concatMatrix = a.willChangeTransformationMatrix();
17513            if (concatMatrix) {
17514                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17515            }
17516            transformToApply = parent.getChildTransformation();
17517        } else {
17518            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
17519                // No longer animating: clear out old animation matrix
17520                mRenderNode.setAnimationMatrix(null);
17521                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17522            }
17523            if (!drawingWithRenderNode
17524                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17525                final Transformation t = parent.getChildTransformation();
17526                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
17527                if (hasTransform) {
17528                    final int transformType = t.getTransformationType();
17529                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
17530                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
17531                }
17532            }
17533        }
17534
17535        concatMatrix |= !childHasIdentityMatrix;
17536
17537        // Sets the flag as early as possible to allow draw() implementations
17538        // to call invalidate() successfully when doing animations
17539        mPrivateFlags |= PFLAG_DRAWN;
17540
17541        if (!concatMatrix &&
17542                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
17543                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
17544                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
17545                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
17546            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
17547            return more;
17548        }
17549        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
17550
17551        if (hardwareAcceleratedCanvas) {
17552            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
17553            // retain the flag's value temporarily in the mRecreateDisplayList flag
17554            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
17555            mPrivateFlags &= ~PFLAG_INVALIDATED;
17556        }
17557
17558        RenderNode renderNode = null;
17559        Bitmap cache = null;
17560        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
17561        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
17562             if (layerType != LAYER_TYPE_NONE) {
17563                 // If not drawing with RenderNode, treat HW layers as SW
17564                 layerType = LAYER_TYPE_SOFTWARE;
17565                 buildDrawingCache(true);
17566            }
17567            cache = getDrawingCache(true);
17568        }
17569
17570        if (drawingWithRenderNode) {
17571            // Delay getting the display list until animation-driven alpha values are
17572            // set up and possibly passed on to the view
17573            renderNode = updateDisplayListIfDirty();
17574            if (!renderNode.isValid()) {
17575                // Uncommon, but possible. If a view is removed from the hierarchy during the call
17576                // to getDisplayList(), the display list will be marked invalid and we should not
17577                // try to use it again.
17578                renderNode = null;
17579                drawingWithRenderNode = false;
17580            }
17581        }
17582
17583        int sx = 0;
17584        int sy = 0;
17585        if (!drawingWithRenderNode) {
17586            computeScroll();
17587            sx = mScrollX;
17588            sy = mScrollY;
17589        }
17590
17591        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
17592        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
17593
17594        int restoreTo = -1;
17595        if (!drawingWithRenderNode || transformToApply != null) {
17596            restoreTo = canvas.save();
17597        }
17598        if (offsetForScroll) {
17599            canvas.translate(mLeft - sx, mTop - sy);
17600        } else {
17601            if (!drawingWithRenderNode) {
17602                canvas.translate(mLeft, mTop);
17603            }
17604            if (scalingRequired) {
17605                if (drawingWithRenderNode) {
17606                    // TODO: Might not need this if we put everything inside the DL
17607                    restoreTo = canvas.save();
17608                }
17609                // mAttachInfo cannot be null, otherwise scalingRequired == false
17610                final float scale = 1.0f / mAttachInfo.mApplicationScale;
17611                canvas.scale(scale, scale);
17612            }
17613        }
17614
17615        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
17616        if (transformToApply != null
17617                || alpha < 1
17618                || !hasIdentityMatrix()
17619                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17620            if (transformToApply != null || !childHasIdentityMatrix) {
17621                int transX = 0;
17622                int transY = 0;
17623
17624                if (offsetForScroll) {
17625                    transX = -sx;
17626                    transY = -sy;
17627                }
17628
17629                if (transformToApply != null) {
17630                    if (concatMatrix) {
17631                        if (drawingWithRenderNode) {
17632                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17633                        } else {
17634                            // Undo the scroll translation, apply the transformation matrix,
17635                            // then redo the scroll translate to get the correct result.
17636                            canvas.translate(-transX, -transY);
17637                            canvas.concat(transformToApply.getMatrix());
17638                            canvas.translate(transX, transY);
17639                        }
17640                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17641                    }
17642
17643                    float transformAlpha = transformToApply.getAlpha();
17644                    if (transformAlpha < 1) {
17645                        alpha *= transformAlpha;
17646                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17647                    }
17648                }
17649
17650                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17651                    canvas.translate(-transX, -transY);
17652                    canvas.concat(getMatrix());
17653                    canvas.translate(transX, transY);
17654                }
17655            }
17656
17657            // Deal with alpha if it is or used to be <1
17658            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17659                if (alpha < 1) {
17660                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17661                } else {
17662                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17663                }
17664                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17665                if (!drawingWithDrawingCache) {
17666                    final int multipliedAlpha = (int) (255 * alpha);
17667                    if (!onSetAlpha(multipliedAlpha)) {
17668                        if (drawingWithRenderNode) {
17669                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17670                        } else if (layerType == LAYER_TYPE_NONE) {
17671                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17672                                    multipliedAlpha);
17673                        }
17674                    } else {
17675                        // Alpha is handled by the child directly, clobber the layer's alpha
17676                        mPrivateFlags |= PFLAG_ALPHA_SET;
17677                    }
17678                }
17679            }
17680        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17681            onSetAlpha(255);
17682            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17683        }
17684
17685        if (!drawingWithRenderNode) {
17686            // apply clips directly, since RenderNode won't do it for this draw
17687            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17688                if (offsetForScroll) {
17689                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17690                } else {
17691                    if (!scalingRequired || cache == null) {
17692                        canvas.clipRect(0, 0, getWidth(), getHeight());
17693                    } else {
17694                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17695                    }
17696                }
17697            }
17698
17699            if (mClipBounds != null) {
17700                // clip bounds ignore scroll
17701                canvas.clipRect(mClipBounds);
17702            }
17703        }
17704
17705        if (!drawingWithDrawingCache) {
17706            if (drawingWithRenderNode) {
17707                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17708                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17709            } else {
17710                // Fast path for layouts with no backgrounds
17711                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17712                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17713                    dispatchDraw(canvas);
17714                } else {
17715                    draw(canvas);
17716                }
17717            }
17718        } else if (cache != null) {
17719            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17720            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17721                // no layer paint, use temporary paint to draw bitmap
17722                Paint cachePaint = parent.mCachePaint;
17723                if (cachePaint == null) {
17724                    cachePaint = new Paint();
17725                    cachePaint.setDither(false);
17726                    parent.mCachePaint = cachePaint;
17727                }
17728                cachePaint.setAlpha((int) (alpha * 255));
17729                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17730            } else {
17731                // use layer paint to draw the bitmap, merging the two alphas, but also restore
17732                int layerPaintAlpha = mLayerPaint.getAlpha();
17733                if (alpha < 1) {
17734                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
17735                }
17736                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17737                if (alpha < 1) {
17738                    mLayerPaint.setAlpha(layerPaintAlpha);
17739                }
17740            }
17741        }
17742
17743        if (restoreTo >= 0) {
17744            canvas.restoreToCount(restoreTo);
17745        }
17746
17747        if (a != null && !more) {
17748            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17749                onSetAlpha(255);
17750            }
17751            parent.finishAnimatingView(this, a);
17752        }
17753
17754        if (more && hardwareAcceleratedCanvas) {
17755            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17756                // alpha animations should cause the child to recreate its display list
17757                invalidate(true);
17758            }
17759        }
17760
17761        mRecreateDisplayList = false;
17762
17763        return more;
17764    }
17765
17766    static Paint getDebugPaint() {
17767        if (sDebugPaint == null) {
17768            sDebugPaint = new Paint();
17769            sDebugPaint.setAntiAlias(false);
17770        }
17771        return sDebugPaint;
17772    }
17773
17774    final int dipsToPixels(int dips) {
17775        float scale = getContext().getResources().getDisplayMetrics().density;
17776        return (int) (dips * scale + 0.5f);
17777    }
17778
17779    final private void debugDrawFocus(Canvas canvas) {
17780        if (isFocused()) {
17781            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
17782            final int l = mScrollX;
17783            final int r = l + mRight - mLeft;
17784            final int t = mScrollY;
17785            final int b = t + mBottom - mTop;
17786
17787            final Paint paint = getDebugPaint();
17788            paint.setColor(DEBUG_CORNERS_COLOR);
17789
17790            // Draw squares in corners.
17791            paint.setStyle(Paint.Style.FILL);
17792            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
17793            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
17794            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
17795            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
17796
17797            // Draw big X across the view.
17798            paint.setStyle(Paint.Style.STROKE);
17799            canvas.drawLine(l, t, r, b, paint);
17800            canvas.drawLine(l, b, r, t, paint);
17801        }
17802    }
17803
17804    /**
17805     * Manually render this view (and all of its children) to the given Canvas.
17806     * The view must have already done a full layout before this function is
17807     * called.  When implementing a view, implement
17808     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17809     * If you do need to override this method, call the superclass version.
17810     *
17811     * @param canvas The Canvas to which the View is rendered.
17812     */
17813    @CallSuper
17814    public void draw(Canvas canvas) {
17815        final int privateFlags = mPrivateFlags;
17816        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17817                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17818        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17819
17820        /*
17821         * Draw traversal performs several drawing steps which must be executed
17822         * in the appropriate order:
17823         *
17824         *      1. Draw the background
17825         *      2. If necessary, save the canvas' layers to prepare for fading
17826         *      3. Draw view's content
17827         *      4. Draw children
17828         *      5. If necessary, draw the fading edges and restore layers
17829         *      6. Draw decorations (scrollbars for instance)
17830         */
17831
17832        // Step 1, draw the background, if needed
17833        int saveCount;
17834
17835        if (!dirtyOpaque) {
17836            drawBackground(canvas);
17837        }
17838
17839        // skip step 2 & 5 if possible (common case)
17840        final int viewFlags = mViewFlags;
17841        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17842        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17843        if (!verticalEdges && !horizontalEdges) {
17844            // Step 3, draw the content
17845            if (!dirtyOpaque) onDraw(canvas);
17846
17847            // Step 4, draw the children
17848            dispatchDraw(canvas);
17849
17850            // Overlay is part of the content and draws beneath Foreground
17851            if (mOverlay != null && !mOverlay.isEmpty()) {
17852                mOverlay.getOverlayView().dispatchDraw(canvas);
17853            }
17854
17855            // Step 6, draw decorations (foreground, scrollbars)
17856            onDrawForeground(canvas);
17857
17858            if (debugDraw()) {
17859                debugDrawFocus(canvas);
17860            }
17861
17862            // we're done...
17863            return;
17864        }
17865
17866        /*
17867         * Here we do the full fledged routine...
17868         * (this is an uncommon case where speed matters less,
17869         * this is why we repeat some of the tests that have been
17870         * done above)
17871         */
17872
17873        boolean drawTop = false;
17874        boolean drawBottom = false;
17875        boolean drawLeft = false;
17876        boolean drawRight = false;
17877
17878        float topFadeStrength = 0.0f;
17879        float bottomFadeStrength = 0.0f;
17880        float leftFadeStrength = 0.0f;
17881        float rightFadeStrength = 0.0f;
17882
17883        // Step 2, save the canvas' layers
17884        int paddingLeft = mPaddingLeft;
17885
17886        final boolean offsetRequired = isPaddingOffsetRequired();
17887        if (offsetRequired) {
17888            paddingLeft += getLeftPaddingOffset();
17889        }
17890
17891        int left = mScrollX + paddingLeft;
17892        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17893        int top = mScrollY + getFadeTop(offsetRequired);
17894        int bottom = top + getFadeHeight(offsetRequired);
17895
17896        if (offsetRequired) {
17897            right += getRightPaddingOffset();
17898            bottom += getBottomPaddingOffset();
17899        }
17900
17901        final ScrollabilityCache scrollabilityCache = mScrollCache;
17902        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17903        int length = (int) fadeHeight;
17904
17905        // clip the fade length if top and bottom fades overlap
17906        // overlapping fades produce odd-looking artifacts
17907        if (verticalEdges && (top + length > bottom - length)) {
17908            length = (bottom - top) / 2;
17909        }
17910
17911        // also clip horizontal fades if necessary
17912        if (horizontalEdges && (left + length > right - length)) {
17913            length = (right - left) / 2;
17914        }
17915
17916        if (verticalEdges) {
17917            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17918            drawTop = topFadeStrength * fadeHeight > 1.0f;
17919            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17920            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17921        }
17922
17923        if (horizontalEdges) {
17924            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17925            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17926            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17927            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17928        }
17929
17930        saveCount = canvas.getSaveCount();
17931
17932        int solidColor = getSolidColor();
17933        if (solidColor == 0) {
17934            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17935
17936            if (drawTop) {
17937                canvas.saveLayer(left, top, right, top + length, null, flags);
17938            }
17939
17940            if (drawBottom) {
17941                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17942            }
17943
17944            if (drawLeft) {
17945                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17946            }
17947
17948            if (drawRight) {
17949                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17950            }
17951        } else {
17952            scrollabilityCache.setFadeColor(solidColor);
17953        }
17954
17955        // Step 3, draw the content
17956        if (!dirtyOpaque) onDraw(canvas);
17957
17958        // Step 4, draw the children
17959        dispatchDraw(canvas);
17960
17961        // Step 5, draw the fade effect and restore layers
17962        final Paint p = scrollabilityCache.paint;
17963        final Matrix matrix = scrollabilityCache.matrix;
17964        final Shader fade = scrollabilityCache.shader;
17965
17966        if (drawTop) {
17967            matrix.setScale(1, fadeHeight * topFadeStrength);
17968            matrix.postTranslate(left, top);
17969            fade.setLocalMatrix(matrix);
17970            p.setShader(fade);
17971            canvas.drawRect(left, top, right, top + length, p);
17972        }
17973
17974        if (drawBottom) {
17975            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17976            matrix.postRotate(180);
17977            matrix.postTranslate(left, bottom);
17978            fade.setLocalMatrix(matrix);
17979            p.setShader(fade);
17980            canvas.drawRect(left, bottom - length, right, bottom, p);
17981        }
17982
17983        if (drawLeft) {
17984            matrix.setScale(1, fadeHeight * leftFadeStrength);
17985            matrix.postRotate(-90);
17986            matrix.postTranslate(left, top);
17987            fade.setLocalMatrix(matrix);
17988            p.setShader(fade);
17989            canvas.drawRect(left, top, left + length, bottom, p);
17990        }
17991
17992        if (drawRight) {
17993            matrix.setScale(1, fadeHeight * rightFadeStrength);
17994            matrix.postRotate(90);
17995            matrix.postTranslate(right, top);
17996            fade.setLocalMatrix(matrix);
17997            p.setShader(fade);
17998            canvas.drawRect(right - length, top, right, bottom, p);
17999        }
18000
18001        canvas.restoreToCount(saveCount);
18002
18003        // Overlay is part of the content and draws beneath Foreground
18004        if (mOverlay != null && !mOverlay.isEmpty()) {
18005            mOverlay.getOverlayView().dispatchDraw(canvas);
18006        }
18007
18008        // Step 6, draw decorations (foreground, scrollbars)
18009        onDrawForeground(canvas);
18010
18011        if (debugDraw()) {
18012            debugDrawFocus(canvas);
18013        }
18014    }
18015
18016    /**
18017     * Draws the background onto the specified canvas.
18018     *
18019     * @param canvas Canvas on which to draw the background
18020     */
18021    private void drawBackground(Canvas canvas) {
18022        final Drawable background = mBackground;
18023        if (background == null) {
18024            return;
18025        }
18026
18027        setBackgroundBounds();
18028
18029        // Attempt to use a display list if requested.
18030        if (canvas.isHardwareAccelerated() && mAttachInfo != null
18031                && mAttachInfo.mThreadedRenderer != null) {
18032            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
18033
18034            final RenderNode renderNode = mBackgroundRenderNode;
18035            if (renderNode != null && renderNode.isValid()) {
18036                setBackgroundRenderNodeProperties(renderNode);
18037                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
18038                return;
18039            }
18040        }
18041
18042        final int scrollX = mScrollX;
18043        final int scrollY = mScrollY;
18044        if ((scrollX | scrollY) == 0) {
18045            background.draw(canvas);
18046        } else {
18047            canvas.translate(scrollX, scrollY);
18048            background.draw(canvas);
18049            canvas.translate(-scrollX, -scrollY);
18050        }
18051    }
18052
18053    /**
18054     * Sets the correct background bounds and rebuilds the outline, if needed.
18055     * <p/>
18056     * This is called by LayoutLib.
18057     */
18058    void setBackgroundBounds() {
18059        if (mBackgroundSizeChanged && mBackground != null) {
18060            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
18061            mBackgroundSizeChanged = false;
18062            rebuildOutline();
18063        }
18064    }
18065
18066    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
18067        renderNode.setTranslationX(mScrollX);
18068        renderNode.setTranslationY(mScrollY);
18069    }
18070
18071    /**
18072     * Creates a new display list or updates the existing display list for the
18073     * specified Drawable.
18074     *
18075     * @param drawable Drawable for which to create a display list
18076     * @param renderNode Existing RenderNode, or {@code null}
18077     * @return A valid display list for the specified drawable
18078     */
18079    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
18080        if (renderNode == null) {
18081            renderNode = RenderNode.create(drawable.getClass().getName(), this);
18082        }
18083
18084        final Rect bounds = drawable.getBounds();
18085        final int width = bounds.width();
18086        final int height = bounds.height();
18087        final DisplayListCanvas canvas = renderNode.start(width, height);
18088
18089        // Reverse left/top translation done by drawable canvas, which will
18090        // instead be applied by rendernode's LTRB bounds below. This way, the
18091        // drawable's bounds match with its rendernode bounds and its content
18092        // will lie within those bounds in the rendernode tree.
18093        canvas.translate(-bounds.left, -bounds.top);
18094
18095        try {
18096            drawable.draw(canvas);
18097        } finally {
18098            renderNode.end(canvas);
18099        }
18100
18101        // Set up drawable properties that are view-independent.
18102        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
18103        renderNode.setProjectBackwards(drawable.isProjected());
18104        renderNode.setProjectionReceiver(true);
18105        renderNode.setClipToBounds(false);
18106        return renderNode;
18107    }
18108
18109    /**
18110     * Returns the overlay for this view, creating it if it does not yet exist.
18111     * Adding drawables to the overlay will cause them to be displayed whenever
18112     * the view itself is redrawn. Objects in the overlay should be actively
18113     * managed: remove them when they should not be displayed anymore. The
18114     * overlay will always have the same size as its host view.
18115     *
18116     * <p>Note: Overlays do not currently work correctly with {@link
18117     * SurfaceView} or {@link TextureView}; contents in overlays for these
18118     * types of views may not display correctly.</p>
18119     *
18120     * @return The ViewOverlay object for this view.
18121     * @see ViewOverlay
18122     */
18123    public ViewOverlay getOverlay() {
18124        if (mOverlay == null) {
18125            mOverlay = new ViewOverlay(mContext, this);
18126        }
18127        return mOverlay;
18128    }
18129
18130    /**
18131     * Override this if your view is known to always be drawn on top of a solid color background,
18132     * and needs to draw fading edges. Returning a non-zero color enables the view system to
18133     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
18134     * should be set to 0xFF.
18135     *
18136     * @see #setVerticalFadingEdgeEnabled(boolean)
18137     * @see #setHorizontalFadingEdgeEnabled(boolean)
18138     *
18139     * @return The known solid color background for this view, or 0 if the color may vary
18140     */
18141    @ViewDebug.ExportedProperty(category = "drawing")
18142    @ColorInt
18143    public int getSolidColor() {
18144        return 0;
18145    }
18146
18147    /**
18148     * Build a human readable string representation of the specified view flags.
18149     *
18150     * @param flags the view flags to convert to a string
18151     * @return a String representing the supplied flags
18152     */
18153    private static String printFlags(int flags) {
18154        String output = "";
18155        int numFlags = 0;
18156        if ((flags & FOCUSABLE) == FOCUSABLE) {
18157            output += "TAKES_FOCUS";
18158            numFlags++;
18159        }
18160
18161        switch (flags & VISIBILITY_MASK) {
18162        case INVISIBLE:
18163            if (numFlags > 0) {
18164                output += " ";
18165            }
18166            output += "INVISIBLE";
18167            // USELESS HERE numFlags++;
18168            break;
18169        case GONE:
18170            if (numFlags > 0) {
18171                output += " ";
18172            }
18173            output += "GONE";
18174            // USELESS HERE numFlags++;
18175            break;
18176        default:
18177            break;
18178        }
18179        return output;
18180    }
18181
18182    /**
18183     * Build a human readable string representation of the specified private
18184     * view flags.
18185     *
18186     * @param privateFlags the private view flags to convert to a string
18187     * @return a String representing the supplied flags
18188     */
18189    private static String printPrivateFlags(int privateFlags) {
18190        String output = "";
18191        int numFlags = 0;
18192
18193        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
18194            output += "WANTS_FOCUS";
18195            numFlags++;
18196        }
18197
18198        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
18199            if (numFlags > 0) {
18200                output += " ";
18201            }
18202            output += "FOCUSED";
18203            numFlags++;
18204        }
18205
18206        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
18207            if (numFlags > 0) {
18208                output += " ";
18209            }
18210            output += "SELECTED";
18211            numFlags++;
18212        }
18213
18214        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
18215            if (numFlags > 0) {
18216                output += " ";
18217            }
18218            output += "IS_ROOT_NAMESPACE";
18219            numFlags++;
18220        }
18221
18222        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
18223            if (numFlags > 0) {
18224                output += " ";
18225            }
18226            output += "HAS_BOUNDS";
18227            numFlags++;
18228        }
18229
18230        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
18231            if (numFlags > 0) {
18232                output += " ";
18233            }
18234            output += "DRAWN";
18235            // USELESS HERE numFlags++;
18236        }
18237        return output;
18238    }
18239
18240    /**
18241     * <p>Indicates whether or not this view's layout will be requested during
18242     * the next hierarchy layout pass.</p>
18243     *
18244     * @return true if the layout will be forced during next layout pass
18245     */
18246    public boolean isLayoutRequested() {
18247        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18248    }
18249
18250    /**
18251     * Return true if o is a ViewGroup that is laying out using optical bounds.
18252     * @hide
18253     */
18254    public static boolean isLayoutModeOptical(Object o) {
18255        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
18256    }
18257
18258    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
18259        Insets parentInsets = mParent instanceof View ?
18260                ((View) mParent).getOpticalInsets() : Insets.NONE;
18261        Insets childInsets = getOpticalInsets();
18262        return setFrame(
18263                left   + parentInsets.left - childInsets.left,
18264                top    + parentInsets.top  - childInsets.top,
18265                right  + parentInsets.left + childInsets.right,
18266                bottom + parentInsets.top  + childInsets.bottom);
18267    }
18268
18269    /**
18270     * Assign a size and position to a view and all of its
18271     * descendants
18272     *
18273     * <p>This is the second phase of the layout mechanism.
18274     * (The first is measuring). In this phase, each parent calls
18275     * layout on all of its children to position them.
18276     * This is typically done using the child measurements
18277     * that were stored in the measure pass().</p>
18278     *
18279     * <p>Derived classes should not override this method.
18280     * Derived classes with children should override
18281     * onLayout. In that method, they should
18282     * call layout on each of their children.</p>
18283     *
18284     * @param l Left position, relative to parent
18285     * @param t Top position, relative to parent
18286     * @param r Right position, relative to parent
18287     * @param b Bottom position, relative to parent
18288     */
18289    @SuppressWarnings({"unchecked"})
18290    public void layout(int l, int t, int r, int b) {
18291        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
18292            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
18293            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18294        }
18295
18296        int oldL = mLeft;
18297        int oldT = mTop;
18298        int oldB = mBottom;
18299        int oldR = mRight;
18300
18301        boolean changed = isLayoutModeOptical(mParent) ?
18302                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
18303
18304        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
18305            onLayout(changed, l, t, r, b);
18306
18307            if (shouldDrawRoundScrollbar()) {
18308                if(mRoundScrollbarRenderer == null) {
18309                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
18310                }
18311            } else {
18312                mRoundScrollbarRenderer = null;
18313            }
18314
18315            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
18316
18317            ListenerInfo li = mListenerInfo;
18318            if (li != null && li.mOnLayoutChangeListeners != null) {
18319                ArrayList<OnLayoutChangeListener> listenersCopy =
18320                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
18321                int numListeners = listenersCopy.size();
18322                for (int i = 0; i < numListeners; ++i) {
18323                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
18324                }
18325            }
18326        }
18327
18328        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
18329        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
18330    }
18331
18332    /**
18333     * Called from layout when this view should
18334     * assign a size and position to each of its children.
18335     *
18336     * Derived classes with children should override
18337     * this method and call layout on each of
18338     * their children.
18339     * @param changed This is a new size or position for this view
18340     * @param left Left position, relative to parent
18341     * @param top Top position, relative to parent
18342     * @param right Right position, relative to parent
18343     * @param bottom Bottom position, relative to parent
18344     */
18345    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
18346    }
18347
18348    /**
18349     * Assign a size and position to this view.
18350     *
18351     * This is called from layout.
18352     *
18353     * @param left Left position, relative to parent
18354     * @param top Top position, relative to parent
18355     * @param right Right position, relative to parent
18356     * @param bottom Bottom position, relative to parent
18357     * @return true if the new size and position are different than the
18358     *         previous ones
18359     * {@hide}
18360     */
18361    protected boolean setFrame(int left, int top, int right, int bottom) {
18362        boolean changed = false;
18363
18364        if (DBG) {
18365            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
18366                    + right + "," + bottom + ")");
18367        }
18368
18369        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
18370            changed = true;
18371
18372            // Remember our drawn bit
18373            int drawn = mPrivateFlags & PFLAG_DRAWN;
18374
18375            int oldWidth = mRight - mLeft;
18376            int oldHeight = mBottom - mTop;
18377            int newWidth = right - left;
18378            int newHeight = bottom - top;
18379            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
18380
18381            // Invalidate our old position
18382            invalidate(sizeChanged);
18383
18384            mLeft = left;
18385            mTop = top;
18386            mRight = right;
18387            mBottom = bottom;
18388            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
18389
18390            mPrivateFlags |= PFLAG_HAS_BOUNDS;
18391
18392
18393            if (sizeChanged) {
18394                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
18395            }
18396
18397            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
18398                // If we are visible, force the DRAWN bit to on so that
18399                // this invalidate will go through (at least to our parent).
18400                // This is because someone may have invalidated this view
18401                // before this call to setFrame came in, thereby clearing
18402                // the DRAWN bit.
18403                mPrivateFlags |= PFLAG_DRAWN;
18404                invalidate(sizeChanged);
18405                // parent display list may need to be recreated based on a change in the bounds
18406                // of any child
18407                invalidateParentCaches();
18408            }
18409
18410            // Reset drawn bit to original value (invalidate turns it off)
18411            mPrivateFlags |= drawn;
18412
18413            mBackgroundSizeChanged = true;
18414            if (mForegroundInfo != null) {
18415                mForegroundInfo.mBoundsChanged = true;
18416            }
18417
18418            notifySubtreeAccessibilityStateChangedIfNeeded();
18419        }
18420        return changed;
18421    }
18422
18423    /**
18424     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
18425     * @hide
18426     */
18427    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
18428        setFrame(left, top, right, bottom);
18429    }
18430
18431    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
18432        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
18433        if (mOverlay != null) {
18434            mOverlay.getOverlayView().setRight(newWidth);
18435            mOverlay.getOverlayView().setBottom(newHeight);
18436        }
18437        rebuildOutline();
18438    }
18439
18440    /**
18441     * Finalize inflating a view from XML.  This is called as the last phase
18442     * of inflation, after all child views have been added.
18443     *
18444     * <p>Even if the subclass overrides onFinishInflate, they should always be
18445     * sure to call the super method, so that we get called.
18446     */
18447    @CallSuper
18448    protected void onFinishInflate() {
18449    }
18450
18451    /**
18452     * Returns the resources associated with this view.
18453     *
18454     * @return Resources object.
18455     */
18456    public Resources getResources() {
18457        return mResources;
18458    }
18459
18460    /**
18461     * Invalidates the specified Drawable.
18462     *
18463     * @param drawable the drawable to invalidate
18464     */
18465    @Override
18466    public void invalidateDrawable(@NonNull Drawable drawable) {
18467        if (verifyDrawable(drawable)) {
18468            final Rect dirty = drawable.getDirtyBounds();
18469            final int scrollX = mScrollX;
18470            final int scrollY = mScrollY;
18471
18472            invalidate(dirty.left + scrollX, dirty.top + scrollY,
18473                    dirty.right + scrollX, dirty.bottom + scrollY);
18474            rebuildOutline();
18475        }
18476    }
18477
18478    /**
18479     * Schedules an action on a drawable to occur at a specified time.
18480     *
18481     * @param who the recipient of the action
18482     * @param what the action to run on the drawable
18483     * @param when the time at which the action must occur. Uses the
18484     *        {@link SystemClock#uptimeMillis} timebase.
18485     */
18486    @Override
18487    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
18488        if (verifyDrawable(who) && what != null) {
18489            final long delay = when - SystemClock.uptimeMillis();
18490            if (mAttachInfo != null) {
18491                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
18492                        Choreographer.CALLBACK_ANIMATION, what, who,
18493                        Choreographer.subtractFrameDelay(delay));
18494            } else {
18495                // Postpone the runnable until we know
18496                // on which thread it needs to run.
18497                getRunQueue().postDelayed(what, delay);
18498            }
18499        }
18500    }
18501
18502    /**
18503     * Cancels a scheduled action on a drawable.
18504     *
18505     * @param who the recipient of the action
18506     * @param what the action to cancel
18507     */
18508    @Override
18509    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
18510        if (verifyDrawable(who) && what != null) {
18511            if (mAttachInfo != null) {
18512                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18513                        Choreographer.CALLBACK_ANIMATION, what, who);
18514            }
18515            getRunQueue().removeCallbacks(what);
18516        }
18517    }
18518
18519    /**
18520     * Unschedule any events associated with the given Drawable.  This can be
18521     * used when selecting a new Drawable into a view, so that the previous
18522     * one is completely unscheduled.
18523     *
18524     * @param who The Drawable to unschedule.
18525     *
18526     * @see #drawableStateChanged
18527     */
18528    public void unscheduleDrawable(Drawable who) {
18529        if (mAttachInfo != null && who != null) {
18530            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18531                    Choreographer.CALLBACK_ANIMATION, null, who);
18532        }
18533    }
18534
18535    /**
18536     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
18537     * that the View directionality can and will be resolved before its Drawables.
18538     *
18539     * Will call {@link View#onResolveDrawables} when resolution is done.
18540     *
18541     * @hide
18542     */
18543    protected void resolveDrawables() {
18544        // Drawables resolution may need to happen before resolving the layout direction (which is
18545        // done only during the measure() call).
18546        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
18547        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
18548        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
18549        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
18550        // direction to be resolved as its resolved value will be the same as its raw value.
18551        if (!isLayoutDirectionResolved() &&
18552                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
18553            return;
18554        }
18555
18556        final int layoutDirection = isLayoutDirectionResolved() ?
18557                getLayoutDirection() : getRawLayoutDirection();
18558
18559        if (mBackground != null) {
18560            mBackground.setLayoutDirection(layoutDirection);
18561        }
18562        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18563            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
18564        }
18565        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
18566        onResolveDrawables(layoutDirection);
18567    }
18568
18569    boolean areDrawablesResolved() {
18570        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
18571    }
18572
18573    /**
18574     * Called when layout direction has been resolved.
18575     *
18576     * The default implementation does nothing.
18577     *
18578     * @param layoutDirection The resolved layout direction.
18579     *
18580     * @see #LAYOUT_DIRECTION_LTR
18581     * @see #LAYOUT_DIRECTION_RTL
18582     *
18583     * @hide
18584     */
18585    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
18586    }
18587
18588    /**
18589     * @hide
18590     */
18591    protected void resetResolvedDrawables() {
18592        resetResolvedDrawablesInternal();
18593    }
18594
18595    void resetResolvedDrawablesInternal() {
18596        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
18597    }
18598
18599    /**
18600     * If your view subclass is displaying its own Drawable objects, it should
18601     * override this function and return true for any Drawable it is
18602     * displaying.  This allows animations for those drawables to be
18603     * scheduled.
18604     *
18605     * <p>Be sure to call through to the super class when overriding this
18606     * function.
18607     *
18608     * @param who The Drawable to verify.  Return true if it is one you are
18609     *            displaying, else return the result of calling through to the
18610     *            super class.
18611     *
18612     * @return boolean If true than the Drawable is being displayed in the
18613     *         view; else false and it is not allowed to animate.
18614     *
18615     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
18616     * @see #drawableStateChanged()
18617     */
18618    @CallSuper
18619    protected boolean verifyDrawable(@NonNull Drawable who) {
18620        // Avoid verifying the scroll bar drawable so that we don't end up in
18621        // an invalidation loop. This effectively prevents the scroll bar
18622        // drawable from triggering invalidations and scheduling runnables.
18623        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
18624    }
18625
18626    /**
18627     * This function is called whenever the state of the view changes in such
18628     * a way that it impacts the state of drawables being shown.
18629     * <p>
18630     * If the View has a StateListAnimator, it will also be called to run necessary state
18631     * change animations.
18632     * <p>
18633     * Be sure to call through to the superclass when overriding this function.
18634     *
18635     * @see Drawable#setState(int[])
18636     */
18637    @CallSuper
18638    protected void drawableStateChanged() {
18639        final int[] state = getDrawableState();
18640        boolean changed = false;
18641
18642        final Drawable bg = mBackground;
18643        if (bg != null && bg.isStateful()) {
18644            changed |= bg.setState(state);
18645        }
18646
18647        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18648        if (fg != null && fg.isStateful()) {
18649            changed |= fg.setState(state);
18650        }
18651
18652        if (mScrollCache != null) {
18653            final Drawable scrollBar = mScrollCache.scrollBar;
18654            if (scrollBar != null && scrollBar.isStateful()) {
18655                changed |= scrollBar.setState(state)
18656                        && mScrollCache.state != ScrollabilityCache.OFF;
18657            }
18658        }
18659
18660        if (mStateListAnimator != null) {
18661            mStateListAnimator.setState(state);
18662        }
18663
18664        if (changed) {
18665            invalidate();
18666        }
18667    }
18668
18669    /**
18670     * This function is called whenever the view hotspot changes and needs to
18671     * be propagated to drawables or child views managed by the view.
18672     * <p>
18673     * Dispatching to child views is handled by
18674     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18675     * <p>
18676     * Be sure to call through to the superclass when overriding this function.
18677     *
18678     * @param x hotspot x coordinate
18679     * @param y hotspot y coordinate
18680     */
18681    @CallSuper
18682    public void drawableHotspotChanged(float x, float y) {
18683        if (mBackground != null) {
18684            mBackground.setHotspot(x, y);
18685        }
18686        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18687            mForegroundInfo.mDrawable.setHotspot(x, y);
18688        }
18689
18690        dispatchDrawableHotspotChanged(x, y);
18691    }
18692
18693    /**
18694     * Dispatches drawableHotspotChanged to all of this View's children.
18695     *
18696     * @param x hotspot x coordinate
18697     * @param y hotspot y coordinate
18698     * @see #drawableHotspotChanged(float, float)
18699     */
18700    public void dispatchDrawableHotspotChanged(float x, float y) {
18701    }
18702
18703    /**
18704     * Call this to force a view to update its drawable state. This will cause
18705     * drawableStateChanged to be called on this view. Views that are interested
18706     * in the new state should call getDrawableState.
18707     *
18708     * @see #drawableStateChanged
18709     * @see #getDrawableState
18710     */
18711    public void refreshDrawableState() {
18712        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18713        drawableStateChanged();
18714
18715        ViewParent parent = mParent;
18716        if (parent != null) {
18717            parent.childDrawableStateChanged(this);
18718        }
18719    }
18720
18721    /**
18722     * Return an array of resource IDs of the drawable states representing the
18723     * current state of the view.
18724     *
18725     * @return The current drawable state
18726     *
18727     * @see Drawable#setState(int[])
18728     * @see #drawableStateChanged()
18729     * @see #onCreateDrawableState(int)
18730     */
18731    public final int[] getDrawableState() {
18732        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
18733            return mDrawableState;
18734        } else {
18735            mDrawableState = onCreateDrawableState(0);
18736            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
18737            return mDrawableState;
18738        }
18739    }
18740
18741    /**
18742     * Generate the new {@link android.graphics.drawable.Drawable} state for
18743     * this view. This is called by the view
18744     * system when the cached Drawable state is determined to be invalid.  To
18745     * retrieve the current state, you should use {@link #getDrawableState}.
18746     *
18747     * @param extraSpace if non-zero, this is the number of extra entries you
18748     * would like in the returned array in which you can place your own
18749     * states.
18750     *
18751     * @return Returns an array holding the current {@link Drawable} state of
18752     * the view.
18753     *
18754     * @see #mergeDrawableStates(int[], int[])
18755     */
18756    protected int[] onCreateDrawableState(int extraSpace) {
18757        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
18758                mParent instanceof View) {
18759            return ((View) mParent).onCreateDrawableState(extraSpace);
18760        }
18761
18762        int[] drawableState;
18763
18764        int privateFlags = mPrivateFlags;
18765
18766        int viewStateIndex = 0;
18767        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
18768        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
18769        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
18770        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
18771        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
18772        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
18773        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
18774                ThreadedRenderer.isAvailable()) {
18775            // This is set if HW acceleration is requested, even if the current
18776            // process doesn't allow it.  This is just to allow app preview
18777            // windows to better match their app.
18778            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
18779        }
18780        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
18781
18782        final int privateFlags2 = mPrivateFlags2;
18783        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
18784            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
18785        }
18786        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
18787            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
18788        }
18789
18790        drawableState = StateSet.get(viewStateIndex);
18791
18792        //noinspection ConstantIfStatement
18793        if (false) {
18794            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18795            Log.i("View", toString()
18796                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18797                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18798                    + " fo=" + hasFocus()
18799                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18800                    + " wf=" + hasWindowFocus()
18801                    + ": " + Arrays.toString(drawableState));
18802        }
18803
18804        if (extraSpace == 0) {
18805            return drawableState;
18806        }
18807
18808        final int[] fullState;
18809        if (drawableState != null) {
18810            fullState = new int[drawableState.length + extraSpace];
18811            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18812        } else {
18813            fullState = new int[extraSpace];
18814        }
18815
18816        return fullState;
18817    }
18818
18819    /**
18820     * Merge your own state values in <var>additionalState</var> into the base
18821     * state values <var>baseState</var> that were returned by
18822     * {@link #onCreateDrawableState(int)}.
18823     *
18824     * @param baseState The base state values returned by
18825     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18826     * own additional state values.
18827     *
18828     * @param additionalState The additional state values you would like
18829     * added to <var>baseState</var>; this array is not modified.
18830     *
18831     * @return As a convenience, the <var>baseState</var> array you originally
18832     * passed into the function is returned.
18833     *
18834     * @see #onCreateDrawableState(int)
18835     */
18836    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18837        final int N = baseState.length;
18838        int i = N - 1;
18839        while (i >= 0 && baseState[i] == 0) {
18840            i--;
18841        }
18842        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18843        return baseState;
18844    }
18845
18846    /**
18847     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18848     * on all Drawable objects associated with this view.
18849     * <p>
18850     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18851     * attached to this view.
18852     */
18853    @CallSuper
18854    public void jumpDrawablesToCurrentState() {
18855        if (mBackground != null) {
18856            mBackground.jumpToCurrentState();
18857        }
18858        if (mStateListAnimator != null) {
18859            mStateListAnimator.jumpToCurrentState();
18860        }
18861        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18862            mForegroundInfo.mDrawable.jumpToCurrentState();
18863        }
18864    }
18865
18866    /**
18867     * Sets the background color for this view.
18868     * @param color the color of the background
18869     */
18870    @RemotableViewMethod
18871    public void setBackgroundColor(@ColorInt int color) {
18872        if (mBackground instanceof ColorDrawable) {
18873            ((ColorDrawable) mBackground.mutate()).setColor(color);
18874            computeOpaqueFlags();
18875            mBackgroundResource = 0;
18876        } else {
18877            setBackground(new ColorDrawable(color));
18878        }
18879    }
18880
18881    /**
18882     * Set the background to a given resource. The resource should refer to
18883     * a Drawable object or 0 to remove the background.
18884     * @param resid The identifier of the resource.
18885     *
18886     * @attr ref android.R.styleable#View_background
18887     */
18888    @RemotableViewMethod
18889    public void setBackgroundResource(@DrawableRes int resid) {
18890        if (resid != 0 && resid == mBackgroundResource) {
18891            return;
18892        }
18893
18894        Drawable d = null;
18895        if (resid != 0) {
18896            d = mContext.getDrawable(resid);
18897        }
18898        setBackground(d);
18899
18900        mBackgroundResource = resid;
18901    }
18902
18903    /**
18904     * Set the background to a given Drawable, or remove the background. If the
18905     * background has padding, this View's padding is set to the background's
18906     * padding. However, when a background is removed, this View's padding isn't
18907     * touched. If setting the padding is desired, please use
18908     * {@link #setPadding(int, int, int, int)}.
18909     *
18910     * @param background The Drawable to use as the background, or null to remove the
18911     *        background
18912     */
18913    public void setBackground(Drawable background) {
18914        //noinspection deprecation
18915        setBackgroundDrawable(background);
18916    }
18917
18918    /**
18919     * @deprecated use {@link #setBackground(Drawable)} instead
18920     */
18921    @Deprecated
18922    public void setBackgroundDrawable(Drawable background) {
18923        computeOpaqueFlags();
18924
18925        if (background == mBackground) {
18926            return;
18927        }
18928
18929        boolean requestLayout = false;
18930
18931        mBackgroundResource = 0;
18932
18933        /*
18934         * Regardless of whether we're setting a new background or not, we want
18935         * to clear the previous drawable. setVisible first while we still have the callback set.
18936         */
18937        if (mBackground != null) {
18938            if (isAttachedToWindow()) {
18939                mBackground.setVisible(false, false);
18940            }
18941            mBackground.setCallback(null);
18942            unscheduleDrawable(mBackground);
18943        }
18944
18945        if (background != null) {
18946            Rect padding = sThreadLocal.get();
18947            if (padding == null) {
18948                padding = new Rect();
18949                sThreadLocal.set(padding);
18950            }
18951            resetResolvedDrawablesInternal();
18952            background.setLayoutDirection(getLayoutDirection());
18953            if (background.getPadding(padding)) {
18954                resetResolvedPaddingInternal();
18955                switch (background.getLayoutDirection()) {
18956                    case LAYOUT_DIRECTION_RTL:
18957                        mUserPaddingLeftInitial = padding.right;
18958                        mUserPaddingRightInitial = padding.left;
18959                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18960                        break;
18961                    case LAYOUT_DIRECTION_LTR:
18962                    default:
18963                        mUserPaddingLeftInitial = padding.left;
18964                        mUserPaddingRightInitial = padding.right;
18965                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18966                }
18967                mLeftPaddingDefined = false;
18968                mRightPaddingDefined = false;
18969            }
18970
18971            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18972            // if it has a different minimum size, we should layout again
18973            if (mBackground == null
18974                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18975                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18976                requestLayout = true;
18977            }
18978
18979            // Set mBackground before we set this as the callback and start making other
18980            // background drawable state change calls. In particular, the setVisible call below
18981            // can result in drawables attempting to start animations or otherwise invalidate,
18982            // which requires the view set as the callback (us) to recognize the drawable as
18983            // belonging to it as per verifyDrawable.
18984            mBackground = background;
18985            if (background.isStateful()) {
18986                background.setState(getDrawableState());
18987            }
18988            if (isAttachedToWindow()) {
18989                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18990            }
18991
18992            applyBackgroundTint();
18993
18994            // Set callback last, since the view may still be initializing.
18995            background.setCallback(this);
18996
18997            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18998                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18999                requestLayout = true;
19000            }
19001        } else {
19002            /* Remove the background */
19003            mBackground = null;
19004            if ((mViewFlags & WILL_NOT_DRAW) != 0
19005                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
19006                mPrivateFlags |= PFLAG_SKIP_DRAW;
19007            }
19008
19009            /*
19010             * When the background is set, we try to apply its padding to this
19011             * View. When the background is removed, we don't touch this View's
19012             * padding. This is noted in the Javadocs. Hence, we don't need to
19013             * requestLayout(), the invalidate() below is sufficient.
19014             */
19015
19016            // The old background's minimum size could have affected this
19017            // View's layout, so let's requestLayout
19018            requestLayout = true;
19019        }
19020
19021        computeOpaqueFlags();
19022
19023        if (requestLayout) {
19024            requestLayout();
19025        }
19026
19027        mBackgroundSizeChanged = true;
19028        invalidate(true);
19029        invalidateOutline();
19030    }
19031
19032    /**
19033     * Gets the background drawable
19034     *
19035     * @return The drawable used as the background for this view, if any.
19036     *
19037     * @see #setBackground(Drawable)
19038     *
19039     * @attr ref android.R.styleable#View_background
19040     */
19041    public Drawable getBackground() {
19042        return mBackground;
19043    }
19044
19045    /**
19046     * Applies a tint to the background drawable. Does not modify the current tint
19047     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19048     * <p>
19049     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
19050     * mutate the drawable and apply the specified tint and tint mode using
19051     * {@link Drawable#setTintList(ColorStateList)}.
19052     *
19053     * @param tint the tint to apply, may be {@code null} to clear tint
19054     *
19055     * @attr ref android.R.styleable#View_backgroundTint
19056     * @see #getBackgroundTintList()
19057     * @see Drawable#setTintList(ColorStateList)
19058     */
19059    public void setBackgroundTintList(@Nullable ColorStateList tint) {
19060        if (mBackgroundTint == null) {
19061            mBackgroundTint = new TintInfo();
19062        }
19063        mBackgroundTint.mTintList = tint;
19064        mBackgroundTint.mHasTintList = true;
19065
19066        applyBackgroundTint();
19067    }
19068
19069    /**
19070     * Return the tint applied to the background drawable, if specified.
19071     *
19072     * @return the tint applied to the background drawable
19073     * @attr ref android.R.styleable#View_backgroundTint
19074     * @see #setBackgroundTintList(ColorStateList)
19075     */
19076    @Nullable
19077    public ColorStateList getBackgroundTintList() {
19078        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
19079    }
19080
19081    /**
19082     * Specifies the blending mode used to apply the tint specified by
19083     * {@link #setBackgroundTintList(ColorStateList)}} to the background
19084     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19085     *
19086     * @param tintMode the blending mode used to apply the tint, may be
19087     *                 {@code null} to clear tint
19088     * @attr ref android.R.styleable#View_backgroundTintMode
19089     * @see #getBackgroundTintMode()
19090     * @see Drawable#setTintMode(PorterDuff.Mode)
19091     */
19092    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19093        if (mBackgroundTint == null) {
19094            mBackgroundTint = new TintInfo();
19095        }
19096        mBackgroundTint.mTintMode = tintMode;
19097        mBackgroundTint.mHasTintMode = true;
19098
19099        applyBackgroundTint();
19100    }
19101
19102    /**
19103     * Return the blending mode used to apply the tint to the background
19104     * drawable, if specified.
19105     *
19106     * @return the blending mode used to apply the tint to the background
19107     *         drawable
19108     * @attr ref android.R.styleable#View_backgroundTintMode
19109     * @see #setBackgroundTintMode(PorterDuff.Mode)
19110     */
19111    @Nullable
19112    public PorterDuff.Mode getBackgroundTintMode() {
19113        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
19114    }
19115
19116    private void applyBackgroundTint() {
19117        if (mBackground != null && mBackgroundTint != null) {
19118            final TintInfo tintInfo = mBackgroundTint;
19119            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19120                mBackground = mBackground.mutate();
19121
19122                if (tintInfo.mHasTintList) {
19123                    mBackground.setTintList(tintInfo.mTintList);
19124                }
19125
19126                if (tintInfo.mHasTintMode) {
19127                    mBackground.setTintMode(tintInfo.mTintMode);
19128                }
19129
19130                // The drawable (or one of its children) may not have been
19131                // stateful before applying the tint, so let's try again.
19132                if (mBackground.isStateful()) {
19133                    mBackground.setState(getDrawableState());
19134                }
19135            }
19136        }
19137    }
19138
19139    /**
19140     * Returns the drawable used as the foreground of this View. The
19141     * foreground drawable, if non-null, is always drawn on top of the view's content.
19142     *
19143     * @return a Drawable or null if no foreground was set
19144     *
19145     * @see #onDrawForeground(Canvas)
19146     */
19147    public Drawable getForeground() {
19148        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19149    }
19150
19151    /**
19152     * Supply a Drawable that is to be rendered on top of all of the content in the view.
19153     *
19154     * @param foreground the Drawable to be drawn on top of the children
19155     *
19156     * @attr ref android.R.styleable#View_foreground
19157     */
19158    public void setForeground(Drawable foreground) {
19159        if (mForegroundInfo == null) {
19160            if (foreground == null) {
19161                // Nothing to do.
19162                return;
19163            }
19164            mForegroundInfo = new ForegroundInfo();
19165        }
19166
19167        if (foreground == mForegroundInfo.mDrawable) {
19168            // Nothing to do
19169            return;
19170        }
19171
19172        if (mForegroundInfo.mDrawable != null) {
19173            if (isAttachedToWindow()) {
19174                mForegroundInfo.mDrawable.setVisible(false, false);
19175            }
19176            mForegroundInfo.mDrawable.setCallback(null);
19177            unscheduleDrawable(mForegroundInfo.mDrawable);
19178        }
19179
19180        mForegroundInfo.mDrawable = foreground;
19181        mForegroundInfo.mBoundsChanged = true;
19182        if (foreground != null) {
19183            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19184                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19185            }
19186            foreground.setLayoutDirection(getLayoutDirection());
19187            if (foreground.isStateful()) {
19188                foreground.setState(getDrawableState());
19189            }
19190            applyForegroundTint();
19191            if (isAttachedToWindow()) {
19192                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19193            }
19194            // Set callback last, since the view may still be initializing.
19195            foreground.setCallback(this);
19196        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
19197            mPrivateFlags |= PFLAG_SKIP_DRAW;
19198        }
19199        requestLayout();
19200        invalidate();
19201    }
19202
19203    /**
19204     * Magic bit used to support features of framework-internal window decor implementation details.
19205     * This used to live exclusively in FrameLayout.
19206     *
19207     * @return true if the foreground should draw inside the padding region or false
19208     *         if it should draw inset by the view's padding
19209     * @hide internal use only; only used by FrameLayout and internal screen layouts.
19210     */
19211    public boolean isForegroundInsidePadding() {
19212        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
19213    }
19214
19215    /**
19216     * Describes how the foreground is positioned.
19217     *
19218     * @return foreground gravity.
19219     *
19220     * @see #setForegroundGravity(int)
19221     *
19222     * @attr ref android.R.styleable#View_foregroundGravity
19223     */
19224    public int getForegroundGravity() {
19225        return mForegroundInfo != null ? mForegroundInfo.mGravity
19226                : Gravity.START | Gravity.TOP;
19227    }
19228
19229    /**
19230     * Describes how the foreground is positioned. Defaults to START and TOP.
19231     *
19232     * @param gravity see {@link android.view.Gravity}
19233     *
19234     * @see #getForegroundGravity()
19235     *
19236     * @attr ref android.R.styleable#View_foregroundGravity
19237     */
19238    public void setForegroundGravity(int gravity) {
19239        if (mForegroundInfo == null) {
19240            mForegroundInfo = new ForegroundInfo();
19241        }
19242
19243        if (mForegroundInfo.mGravity != gravity) {
19244            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
19245                gravity |= Gravity.START;
19246            }
19247
19248            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
19249                gravity |= Gravity.TOP;
19250            }
19251
19252            mForegroundInfo.mGravity = gravity;
19253            requestLayout();
19254        }
19255    }
19256
19257    /**
19258     * Applies a tint to the foreground drawable. Does not modify the current tint
19259     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19260     * <p>
19261     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
19262     * mutate the drawable and apply the specified tint and tint mode using
19263     * {@link Drawable#setTintList(ColorStateList)}.
19264     *
19265     * @param tint the tint to apply, may be {@code null} to clear tint
19266     *
19267     * @attr ref android.R.styleable#View_foregroundTint
19268     * @see #getForegroundTintList()
19269     * @see Drawable#setTintList(ColorStateList)
19270     */
19271    public void setForegroundTintList(@Nullable ColorStateList tint) {
19272        if (mForegroundInfo == null) {
19273            mForegroundInfo = new ForegroundInfo();
19274        }
19275        if (mForegroundInfo.mTintInfo == null) {
19276            mForegroundInfo.mTintInfo = new TintInfo();
19277        }
19278        mForegroundInfo.mTintInfo.mTintList = tint;
19279        mForegroundInfo.mTintInfo.mHasTintList = true;
19280
19281        applyForegroundTint();
19282    }
19283
19284    /**
19285     * Return the tint applied to the foreground drawable, if specified.
19286     *
19287     * @return the tint applied to the foreground drawable
19288     * @attr ref android.R.styleable#View_foregroundTint
19289     * @see #setForegroundTintList(ColorStateList)
19290     */
19291    @Nullable
19292    public ColorStateList getForegroundTintList() {
19293        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19294                ? mForegroundInfo.mTintInfo.mTintList : null;
19295    }
19296
19297    /**
19298     * Specifies the blending mode used to apply the tint specified by
19299     * {@link #setForegroundTintList(ColorStateList)}} to the background
19300     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19301     *
19302     * @param tintMode the blending mode used to apply the tint, may be
19303     *                 {@code null} to clear tint
19304     * @attr ref android.R.styleable#View_foregroundTintMode
19305     * @see #getForegroundTintMode()
19306     * @see Drawable#setTintMode(PorterDuff.Mode)
19307     */
19308    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19309        if (mForegroundInfo == null) {
19310            mForegroundInfo = new ForegroundInfo();
19311        }
19312        if (mForegroundInfo.mTintInfo == null) {
19313            mForegroundInfo.mTintInfo = new TintInfo();
19314        }
19315        mForegroundInfo.mTintInfo.mTintMode = tintMode;
19316        mForegroundInfo.mTintInfo.mHasTintMode = true;
19317
19318        applyForegroundTint();
19319    }
19320
19321    /**
19322     * Return the blending mode used to apply the tint to the foreground
19323     * drawable, if specified.
19324     *
19325     * @return the blending mode used to apply the tint to the foreground
19326     *         drawable
19327     * @attr ref android.R.styleable#View_foregroundTintMode
19328     * @see #setForegroundTintMode(PorterDuff.Mode)
19329     */
19330    @Nullable
19331    public PorterDuff.Mode getForegroundTintMode() {
19332        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19333                ? mForegroundInfo.mTintInfo.mTintMode : null;
19334    }
19335
19336    private void applyForegroundTint() {
19337        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
19338                && mForegroundInfo.mTintInfo != null) {
19339            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
19340            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19341                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
19342
19343                if (tintInfo.mHasTintList) {
19344                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
19345                }
19346
19347                if (tintInfo.mHasTintMode) {
19348                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
19349                }
19350
19351                // The drawable (or one of its children) may not have been
19352                // stateful before applying the tint, so let's try again.
19353                if (mForegroundInfo.mDrawable.isStateful()) {
19354                    mForegroundInfo.mDrawable.setState(getDrawableState());
19355                }
19356            }
19357        }
19358    }
19359
19360    /**
19361     * Draw any foreground content for this view.
19362     *
19363     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
19364     * drawable or other view-specific decorations. The foreground is drawn on top of the
19365     * primary view content.</p>
19366     *
19367     * @param canvas canvas to draw into
19368     */
19369    public void onDrawForeground(Canvas canvas) {
19370        onDrawScrollIndicators(canvas);
19371        onDrawScrollBars(canvas);
19372
19373        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19374        if (foreground != null) {
19375            if (mForegroundInfo.mBoundsChanged) {
19376                mForegroundInfo.mBoundsChanged = false;
19377                final Rect selfBounds = mForegroundInfo.mSelfBounds;
19378                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
19379
19380                if (mForegroundInfo.mInsidePadding) {
19381                    selfBounds.set(0, 0, getWidth(), getHeight());
19382                } else {
19383                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
19384                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
19385                }
19386
19387                final int ld = getLayoutDirection();
19388                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
19389                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
19390                foreground.setBounds(overlayBounds);
19391            }
19392
19393            foreground.draw(canvas);
19394        }
19395    }
19396
19397    /**
19398     * Sets the padding. The view may add on the space required to display
19399     * the scrollbars, depending on the style and visibility of the scrollbars.
19400     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
19401     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
19402     * from the values set in this call.
19403     *
19404     * @attr ref android.R.styleable#View_padding
19405     * @attr ref android.R.styleable#View_paddingBottom
19406     * @attr ref android.R.styleable#View_paddingLeft
19407     * @attr ref android.R.styleable#View_paddingRight
19408     * @attr ref android.R.styleable#View_paddingTop
19409     * @param left the left padding in pixels
19410     * @param top the top padding in pixels
19411     * @param right the right padding in pixels
19412     * @param bottom the bottom padding in pixels
19413     */
19414    public void setPadding(int left, int top, int right, int bottom) {
19415        resetResolvedPaddingInternal();
19416
19417        mUserPaddingStart = UNDEFINED_PADDING;
19418        mUserPaddingEnd = UNDEFINED_PADDING;
19419
19420        mUserPaddingLeftInitial = left;
19421        mUserPaddingRightInitial = right;
19422
19423        mLeftPaddingDefined = true;
19424        mRightPaddingDefined = true;
19425
19426        internalSetPadding(left, top, right, bottom);
19427    }
19428
19429    /**
19430     * @hide
19431     */
19432    protected void internalSetPadding(int left, int top, int right, int bottom) {
19433        mUserPaddingLeft = left;
19434        mUserPaddingRight = right;
19435        mUserPaddingBottom = bottom;
19436
19437        final int viewFlags = mViewFlags;
19438        boolean changed = false;
19439
19440        // Common case is there are no scroll bars.
19441        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
19442            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
19443                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
19444                        ? 0 : getVerticalScrollbarWidth();
19445                switch (mVerticalScrollbarPosition) {
19446                    case SCROLLBAR_POSITION_DEFAULT:
19447                        if (isLayoutRtl()) {
19448                            left += offset;
19449                        } else {
19450                            right += offset;
19451                        }
19452                        break;
19453                    case SCROLLBAR_POSITION_RIGHT:
19454                        right += offset;
19455                        break;
19456                    case SCROLLBAR_POSITION_LEFT:
19457                        left += offset;
19458                        break;
19459                }
19460            }
19461            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
19462                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
19463                        ? 0 : getHorizontalScrollbarHeight();
19464            }
19465        }
19466
19467        if (mPaddingLeft != left) {
19468            changed = true;
19469            mPaddingLeft = left;
19470        }
19471        if (mPaddingTop != top) {
19472            changed = true;
19473            mPaddingTop = top;
19474        }
19475        if (mPaddingRight != right) {
19476            changed = true;
19477            mPaddingRight = right;
19478        }
19479        if (mPaddingBottom != bottom) {
19480            changed = true;
19481            mPaddingBottom = bottom;
19482        }
19483
19484        if (changed) {
19485            requestLayout();
19486            invalidateOutline();
19487        }
19488    }
19489
19490    /**
19491     * Sets the relative padding. The view may add on the space required to display
19492     * the scrollbars, depending on the style and visibility of the scrollbars.
19493     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
19494     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
19495     * from the values set in this call.
19496     *
19497     * @attr ref android.R.styleable#View_padding
19498     * @attr ref android.R.styleable#View_paddingBottom
19499     * @attr ref android.R.styleable#View_paddingStart
19500     * @attr ref android.R.styleable#View_paddingEnd
19501     * @attr ref android.R.styleable#View_paddingTop
19502     * @param start the start padding in pixels
19503     * @param top the top padding in pixels
19504     * @param end the end padding in pixels
19505     * @param bottom the bottom padding in pixels
19506     */
19507    public void setPaddingRelative(int start, int top, int end, int bottom) {
19508        resetResolvedPaddingInternal();
19509
19510        mUserPaddingStart = start;
19511        mUserPaddingEnd = end;
19512        mLeftPaddingDefined = true;
19513        mRightPaddingDefined = true;
19514
19515        switch(getLayoutDirection()) {
19516            case LAYOUT_DIRECTION_RTL:
19517                mUserPaddingLeftInitial = end;
19518                mUserPaddingRightInitial = start;
19519                internalSetPadding(end, top, start, bottom);
19520                break;
19521            case LAYOUT_DIRECTION_LTR:
19522            default:
19523                mUserPaddingLeftInitial = start;
19524                mUserPaddingRightInitial = end;
19525                internalSetPadding(start, top, end, bottom);
19526        }
19527    }
19528
19529    /**
19530     * Returns the top padding of this view.
19531     *
19532     * @return the top padding in pixels
19533     */
19534    public int getPaddingTop() {
19535        return mPaddingTop;
19536    }
19537
19538    /**
19539     * Returns the bottom padding of this view. If there are inset and enabled
19540     * scrollbars, this value may include the space required to display the
19541     * scrollbars as well.
19542     *
19543     * @return the bottom padding in pixels
19544     */
19545    public int getPaddingBottom() {
19546        return mPaddingBottom;
19547    }
19548
19549    /**
19550     * Returns the left padding of this view. If there are inset and enabled
19551     * scrollbars, this value may include the space required to display the
19552     * scrollbars as well.
19553     *
19554     * @return the left padding in pixels
19555     */
19556    public int getPaddingLeft() {
19557        if (!isPaddingResolved()) {
19558            resolvePadding();
19559        }
19560        return mPaddingLeft;
19561    }
19562
19563    /**
19564     * Returns the start padding of this view depending on its resolved layout direction.
19565     * If there are inset and enabled scrollbars, this value may include the space
19566     * required to display the scrollbars as well.
19567     *
19568     * @return the start padding in pixels
19569     */
19570    public int getPaddingStart() {
19571        if (!isPaddingResolved()) {
19572            resolvePadding();
19573        }
19574        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19575                mPaddingRight : mPaddingLeft;
19576    }
19577
19578    /**
19579     * Returns the right padding of this view. If there are inset and enabled
19580     * scrollbars, this value may include the space required to display the
19581     * scrollbars as well.
19582     *
19583     * @return the right padding in pixels
19584     */
19585    public int getPaddingRight() {
19586        if (!isPaddingResolved()) {
19587            resolvePadding();
19588        }
19589        return mPaddingRight;
19590    }
19591
19592    /**
19593     * Returns the end padding of this view depending on its resolved layout direction.
19594     * If there are inset and enabled scrollbars, this value may include the space
19595     * required to display the scrollbars as well.
19596     *
19597     * @return the end padding in pixels
19598     */
19599    public int getPaddingEnd() {
19600        if (!isPaddingResolved()) {
19601            resolvePadding();
19602        }
19603        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19604                mPaddingLeft : mPaddingRight;
19605    }
19606
19607    /**
19608     * Return if the padding has been set through relative values
19609     * {@link #setPaddingRelative(int, int, int, int)} or through
19610     * @attr ref android.R.styleable#View_paddingStart or
19611     * @attr ref android.R.styleable#View_paddingEnd
19612     *
19613     * @return true if the padding is relative or false if it is not.
19614     */
19615    public boolean isPaddingRelative() {
19616        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
19617    }
19618
19619    Insets computeOpticalInsets() {
19620        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
19621    }
19622
19623    /**
19624     * @hide
19625     */
19626    public void resetPaddingToInitialValues() {
19627        if (isRtlCompatibilityMode()) {
19628            mPaddingLeft = mUserPaddingLeftInitial;
19629            mPaddingRight = mUserPaddingRightInitial;
19630            return;
19631        }
19632        if (isLayoutRtl()) {
19633            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
19634            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
19635        } else {
19636            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
19637            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
19638        }
19639    }
19640
19641    /**
19642     * @hide
19643     */
19644    public Insets getOpticalInsets() {
19645        if (mLayoutInsets == null) {
19646            mLayoutInsets = computeOpticalInsets();
19647        }
19648        return mLayoutInsets;
19649    }
19650
19651    /**
19652     * Set this view's optical insets.
19653     *
19654     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
19655     * property. Views that compute their own optical insets should call it as part of measurement.
19656     * This method does not request layout. If you are setting optical insets outside of
19657     * measure/layout itself you will want to call requestLayout() yourself.
19658     * </p>
19659     * @hide
19660     */
19661    public void setOpticalInsets(Insets insets) {
19662        mLayoutInsets = insets;
19663    }
19664
19665    /**
19666     * Changes the selection state of this view. A view can be selected or not.
19667     * Note that selection is not the same as focus. Views are typically
19668     * selected in the context of an AdapterView like ListView or GridView;
19669     * the selected view is the view that is highlighted.
19670     *
19671     * @param selected true if the view must be selected, false otherwise
19672     */
19673    public void setSelected(boolean selected) {
19674        //noinspection DoubleNegation
19675        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19676            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19677            if (!selected) resetPressedState();
19678            invalidate(true);
19679            refreshDrawableState();
19680            dispatchSetSelected(selected);
19681            if (selected) {
19682                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19683            } else {
19684                notifyViewAccessibilityStateChangedIfNeeded(
19685                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19686            }
19687        }
19688    }
19689
19690    /**
19691     * Dispatch setSelected to all of this View's children.
19692     *
19693     * @see #setSelected(boolean)
19694     *
19695     * @param selected The new selected state
19696     */
19697    protected void dispatchSetSelected(boolean selected) {
19698    }
19699
19700    /**
19701     * Indicates the selection state of this view.
19702     *
19703     * @return true if the view is selected, false otherwise
19704     */
19705    @ViewDebug.ExportedProperty
19706    public boolean isSelected() {
19707        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19708    }
19709
19710    /**
19711     * Changes the activated state of this view. A view can be activated or not.
19712     * Note that activation is not the same as selection.  Selection is
19713     * a transient property, representing the view (hierarchy) the user is
19714     * currently interacting with.  Activation is a longer-term state that the
19715     * user can move views in and out of.  For example, in a list view with
19716     * single or multiple selection enabled, the views in the current selection
19717     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19718     * here.)  The activated state is propagated down to children of the view it
19719     * is set on.
19720     *
19721     * @param activated true if the view must be activated, false otherwise
19722     */
19723    public void setActivated(boolean activated) {
19724        //noinspection DoubleNegation
19725        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19726            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19727            invalidate(true);
19728            refreshDrawableState();
19729            dispatchSetActivated(activated);
19730        }
19731    }
19732
19733    /**
19734     * Dispatch setActivated to all of this View's children.
19735     *
19736     * @see #setActivated(boolean)
19737     *
19738     * @param activated The new activated state
19739     */
19740    protected void dispatchSetActivated(boolean activated) {
19741    }
19742
19743    /**
19744     * Indicates the activation state of this view.
19745     *
19746     * @return true if the view is activated, false otherwise
19747     */
19748    @ViewDebug.ExportedProperty
19749    public boolean isActivated() {
19750        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
19751    }
19752
19753    /**
19754     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
19755     * observer can be used to get notifications when global events, like
19756     * layout, happen.
19757     *
19758     * The returned ViewTreeObserver observer is not guaranteed to remain
19759     * valid for the lifetime of this View. If the caller of this method keeps
19760     * a long-lived reference to ViewTreeObserver, it should always check for
19761     * the return value of {@link ViewTreeObserver#isAlive()}.
19762     *
19763     * @return The ViewTreeObserver for this view's hierarchy.
19764     */
19765    public ViewTreeObserver getViewTreeObserver() {
19766        if (mAttachInfo != null) {
19767            return mAttachInfo.mTreeObserver;
19768        }
19769        if (mFloatingTreeObserver == null) {
19770            mFloatingTreeObserver = new ViewTreeObserver(mContext);
19771        }
19772        return mFloatingTreeObserver;
19773    }
19774
19775    /**
19776     * <p>Finds the topmost view in the current view hierarchy.</p>
19777     *
19778     * @return the topmost view containing this view
19779     */
19780    public View getRootView() {
19781        if (mAttachInfo != null) {
19782            final View v = mAttachInfo.mRootView;
19783            if (v != null) {
19784                return v;
19785            }
19786        }
19787
19788        View parent = this;
19789
19790        while (parent.mParent != null && parent.mParent instanceof View) {
19791            parent = (View) parent.mParent;
19792        }
19793
19794        return parent;
19795    }
19796
19797    /**
19798     * Transforms a motion event from view-local coordinates to on-screen
19799     * coordinates.
19800     *
19801     * @param ev the view-local motion event
19802     * @return false if the transformation could not be applied
19803     * @hide
19804     */
19805    public boolean toGlobalMotionEvent(MotionEvent ev) {
19806        final AttachInfo info = mAttachInfo;
19807        if (info == null) {
19808            return false;
19809        }
19810
19811        final Matrix m = info.mTmpMatrix;
19812        m.set(Matrix.IDENTITY_MATRIX);
19813        transformMatrixToGlobal(m);
19814        ev.transform(m);
19815        return true;
19816    }
19817
19818    /**
19819     * Transforms a motion event from on-screen coordinates to view-local
19820     * coordinates.
19821     *
19822     * @param ev the on-screen motion event
19823     * @return false if the transformation could not be applied
19824     * @hide
19825     */
19826    public boolean toLocalMotionEvent(MotionEvent ev) {
19827        final AttachInfo info = mAttachInfo;
19828        if (info == null) {
19829            return false;
19830        }
19831
19832        final Matrix m = info.mTmpMatrix;
19833        m.set(Matrix.IDENTITY_MATRIX);
19834        transformMatrixToLocal(m);
19835        ev.transform(m);
19836        return true;
19837    }
19838
19839    /**
19840     * Modifies the input matrix such that it maps view-local coordinates to
19841     * on-screen coordinates.
19842     *
19843     * @param m input matrix to modify
19844     * @hide
19845     */
19846    public void transformMatrixToGlobal(Matrix m) {
19847        final ViewParent parent = mParent;
19848        if (parent instanceof View) {
19849            final View vp = (View) parent;
19850            vp.transformMatrixToGlobal(m);
19851            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19852        } else if (parent instanceof ViewRootImpl) {
19853            final ViewRootImpl vr = (ViewRootImpl) parent;
19854            vr.transformMatrixToGlobal(m);
19855            m.preTranslate(0, -vr.mCurScrollY);
19856        }
19857
19858        m.preTranslate(mLeft, mTop);
19859
19860        if (!hasIdentityMatrix()) {
19861            m.preConcat(getMatrix());
19862        }
19863    }
19864
19865    /**
19866     * Modifies the input matrix such that it maps on-screen coordinates to
19867     * view-local coordinates.
19868     *
19869     * @param m input matrix to modify
19870     * @hide
19871     */
19872    public void transformMatrixToLocal(Matrix m) {
19873        final ViewParent parent = mParent;
19874        if (parent instanceof View) {
19875            final View vp = (View) parent;
19876            vp.transformMatrixToLocal(m);
19877            m.postTranslate(vp.mScrollX, vp.mScrollY);
19878        } else if (parent instanceof ViewRootImpl) {
19879            final ViewRootImpl vr = (ViewRootImpl) parent;
19880            vr.transformMatrixToLocal(m);
19881            m.postTranslate(0, vr.mCurScrollY);
19882        }
19883
19884        m.postTranslate(-mLeft, -mTop);
19885
19886        if (!hasIdentityMatrix()) {
19887            m.postConcat(getInverseMatrix());
19888        }
19889    }
19890
19891    /**
19892     * @hide
19893     */
19894    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19895            @ViewDebug.IntToString(from = 0, to = "x"),
19896            @ViewDebug.IntToString(from = 1, to = "y")
19897    })
19898    public int[] getLocationOnScreen() {
19899        int[] location = new int[2];
19900        getLocationOnScreen(location);
19901        return location;
19902    }
19903
19904    /**
19905     * <p>Computes the coordinates of this view on the screen. The argument
19906     * must be an array of two integers. After the method returns, the array
19907     * contains the x and y location in that order.</p>
19908     *
19909     * @param outLocation an array of two integers in which to hold the coordinates
19910     */
19911    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19912        getLocationInWindow(outLocation);
19913
19914        final AttachInfo info = mAttachInfo;
19915        if (info != null) {
19916            outLocation[0] += info.mWindowLeft;
19917            outLocation[1] += info.mWindowTop;
19918        }
19919    }
19920
19921    /**
19922     * <p>Computes the coordinates of this view in its window. The argument
19923     * must be an array of two integers. After the method returns, the array
19924     * contains the x and y location in that order.</p>
19925     *
19926     * @param outLocation an array of two integers in which to hold the coordinates
19927     */
19928    public void getLocationInWindow(@Size(2) int[] outLocation) {
19929        if (outLocation == null || outLocation.length < 2) {
19930            throw new IllegalArgumentException("outLocation must be an array of two integers");
19931        }
19932
19933        outLocation[0] = 0;
19934        outLocation[1] = 0;
19935
19936        transformFromViewToWindowSpace(outLocation);
19937    }
19938
19939    /** @hide */
19940    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19941        if (inOutLocation == null || inOutLocation.length < 2) {
19942            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19943        }
19944
19945        if (mAttachInfo == null) {
19946            // When the view is not attached to a window, this method does not make sense
19947            inOutLocation[0] = inOutLocation[1] = 0;
19948            return;
19949        }
19950
19951        float position[] = mAttachInfo.mTmpTransformLocation;
19952        position[0] = inOutLocation[0];
19953        position[1] = inOutLocation[1];
19954
19955        if (!hasIdentityMatrix()) {
19956            getMatrix().mapPoints(position);
19957        }
19958
19959        position[0] += mLeft;
19960        position[1] += mTop;
19961
19962        ViewParent viewParent = mParent;
19963        while (viewParent instanceof View) {
19964            final View view = (View) viewParent;
19965
19966            position[0] -= view.mScrollX;
19967            position[1] -= view.mScrollY;
19968
19969            if (!view.hasIdentityMatrix()) {
19970                view.getMatrix().mapPoints(position);
19971            }
19972
19973            position[0] += view.mLeft;
19974            position[1] += view.mTop;
19975
19976            viewParent = view.mParent;
19977         }
19978
19979        if (viewParent instanceof ViewRootImpl) {
19980            // *cough*
19981            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19982            position[1] -= vr.mCurScrollY;
19983        }
19984
19985        inOutLocation[0] = Math.round(position[0]);
19986        inOutLocation[1] = Math.round(position[1]);
19987    }
19988
19989    /**
19990     * @param id the id of the view to be found
19991     * @return the view of the specified id, null if cannot be found
19992     * @hide
19993     */
19994    protected <T extends View> T findViewTraversal(@IdRes int id) {
19995        if (id == mID) {
19996            return (T) this;
19997        }
19998        return null;
19999    }
20000
20001    /**
20002     * @param tag the tag of the view to be found
20003     * @return the view of specified tag, null if cannot be found
20004     * @hide
20005     */
20006    protected <T extends View> T findViewWithTagTraversal(Object tag) {
20007        if (tag != null && tag.equals(mTag)) {
20008            return (T) this;
20009        }
20010        return null;
20011    }
20012
20013    /**
20014     * @param predicate The predicate to evaluate.
20015     * @param childToSkip If not null, ignores this child during the recursive traversal.
20016     * @return The first view that matches the predicate or null.
20017     * @hide
20018     */
20019    protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate,
20020            View childToSkip) {
20021        if (predicate.apply(this)) {
20022            return (T) this;
20023        }
20024        return null;
20025    }
20026
20027    /**
20028     * Look for a child view with the given id.  If this view has the given
20029     * id, return this view.
20030     *
20031     * @param id The id to search for.
20032     * @return The view that has the given id in the hierarchy or null
20033     */
20034    @Nullable
20035    public final <T extends View> T findViewById(@IdRes int id) {
20036        if (id < 0) {
20037            return null;
20038        }
20039        return findViewTraversal(id);
20040    }
20041
20042    /**
20043     * Finds a view by its unuque and stable accessibility id.
20044     *
20045     * @param accessibilityId The searched accessibility id.
20046     * @return The found view.
20047     */
20048    final <T extends View> T  findViewByAccessibilityId(int accessibilityId) {
20049        if (accessibilityId < 0) {
20050            return null;
20051        }
20052        T view = findViewByAccessibilityIdTraversal(accessibilityId);
20053        if (view != null) {
20054            return view.includeForAccessibility() ? view : null;
20055        }
20056        return null;
20057    }
20058
20059    /**
20060     * Performs the traversal to find a view by its unuque and stable accessibility id.
20061     *
20062     * <strong>Note:</strong>This method does not stop at the root namespace
20063     * boundary since the user can touch the screen at an arbitrary location
20064     * potentially crossing the root namespace bounday which will send an
20065     * accessibility event to accessibility services and they should be able
20066     * to obtain the event source. Also accessibility ids are guaranteed to be
20067     * unique in the window.
20068     *
20069     * @param accessibilityId The accessibility id.
20070     * @return The found view.
20071     * @hide
20072     */
20073    public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) {
20074        if (getAccessibilityViewId() == accessibilityId) {
20075            return (T) this;
20076        }
20077        return null;
20078    }
20079
20080    /**
20081     * Look for a child view with the given tag.  If this view has the given
20082     * tag, return this view.
20083     *
20084     * @param tag The tag to search for, using "tag.equals(getTag())".
20085     * @return The View that has the given tag in the hierarchy or null
20086     */
20087    public final <T extends View> T findViewWithTag(Object tag) {
20088        if (tag == null) {
20089            return null;
20090        }
20091        return findViewWithTagTraversal(tag);
20092    }
20093
20094    /**
20095     * Look for a child view that matches the specified predicate.
20096     * If this view matches the predicate, return this view.
20097     *
20098     * @param predicate The predicate to evaluate.
20099     * @return The first view that matches the predicate or null.
20100     * @hide
20101     */
20102    public final <T extends View> T findViewByPredicate(Predicate<View> predicate) {
20103        return findViewByPredicateTraversal(predicate, null);
20104    }
20105
20106    /**
20107     * Look for a child view that matches the specified predicate,
20108     * starting with the specified view and its descendents and then
20109     * recusively searching the ancestors and siblings of that view
20110     * until this view is reached.
20111     *
20112     * This method is useful in cases where the predicate does not match
20113     * a single unique view (perhaps multiple views use the same id)
20114     * and we are trying to find the view that is "closest" in scope to the
20115     * starting view.
20116     *
20117     * @param start The view to start from.
20118     * @param predicate The predicate to evaluate.
20119     * @return The first view that matches the predicate or null.
20120     * @hide
20121     */
20122    public final <T extends View> T findViewByPredicateInsideOut(
20123            View start, Predicate<View> predicate) {
20124        View childToSkip = null;
20125        for (;;) {
20126            T view = start.findViewByPredicateTraversal(predicate, childToSkip);
20127            if (view != null || start == this) {
20128                return view;
20129            }
20130
20131            ViewParent parent = start.getParent();
20132            if (parent == null || !(parent instanceof View)) {
20133                return null;
20134            }
20135
20136            childToSkip = start;
20137            start = (View) parent;
20138        }
20139    }
20140
20141    /**
20142     * Sets the identifier for this view. The identifier does not have to be
20143     * unique in this view's hierarchy. The identifier should be a positive
20144     * number.
20145     *
20146     * @see #NO_ID
20147     * @see #getId()
20148     * @see #findViewById(int)
20149     *
20150     * @param id a number used to identify the view
20151     *
20152     * @attr ref android.R.styleable#View_id
20153     */
20154    public void setId(@IdRes int id) {
20155        mID = id;
20156        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
20157            mID = generateViewId();
20158        }
20159    }
20160
20161    /**
20162     * {@hide}
20163     *
20164     * @param isRoot true if the view belongs to the root namespace, false
20165     *        otherwise
20166     */
20167    public void setIsRootNamespace(boolean isRoot) {
20168        if (isRoot) {
20169            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
20170        } else {
20171            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
20172        }
20173    }
20174
20175    /**
20176     * {@hide}
20177     *
20178     * @return true if the view belongs to the root namespace, false otherwise
20179     */
20180    public boolean isRootNamespace() {
20181        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
20182    }
20183
20184    /**
20185     * Returns this view's identifier.
20186     *
20187     * @return a positive integer used to identify the view or {@link #NO_ID}
20188     *         if the view has no ID
20189     *
20190     * @see #setId(int)
20191     * @see #findViewById(int)
20192     * @attr ref android.R.styleable#View_id
20193     */
20194    @IdRes
20195    @ViewDebug.CapturedViewProperty
20196    public int getId() {
20197        return mID;
20198    }
20199
20200    /**
20201     * Returns this view's tag.
20202     *
20203     * @return the Object stored in this view as a tag, or {@code null} if not
20204     *         set
20205     *
20206     * @see #setTag(Object)
20207     * @see #getTag(int)
20208     */
20209    @ViewDebug.ExportedProperty
20210    public Object getTag() {
20211        return mTag;
20212    }
20213
20214    /**
20215     * Sets the tag associated with this view. A tag can be used to mark
20216     * a view in its hierarchy and does not have to be unique within the
20217     * hierarchy. Tags can also be used to store data within a view without
20218     * resorting to another data structure.
20219     *
20220     * @param tag an Object to tag the view with
20221     *
20222     * @see #getTag()
20223     * @see #setTag(int, Object)
20224     */
20225    public void setTag(final Object tag) {
20226        mTag = tag;
20227    }
20228
20229    /**
20230     * Returns the tag associated with this view and the specified key.
20231     *
20232     * @param key The key identifying the tag
20233     *
20234     * @return the Object stored in this view as a tag, or {@code null} if not
20235     *         set
20236     *
20237     * @see #setTag(int, Object)
20238     * @see #getTag()
20239     */
20240    public Object getTag(int key) {
20241        if (mKeyedTags != null) return mKeyedTags.get(key);
20242        return null;
20243    }
20244
20245    /**
20246     * Sets a tag associated with this view and a key. A tag can be used
20247     * to mark a view in its hierarchy and does not have to be unique within
20248     * the hierarchy. Tags can also be used to store data within a view
20249     * without resorting to another data structure.
20250     *
20251     * The specified key should be an id declared in the resources of the
20252     * application to ensure it is unique (see the <a
20253     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
20254     * Keys identified as belonging to
20255     * the Android framework or not associated with any package will cause
20256     * an {@link IllegalArgumentException} to be thrown.
20257     *
20258     * @param key The key identifying the tag
20259     * @param tag An Object to tag the view with
20260     *
20261     * @throws IllegalArgumentException If they specified key is not valid
20262     *
20263     * @see #setTag(Object)
20264     * @see #getTag(int)
20265     */
20266    public void setTag(int key, final Object tag) {
20267        // If the package id is 0x00 or 0x01, it's either an undefined package
20268        // or a framework id
20269        if ((key >>> 24) < 2) {
20270            throw new IllegalArgumentException("The key must be an application-specific "
20271                    + "resource id.");
20272        }
20273
20274        setKeyedTag(key, tag);
20275    }
20276
20277    /**
20278     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
20279     * framework id.
20280     *
20281     * @hide
20282     */
20283    public void setTagInternal(int key, Object tag) {
20284        if ((key >>> 24) != 0x1) {
20285            throw new IllegalArgumentException("The key must be a framework-specific "
20286                    + "resource id.");
20287        }
20288
20289        setKeyedTag(key, tag);
20290    }
20291
20292    private void setKeyedTag(int key, Object tag) {
20293        if (mKeyedTags == null) {
20294            mKeyedTags = new SparseArray<Object>(2);
20295        }
20296
20297        mKeyedTags.put(key, tag);
20298    }
20299
20300    /**
20301     * Prints information about this view in the log output, with the tag
20302     * {@link #VIEW_LOG_TAG}.
20303     *
20304     * @hide
20305     */
20306    public void debug() {
20307        debug(0);
20308    }
20309
20310    /**
20311     * Prints information about this view in the log output, with the tag
20312     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
20313     * indentation defined by the <code>depth</code>.
20314     *
20315     * @param depth the indentation level
20316     *
20317     * @hide
20318     */
20319    protected void debug(int depth) {
20320        String output = debugIndent(depth - 1);
20321
20322        output += "+ " + this;
20323        int id = getId();
20324        if (id != -1) {
20325            output += " (id=" + id + ")";
20326        }
20327        Object tag = getTag();
20328        if (tag != null) {
20329            output += " (tag=" + tag + ")";
20330        }
20331        Log.d(VIEW_LOG_TAG, output);
20332
20333        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
20334            output = debugIndent(depth) + " FOCUSED";
20335            Log.d(VIEW_LOG_TAG, output);
20336        }
20337
20338        output = debugIndent(depth);
20339        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
20340                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
20341                + "} ";
20342        Log.d(VIEW_LOG_TAG, output);
20343
20344        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
20345                || mPaddingBottom != 0) {
20346            output = debugIndent(depth);
20347            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
20348                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
20349            Log.d(VIEW_LOG_TAG, output);
20350        }
20351
20352        output = debugIndent(depth);
20353        output += "mMeasureWidth=" + mMeasuredWidth +
20354                " mMeasureHeight=" + mMeasuredHeight;
20355        Log.d(VIEW_LOG_TAG, output);
20356
20357        output = debugIndent(depth);
20358        if (mLayoutParams == null) {
20359            output += "BAD! no layout params";
20360        } else {
20361            output = mLayoutParams.debug(output);
20362        }
20363        Log.d(VIEW_LOG_TAG, output);
20364
20365        output = debugIndent(depth);
20366        output += "flags={";
20367        output += View.printFlags(mViewFlags);
20368        output += "}";
20369        Log.d(VIEW_LOG_TAG, output);
20370
20371        output = debugIndent(depth);
20372        output += "privateFlags={";
20373        output += View.printPrivateFlags(mPrivateFlags);
20374        output += "}";
20375        Log.d(VIEW_LOG_TAG, output);
20376    }
20377
20378    /**
20379     * Creates a string of whitespaces used for indentation.
20380     *
20381     * @param depth the indentation level
20382     * @return a String containing (depth * 2 + 3) * 2 white spaces
20383     *
20384     * @hide
20385     */
20386    protected static String debugIndent(int depth) {
20387        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
20388        for (int i = 0; i < (depth * 2) + 3; i++) {
20389            spaces.append(' ').append(' ');
20390        }
20391        return spaces.toString();
20392    }
20393
20394    /**
20395     * <p>Return the offset of the widget's text baseline from the widget's top
20396     * boundary. If this widget does not support baseline alignment, this
20397     * method returns -1. </p>
20398     *
20399     * @return the offset of the baseline within the widget's bounds or -1
20400     *         if baseline alignment is not supported
20401     */
20402    @ViewDebug.ExportedProperty(category = "layout")
20403    public int getBaseline() {
20404        return -1;
20405    }
20406
20407    /**
20408     * Returns whether the view hierarchy is currently undergoing a layout pass. This
20409     * information is useful to avoid situations such as calling {@link #requestLayout()} during
20410     * a layout pass.
20411     *
20412     * @return whether the view hierarchy is currently undergoing a layout pass
20413     */
20414    public boolean isInLayout() {
20415        ViewRootImpl viewRoot = getViewRootImpl();
20416        return (viewRoot != null && viewRoot.isInLayout());
20417    }
20418
20419    /**
20420     * Call this when something has changed which has invalidated the
20421     * layout of this view. This will schedule a layout pass of the view
20422     * tree. This should not be called while the view hierarchy is currently in a layout
20423     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
20424     * end of the current layout pass (and then layout will run again) or after the current
20425     * frame is drawn and the next layout occurs.
20426     *
20427     * <p>Subclasses which override this method should call the superclass method to
20428     * handle possible request-during-layout errors correctly.</p>
20429     */
20430    @CallSuper
20431    public void requestLayout() {
20432        if (mMeasureCache != null) mMeasureCache.clear();
20433
20434        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
20435            // Only trigger request-during-layout logic if this is the view requesting it,
20436            // not the views in its parent hierarchy
20437            ViewRootImpl viewRoot = getViewRootImpl();
20438            if (viewRoot != null && viewRoot.isInLayout()) {
20439                if (!viewRoot.requestLayoutDuringLayout(this)) {
20440                    return;
20441                }
20442            }
20443            mAttachInfo.mViewRequestingLayout = this;
20444        }
20445
20446        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20447        mPrivateFlags |= PFLAG_INVALIDATED;
20448
20449        if (mParent != null && !mParent.isLayoutRequested()) {
20450            mParent.requestLayout();
20451        }
20452        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
20453            mAttachInfo.mViewRequestingLayout = null;
20454        }
20455    }
20456
20457    /**
20458     * Forces this view to be laid out during the next layout pass.
20459     * This method does not call requestLayout() or forceLayout()
20460     * on the parent.
20461     */
20462    public void forceLayout() {
20463        if (mMeasureCache != null) mMeasureCache.clear();
20464
20465        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20466        mPrivateFlags |= PFLAG_INVALIDATED;
20467    }
20468
20469    /**
20470     * <p>
20471     * This is called to find out how big a view should be. The parent
20472     * supplies constraint information in the width and height parameters.
20473     * </p>
20474     *
20475     * <p>
20476     * The actual measurement work of a view is performed in
20477     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
20478     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
20479     * </p>
20480     *
20481     *
20482     * @param widthMeasureSpec Horizontal space requirements as imposed by the
20483     *        parent
20484     * @param heightMeasureSpec Vertical space requirements as imposed by the
20485     *        parent
20486     *
20487     * @see #onMeasure(int, int)
20488     */
20489    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
20490        boolean optical = isLayoutModeOptical(this);
20491        if (optical != isLayoutModeOptical(mParent)) {
20492            Insets insets = getOpticalInsets();
20493            int oWidth  = insets.left + insets.right;
20494            int oHeight = insets.top  + insets.bottom;
20495            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
20496            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
20497        }
20498
20499        // Suppress sign extension for the low bytes
20500        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
20501        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
20502
20503        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20504
20505        // Optimize layout by avoiding an extra EXACTLY pass when the view is
20506        // already measured as the correct size. In API 23 and below, this
20507        // extra pass is required to make LinearLayout re-distribute weight.
20508        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
20509                || heightMeasureSpec != mOldHeightMeasureSpec;
20510        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
20511                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
20512        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
20513                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
20514        final boolean needsLayout = specChanged
20515                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
20516
20517        if (forceLayout || needsLayout) {
20518            // first clears the measured dimension flag
20519            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
20520
20521            resolveRtlPropertiesIfNeeded();
20522
20523            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
20524            if (cacheIndex < 0 || sIgnoreMeasureCache) {
20525                // measure ourselves, this should set the measured dimension flag back
20526                onMeasure(widthMeasureSpec, heightMeasureSpec);
20527                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20528            } else {
20529                long value = mMeasureCache.valueAt(cacheIndex);
20530                // Casting a long to int drops the high 32 bits, no mask needed
20531                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
20532                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20533            }
20534
20535            // flag not set, setMeasuredDimension() was not invoked, we raise
20536            // an exception to warn the developer
20537            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
20538                throw new IllegalStateException("View with id " + getId() + ": "
20539                        + getClass().getName() + "#onMeasure() did not set the"
20540                        + " measured dimension by calling"
20541                        + " setMeasuredDimension()");
20542            }
20543
20544            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
20545        }
20546
20547        mOldWidthMeasureSpec = widthMeasureSpec;
20548        mOldHeightMeasureSpec = heightMeasureSpec;
20549
20550        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
20551                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
20552    }
20553
20554    /**
20555     * <p>
20556     * Measure the view and its content to determine the measured width and the
20557     * measured height. This method is invoked by {@link #measure(int, int)} and
20558     * should be overridden by subclasses to provide accurate and efficient
20559     * measurement of their contents.
20560     * </p>
20561     *
20562     * <p>
20563     * <strong>CONTRACT:</strong> When overriding this method, you
20564     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
20565     * measured width and height of this view. Failure to do so will trigger an
20566     * <code>IllegalStateException</code>, thrown by
20567     * {@link #measure(int, int)}. Calling the superclass'
20568     * {@link #onMeasure(int, int)} is a valid use.
20569     * </p>
20570     *
20571     * <p>
20572     * The base class implementation of measure defaults to the background size,
20573     * unless a larger size is allowed by the MeasureSpec. Subclasses should
20574     * override {@link #onMeasure(int, int)} to provide better measurements of
20575     * their content.
20576     * </p>
20577     *
20578     * <p>
20579     * If this method is overridden, it is the subclass's responsibility to make
20580     * sure the measured height and width are at least the view's minimum height
20581     * and width ({@link #getSuggestedMinimumHeight()} and
20582     * {@link #getSuggestedMinimumWidth()}).
20583     * </p>
20584     *
20585     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
20586     *                         The requirements are encoded with
20587     *                         {@link android.view.View.MeasureSpec}.
20588     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
20589     *                         The requirements are encoded with
20590     *                         {@link android.view.View.MeasureSpec}.
20591     *
20592     * @see #getMeasuredWidth()
20593     * @see #getMeasuredHeight()
20594     * @see #setMeasuredDimension(int, int)
20595     * @see #getSuggestedMinimumHeight()
20596     * @see #getSuggestedMinimumWidth()
20597     * @see android.view.View.MeasureSpec#getMode(int)
20598     * @see android.view.View.MeasureSpec#getSize(int)
20599     */
20600    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
20601        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
20602                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
20603    }
20604
20605    /**
20606     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
20607     * measured width and measured height. Failing to do so will trigger an
20608     * exception at measurement time.</p>
20609     *
20610     * @param measuredWidth The measured width of this view.  May be a complex
20611     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20612     * {@link #MEASURED_STATE_TOO_SMALL}.
20613     * @param measuredHeight The measured height of this view.  May be a complex
20614     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20615     * {@link #MEASURED_STATE_TOO_SMALL}.
20616     */
20617    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
20618        boolean optical = isLayoutModeOptical(this);
20619        if (optical != isLayoutModeOptical(mParent)) {
20620            Insets insets = getOpticalInsets();
20621            int opticalWidth  = insets.left + insets.right;
20622            int opticalHeight = insets.top  + insets.bottom;
20623
20624            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
20625            measuredHeight += optical ? opticalHeight : -opticalHeight;
20626        }
20627        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
20628    }
20629
20630    /**
20631     * Sets the measured dimension without extra processing for things like optical bounds.
20632     * Useful for reapplying consistent values that have already been cooked with adjustments
20633     * for optical bounds, etc. such as those from the measurement cache.
20634     *
20635     * @param measuredWidth The measured width of this view.  May be a complex
20636     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20637     * {@link #MEASURED_STATE_TOO_SMALL}.
20638     * @param measuredHeight The measured height of this view.  May be a complex
20639     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20640     * {@link #MEASURED_STATE_TOO_SMALL}.
20641     */
20642    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
20643        mMeasuredWidth = measuredWidth;
20644        mMeasuredHeight = measuredHeight;
20645
20646        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
20647    }
20648
20649    /**
20650     * Merge two states as returned by {@link #getMeasuredState()}.
20651     * @param curState The current state as returned from a view or the result
20652     * of combining multiple views.
20653     * @param newState The new view state to combine.
20654     * @return Returns a new integer reflecting the combination of the two
20655     * states.
20656     */
20657    public static int combineMeasuredStates(int curState, int newState) {
20658        return curState | newState;
20659    }
20660
20661    /**
20662     * Version of {@link #resolveSizeAndState(int, int, int)}
20663     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
20664     */
20665    public static int resolveSize(int size, int measureSpec) {
20666        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
20667    }
20668
20669    /**
20670     * Utility to reconcile a desired size and state, with constraints imposed
20671     * by a MeasureSpec. Will take the desired size, unless a different size
20672     * is imposed by the constraints. The returned value is a compound integer,
20673     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20674     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20675     * resulting size is smaller than the size the view wants to be.
20676     *
20677     * @param size How big the view wants to be.
20678     * @param measureSpec Constraints imposed by the parent.
20679     * @param childMeasuredState Size information bit mask for the view's
20680     *                           children.
20681     * @return Size information bit mask as defined by
20682     *         {@link #MEASURED_SIZE_MASK} and
20683     *         {@link #MEASURED_STATE_TOO_SMALL}.
20684     */
20685    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20686        final int specMode = MeasureSpec.getMode(measureSpec);
20687        final int specSize = MeasureSpec.getSize(measureSpec);
20688        final int result;
20689        switch (specMode) {
20690            case MeasureSpec.AT_MOST:
20691                if (specSize < size) {
20692                    result = specSize | MEASURED_STATE_TOO_SMALL;
20693                } else {
20694                    result = size;
20695                }
20696                break;
20697            case MeasureSpec.EXACTLY:
20698                result = specSize;
20699                break;
20700            case MeasureSpec.UNSPECIFIED:
20701            default:
20702                result = size;
20703        }
20704        return result | (childMeasuredState & MEASURED_STATE_MASK);
20705    }
20706
20707    /**
20708     * Utility to return a default size. Uses the supplied size if the
20709     * MeasureSpec imposed no constraints. Will get larger if allowed
20710     * by the MeasureSpec.
20711     *
20712     * @param size Default size for this view
20713     * @param measureSpec Constraints imposed by the parent
20714     * @return The size this view should be.
20715     */
20716    public static int getDefaultSize(int size, int measureSpec) {
20717        int result = size;
20718        int specMode = MeasureSpec.getMode(measureSpec);
20719        int specSize = MeasureSpec.getSize(measureSpec);
20720
20721        switch (specMode) {
20722        case MeasureSpec.UNSPECIFIED:
20723            result = size;
20724            break;
20725        case MeasureSpec.AT_MOST:
20726        case MeasureSpec.EXACTLY:
20727            result = specSize;
20728            break;
20729        }
20730        return result;
20731    }
20732
20733    /**
20734     * Returns the suggested minimum height that the view should use. This
20735     * returns the maximum of the view's minimum height
20736     * and the background's minimum height
20737     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
20738     * <p>
20739     * When being used in {@link #onMeasure(int, int)}, the caller should still
20740     * ensure the returned height is within the requirements of the parent.
20741     *
20742     * @return The suggested minimum height of the view.
20743     */
20744    protected int getSuggestedMinimumHeight() {
20745        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
20746
20747    }
20748
20749    /**
20750     * Returns the suggested minimum width that the view should use. This
20751     * returns the maximum of the view's minimum width
20752     * and the background's minimum width
20753     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
20754     * <p>
20755     * When being used in {@link #onMeasure(int, int)}, the caller should still
20756     * ensure the returned width is within the requirements of the parent.
20757     *
20758     * @return The suggested minimum width of the view.
20759     */
20760    protected int getSuggestedMinimumWidth() {
20761        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
20762    }
20763
20764    /**
20765     * Returns the minimum height of the view.
20766     *
20767     * @return the minimum height the view will try to be, in pixels
20768     *
20769     * @see #setMinimumHeight(int)
20770     *
20771     * @attr ref android.R.styleable#View_minHeight
20772     */
20773    public int getMinimumHeight() {
20774        return mMinHeight;
20775    }
20776
20777    /**
20778     * Sets the minimum height of the view. It is not guaranteed the view will
20779     * be able to achieve this minimum height (for example, if its parent layout
20780     * constrains it with less available height).
20781     *
20782     * @param minHeight The minimum height the view will try to be, in pixels
20783     *
20784     * @see #getMinimumHeight()
20785     *
20786     * @attr ref android.R.styleable#View_minHeight
20787     */
20788    @RemotableViewMethod
20789    public void setMinimumHeight(int minHeight) {
20790        mMinHeight = minHeight;
20791        requestLayout();
20792    }
20793
20794    /**
20795     * Returns the minimum width of the view.
20796     *
20797     * @return the minimum width the view will try to be, in pixels
20798     *
20799     * @see #setMinimumWidth(int)
20800     *
20801     * @attr ref android.R.styleable#View_minWidth
20802     */
20803    public int getMinimumWidth() {
20804        return mMinWidth;
20805    }
20806
20807    /**
20808     * Sets the minimum width of the view. It is not guaranteed the view will
20809     * be able to achieve this minimum width (for example, if its parent layout
20810     * constrains it with less available width).
20811     *
20812     * @param minWidth The minimum width the view will try to be, in pixels
20813     *
20814     * @see #getMinimumWidth()
20815     *
20816     * @attr ref android.R.styleable#View_minWidth
20817     */
20818    public void setMinimumWidth(int minWidth) {
20819        mMinWidth = minWidth;
20820        requestLayout();
20821
20822    }
20823
20824    /**
20825     * Get the animation currently associated with this view.
20826     *
20827     * @return The animation that is currently playing or
20828     *         scheduled to play for this view.
20829     */
20830    public Animation getAnimation() {
20831        return mCurrentAnimation;
20832    }
20833
20834    /**
20835     * Start the specified animation now.
20836     *
20837     * @param animation the animation to start now
20838     */
20839    public void startAnimation(Animation animation) {
20840        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20841        setAnimation(animation);
20842        invalidateParentCaches();
20843        invalidate(true);
20844    }
20845
20846    /**
20847     * Cancels any animations for this view.
20848     */
20849    public void clearAnimation() {
20850        if (mCurrentAnimation != null) {
20851            mCurrentAnimation.detach();
20852        }
20853        mCurrentAnimation = null;
20854        invalidateParentIfNeeded();
20855    }
20856
20857    /**
20858     * Sets the next animation to play for this view.
20859     * If you want the animation to play immediately, use
20860     * {@link #startAnimation(android.view.animation.Animation)} instead.
20861     * This method provides allows fine-grained
20862     * control over the start time and invalidation, but you
20863     * must make sure that 1) the animation has a start time set, and
20864     * 2) the view's parent (which controls animations on its children)
20865     * will be invalidated when the animation is supposed to
20866     * start.
20867     *
20868     * @param animation The next animation, or null.
20869     */
20870    public void setAnimation(Animation animation) {
20871        mCurrentAnimation = animation;
20872
20873        if (animation != null) {
20874            // If the screen is off assume the animation start time is now instead of
20875            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20876            // would cause the animation to start when the screen turns back on
20877            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20878                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20879                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20880            }
20881            animation.reset();
20882        }
20883    }
20884
20885    /**
20886     * Invoked by a parent ViewGroup to notify the start of the animation
20887     * currently associated with this view. If you override this method,
20888     * always call super.onAnimationStart();
20889     *
20890     * @see #setAnimation(android.view.animation.Animation)
20891     * @see #getAnimation()
20892     */
20893    @CallSuper
20894    protected void onAnimationStart() {
20895        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20896    }
20897
20898    /**
20899     * Invoked by a parent ViewGroup to notify the end of the animation
20900     * currently associated with this view. If you override this method,
20901     * always call super.onAnimationEnd();
20902     *
20903     * @see #setAnimation(android.view.animation.Animation)
20904     * @see #getAnimation()
20905     */
20906    @CallSuper
20907    protected void onAnimationEnd() {
20908        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20909    }
20910
20911    /**
20912     * Invoked if there is a Transform that involves alpha. Subclass that can
20913     * draw themselves with the specified alpha should return true, and then
20914     * respect that alpha when their onDraw() is called. If this returns false
20915     * then the view may be redirected to draw into an offscreen buffer to
20916     * fulfill the request, which will look fine, but may be slower than if the
20917     * subclass handles it internally. The default implementation returns false.
20918     *
20919     * @param alpha The alpha (0..255) to apply to the view's drawing
20920     * @return true if the view can draw with the specified alpha.
20921     */
20922    protected boolean onSetAlpha(int alpha) {
20923        return false;
20924    }
20925
20926    /**
20927     * This is used by the RootView to perform an optimization when
20928     * the view hierarchy contains one or several SurfaceView.
20929     * SurfaceView is always considered transparent, but its children are not,
20930     * therefore all View objects remove themselves from the global transparent
20931     * region (passed as a parameter to this function).
20932     *
20933     * @param region The transparent region for this ViewAncestor (window).
20934     *
20935     * @return Returns true if the effective visibility of the view at this
20936     * point is opaque, regardless of the transparent region; returns false
20937     * if it is possible for underlying windows to be seen behind the view.
20938     *
20939     * {@hide}
20940     */
20941    public boolean gatherTransparentRegion(Region region) {
20942        final AttachInfo attachInfo = mAttachInfo;
20943        if (region != null && attachInfo != null) {
20944            final int pflags = mPrivateFlags;
20945            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20946                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20947                // remove it from the transparent region.
20948                final int[] location = attachInfo.mTransparentLocation;
20949                getLocationInWindow(location);
20950                // When a view has Z value, then it will be better to leave some area below the view
20951                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
20952                // the bottom part needs more offset than the left, top and right parts due to the
20953                // spot light effects.
20954                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
20955                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
20956                        location[0] + mRight - mLeft + shadowOffset,
20957                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
20958            } else {
20959                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20960                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20961                    // the background drawable's non-transparent parts from this transparent region.
20962                    applyDrawableToTransparentRegion(mBackground, region);
20963                }
20964                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20965                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20966                    // Similarly, we remove the foreground drawable's non-transparent parts.
20967                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20968                }
20969            }
20970        }
20971        return true;
20972    }
20973
20974    /**
20975     * Play a sound effect for this view.
20976     *
20977     * <p>The framework will play sound effects for some built in actions, such as
20978     * clicking, but you may wish to play these effects in your widget,
20979     * for instance, for internal navigation.
20980     *
20981     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20982     * {@link #isSoundEffectsEnabled()} is true.
20983     *
20984     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20985     */
20986    public void playSoundEffect(int soundConstant) {
20987        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20988            return;
20989        }
20990        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20991    }
20992
20993    /**
20994     * BZZZTT!!1!
20995     *
20996     * <p>Provide haptic feedback to the user for this view.
20997     *
20998     * <p>The framework will provide haptic feedback for some built in actions,
20999     * such as long presses, but you may wish to provide feedback for your
21000     * own widget.
21001     *
21002     * <p>The feedback will only be performed if
21003     * {@link #isHapticFeedbackEnabled()} is true.
21004     *
21005     * @param feedbackConstant One of the constants defined in
21006     * {@link HapticFeedbackConstants}
21007     */
21008    public boolean performHapticFeedback(int feedbackConstant) {
21009        return performHapticFeedback(feedbackConstant, 0);
21010    }
21011
21012    /**
21013     * BZZZTT!!1!
21014     *
21015     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
21016     *
21017     * @param feedbackConstant One of the constants defined in
21018     * {@link HapticFeedbackConstants}
21019     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
21020     */
21021    public boolean performHapticFeedback(int feedbackConstant, int flags) {
21022        if (mAttachInfo == null) {
21023            return false;
21024        }
21025        //noinspection SimplifiableIfStatement
21026        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
21027                && !isHapticFeedbackEnabled()) {
21028            return false;
21029        }
21030        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
21031                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
21032    }
21033
21034    /**
21035     * Request that the visibility of the status bar or other screen/window
21036     * decorations be changed.
21037     *
21038     * <p>This method is used to put the over device UI into temporary modes
21039     * where the user's attention is focused more on the application content,
21040     * by dimming or hiding surrounding system affordances.  This is typically
21041     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
21042     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
21043     * to be placed behind the action bar (and with these flags other system
21044     * affordances) so that smooth transitions between hiding and showing them
21045     * can be done.
21046     *
21047     * <p>Two representative examples of the use of system UI visibility is
21048     * implementing a content browsing application (like a magazine reader)
21049     * and a video playing application.
21050     *
21051     * <p>The first code shows a typical implementation of a View in a content
21052     * browsing application.  In this implementation, the application goes
21053     * into a content-oriented mode by hiding the status bar and action bar,
21054     * and putting the navigation elements into lights out mode.  The user can
21055     * then interact with content while in this mode.  Such an application should
21056     * provide an easy way for the user to toggle out of the mode (such as to
21057     * check information in the status bar or access notifications).  In the
21058     * implementation here, this is done simply by tapping on the content.
21059     *
21060     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
21061     *      content}
21062     *
21063     * <p>This second code sample shows a typical implementation of a View
21064     * in a video playing application.  In this situation, while the video is
21065     * playing the application would like to go into a complete full-screen mode,
21066     * to use as much of the display as possible for the video.  When in this state
21067     * the user can not interact with the application; the system intercepts
21068     * touching on the screen to pop the UI out of full screen mode.  See
21069     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
21070     *
21071     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
21072     *      content}
21073     *
21074     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21075     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21076     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21077     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21078     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21079     */
21080    public void setSystemUiVisibility(int visibility) {
21081        if (visibility != mSystemUiVisibility) {
21082            mSystemUiVisibility = visibility;
21083            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21084                mParent.recomputeViewAttributes(this);
21085            }
21086        }
21087    }
21088
21089    /**
21090     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
21091     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21092     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21093     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21094     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21095     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21096     */
21097    public int getSystemUiVisibility() {
21098        return mSystemUiVisibility;
21099    }
21100
21101    /**
21102     * Returns the current system UI visibility that is currently set for
21103     * the entire window.  This is the combination of the
21104     * {@link #setSystemUiVisibility(int)} values supplied by all of the
21105     * views in the window.
21106     */
21107    public int getWindowSystemUiVisibility() {
21108        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
21109    }
21110
21111    /**
21112     * Override to find out when the window's requested system UI visibility
21113     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
21114     * This is different from the callbacks received through
21115     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
21116     * in that this is only telling you about the local request of the window,
21117     * not the actual values applied by the system.
21118     */
21119    public void onWindowSystemUiVisibilityChanged(int visible) {
21120    }
21121
21122    /**
21123     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
21124     * the view hierarchy.
21125     */
21126    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
21127        onWindowSystemUiVisibilityChanged(visible);
21128    }
21129
21130    /**
21131     * Set a listener to receive callbacks when the visibility of the system bar changes.
21132     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
21133     */
21134    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
21135        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
21136        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21137            mParent.recomputeViewAttributes(this);
21138        }
21139    }
21140
21141    /**
21142     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
21143     * the view hierarchy.
21144     */
21145    public void dispatchSystemUiVisibilityChanged(int visibility) {
21146        ListenerInfo li = mListenerInfo;
21147        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
21148            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
21149                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
21150        }
21151    }
21152
21153    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
21154        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
21155        if (val != mSystemUiVisibility) {
21156            setSystemUiVisibility(val);
21157            return true;
21158        }
21159        return false;
21160    }
21161
21162    /** @hide */
21163    public void setDisabledSystemUiVisibility(int flags) {
21164        if (mAttachInfo != null) {
21165            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
21166                mAttachInfo.mDisabledSystemUiVisibility = flags;
21167                if (mParent != null) {
21168                    mParent.recomputeViewAttributes(this);
21169                }
21170            }
21171        }
21172    }
21173
21174    /**
21175     * Creates an image that the system displays during the drag and drop
21176     * operation. This is called a &quot;drag shadow&quot;. The default implementation
21177     * for a DragShadowBuilder based on a View returns an image that has exactly the same
21178     * appearance as the given View. The default also positions the center of the drag shadow
21179     * directly under the touch point. If no View is provided (the constructor with no parameters
21180     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
21181     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
21182     * default is an invisible drag shadow.
21183     * <p>
21184     * You are not required to use the View you provide to the constructor as the basis of the
21185     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
21186     * anything you want as the drag shadow.
21187     * </p>
21188     * <p>
21189     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
21190     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
21191     *  size and position of the drag shadow. It uses this data to construct a
21192     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
21193     *  so that your application can draw the shadow image in the Canvas.
21194     * </p>
21195     *
21196     * <div class="special reference">
21197     * <h3>Developer Guides</h3>
21198     * <p>For a guide to implementing drag and drop features, read the
21199     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
21200     * </div>
21201     */
21202    public static class DragShadowBuilder {
21203        private final WeakReference<View> mView;
21204
21205        /**
21206         * Constructs a shadow image builder based on a View. By default, the resulting drag
21207         * shadow will have the same appearance and dimensions as the View, with the touch point
21208         * over the center of the View.
21209         * @param view A View. Any View in scope can be used.
21210         */
21211        public DragShadowBuilder(View view) {
21212            mView = new WeakReference<View>(view);
21213        }
21214
21215        /**
21216         * Construct a shadow builder object with no associated View.  This
21217         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
21218         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
21219         * to supply the drag shadow's dimensions and appearance without
21220         * reference to any View object. If they are not overridden, then the result is an
21221         * invisible drag shadow.
21222         */
21223        public DragShadowBuilder() {
21224            mView = new WeakReference<View>(null);
21225        }
21226
21227        /**
21228         * Returns the View object that had been passed to the
21229         * {@link #View.DragShadowBuilder(View)}
21230         * constructor.  If that View parameter was {@code null} or if the
21231         * {@link #View.DragShadowBuilder()}
21232         * constructor was used to instantiate the builder object, this method will return
21233         * null.
21234         *
21235         * @return The View object associate with this builder object.
21236         */
21237        @SuppressWarnings({"JavadocReference"})
21238        final public View getView() {
21239            return mView.get();
21240        }
21241
21242        /**
21243         * Provides the metrics for the shadow image. These include the dimensions of
21244         * the shadow image, and the point within that shadow that should
21245         * be centered under the touch location while dragging.
21246         * <p>
21247         * The default implementation sets the dimensions of the shadow to be the
21248         * same as the dimensions of the View itself and centers the shadow under
21249         * the touch point.
21250         * </p>
21251         *
21252         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
21253         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
21254         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
21255         * image.
21256         *
21257         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
21258         * shadow image that should be underneath the touch point during the drag and drop
21259         * operation. Your application must set {@link android.graphics.Point#x} to the
21260         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
21261         */
21262        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
21263            final View view = mView.get();
21264            if (view != null) {
21265                outShadowSize.set(view.getWidth(), view.getHeight());
21266                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
21267            } else {
21268                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
21269            }
21270        }
21271
21272        /**
21273         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
21274         * based on the dimensions it received from the
21275         * {@link #onProvideShadowMetrics(Point, Point)} callback.
21276         *
21277         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
21278         */
21279        public void onDrawShadow(Canvas canvas) {
21280            final View view = mView.get();
21281            if (view != null) {
21282                view.draw(canvas);
21283            } else {
21284                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
21285            }
21286        }
21287    }
21288
21289    /**
21290     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
21291     * startDragAndDrop()} for newer platform versions.
21292     */
21293    @Deprecated
21294    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
21295                                   Object myLocalState, int flags) {
21296        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
21297    }
21298
21299    /**
21300     * Starts a drag and drop operation. When your application calls this method, it passes a
21301     * {@link android.view.View.DragShadowBuilder} object to the system. The
21302     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
21303     * to get metrics for the drag shadow, and then calls the object's
21304     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
21305     * <p>
21306     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
21307     *  drag events to all the View objects in your application that are currently visible. It does
21308     *  this either by calling the View object's drag listener (an implementation of
21309     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
21310     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
21311     *  Both are passed a {@link android.view.DragEvent} object that has a
21312     *  {@link android.view.DragEvent#getAction()} value of
21313     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
21314     * </p>
21315     * <p>
21316     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
21317     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
21318     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
21319     * to the View the user selected for dragging.
21320     * </p>
21321     * @param data A {@link android.content.ClipData} object pointing to the data to be
21322     * transferred by the drag and drop operation.
21323     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21324     * drag shadow.
21325     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
21326     * drop operation. When dispatching drag events to views in the same activity this object
21327     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
21328     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
21329     * will return null).
21330     * <p>
21331     * myLocalState is a lightweight mechanism for the sending information from the dragged View
21332     * to the target Views. For example, it can contain flags that differentiate between a
21333     * a copy operation and a move operation.
21334     * </p>
21335     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
21336     * flags, or any combination of the following:
21337     *     <ul>
21338     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
21339     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
21340     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
21341     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
21342     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
21343     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
21344     *     </ul>
21345     * @return {@code true} if the method completes successfully, or
21346     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
21347     * do a drag, and so no drag operation is in progress.
21348     */
21349    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
21350            Object myLocalState, int flags) {
21351        if (ViewDebug.DEBUG_DRAG) {
21352            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
21353        }
21354        if (mAttachInfo == null) {
21355            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
21356            return false;
21357        }
21358
21359        if (data != null) {
21360            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
21361        }
21362
21363        boolean okay = false;
21364
21365        Point shadowSize = new Point();
21366        Point shadowTouchPoint = new Point();
21367        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
21368
21369        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
21370                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
21371            throw new IllegalStateException("Drag shadow dimensions must not be negative");
21372        }
21373
21374        if (ViewDebug.DEBUG_DRAG) {
21375            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
21376                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
21377        }
21378        if (mAttachInfo.mDragSurface != null) {
21379            mAttachInfo.mDragSurface.release();
21380        }
21381        mAttachInfo.mDragSurface = new Surface();
21382        try {
21383            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
21384                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
21385            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
21386                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
21387            if (mAttachInfo.mDragToken != null) {
21388                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21389                try {
21390                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21391                    shadowBuilder.onDrawShadow(canvas);
21392                } finally {
21393                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21394                }
21395
21396                final ViewRootImpl root = getViewRootImpl();
21397
21398                // Cache the local state object for delivery with DragEvents
21399                root.setLocalDragState(myLocalState);
21400
21401                // repurpose 'shadowSize' for the last touch point
21402                root.getLastTouchPoint(shadowSize);
21403
21404                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
21405                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
21406                        shadowTouchPoint.x, shadowTouchPoint.y, data);
21407                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
21408            }
21409        } catch (Exception e) {
21410            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
21411            mAttachInfo.mDragSurface.destroy();
21412            mAttachInfo.mDragSurface = null;
21413        }
21414
21415        return okay;
21416    }
21417
21418    /**
21419     * Cancels an ongoing drag and drop operation.
21420     * <p>
21421     * A {@link android.view.DragEvent} object with
21422     * {@link android.view.DragEvent#getAction()} value of
21423     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
21424     * {@link android.view.DragEvent#getResult()} value of {@code false}
21425     * will be sent to every
21426     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
21427     * even if they are not currently visible.
21428     * </p>
21429     * <p>
21430     * This method can be called on any View in the same window as the View on which
21431     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
21432     * was called.
21433     * </p>
21434     */
21435    public final void cancelDragAndDrop() {
21436        if (ViewDebug.DEBUG_DRAG) {
21437            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
21438        }
21439        if (mAttachInfo == null) {
21440            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
21441            return;
21442        }
21443        if (mAttachInfo.mDragToken != null) {
21444            try {
21445                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
21446            } catch (Exception e) {
21447                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
21448            }
21449            mAttachInfo.mDragToken = null;
21450        } else {
21451            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
21452        }
21453    }
21454
21455    /**
21456     * Updates the drag shadow for the ongoing drag and drop operation.
21457     *
21458     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21459     * new drag shadow.
21460     */
21461    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
21462        if (ViewDebug.DEBUG_DRAG) {
21463            Log.d(VIEW_LOG_TAG, "updateDragShadow");
21464        }
21465        if (mAttachInfo == null) {
21466            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
21467            return;
21468        }
21469        if (mAttachInfo.mDragToken != null) {
21470            try {
21471                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21472                try {
21473                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21474                    shadowBuilder.onDrawShadow(canvas);
21475                } finally {
21476                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21477                }
21478            } catch (Exception e) {
21479                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
21480            }
21481        } else {
21482            Log.e(VIEW_LOG_TAG, "No active drag");
21483        }
21484    }
21485
21486    /**
21487     * Starts a move from {startX, startY}, the amount of the movement will be the offset
21488     * between {startX, startY} and the new cursor positon.
21489     * @param startX horizontal coordinate where the move started.
21490     * @param startY vertical coordinate where the move started.
21491     * @return whether moving was started successfully.
21492     * @hide
21493     */
21494    public final boolean startMovingTask(float startX, float startY) {
21495        if (ViewDebug.DEBUG_POSITIONING) {
21496            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
21497        }
21498        try {
21499            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
21500        } catch (RemoteException e) {
21501            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
21502        }
21503        return false;
21504    }
21505
21506    /**
21507     * Handles drag events sent by the system following a call to
21508     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
21509     * startDragAndDrop()}.
21510     *<p>
21511     * When the system calls this method, it passes a
21512     * {@link android.view.DragEvent} object. A call to
21513     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
21514     * in DragEvent. The method uses these to determine what is happening in the drag and drop
21515     * operation.
21516     * @param event The {@link android.view.DragEvent} sent by the system.
21517     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
21518     * in DragEvent, indicating the type of drag event represented by this object.
21519     * @return {@code true} if the method was successful, otherwise {@code false}.
21520     * <p>
21521     *  The method should return {@code true} in response to an action type of
21522     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
21523     *  operation.
21524     * </p>
21525     * <p>
21526     *  The method should also return {@code true} in response to an action type of
21527     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
21528     *  {@code false} if it didn't.
21529     * </p>
21530     * <p>
21531     *  For all other events, the return value is ignored.
21532     * </p>
21533     */
21534    public boolean onDragEvent(DragEvent event) {
21535        return false;
21536    }
21537
21538    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
21539    boolean dispatchDragEnterExitInPreN(DragEvent event) {
21540        return callDragEventHandler(event);
21541    }
21542
21543    /**
21544     * Detects if this View is enabled and has a drag event listener.
21545     * If both are true, then it calls the drag event listener with the
21546     * {@link android.view.DragEvent} it received. If the drag event listener returns
21547     * {@code true}, then dispatchDragEvent() returns {@code true}.
21548     * <p>
21549     * For all other cases, the method calls the
21550     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
21551     * method and returns its result.
21552     * </p>
21553     * <p>
21554     * This ensures that a drag event is always consumed, even if the View does not have a drag
21555     * event listener. However, if the View has a listener and the listener returns true, then
21556     * onDragEvent() is not called.
21557     * </p>
21558     */
21559    public boolean dispatchDragEvent(DragEvent event) {
21560        event.mEventHandlerWasCalled = true;
21561        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
21562            event.mAction == DragEvent.ACTION_DROP) {
21563            // About to deliver an event with coordinates to this view. Notify that now this view
21564            // has drag focus. This will send exit/enter events as needed.
21565            getViewRootImpl().setDragFocus(this, event);
21566        }
21567        return callDragEventHandler(event);
21568    }
21569
21570    final boolean callDragEventHandler(DragEvent event) {
21571        final boolean result;
21572
21573        ListenerInfo li = mListenerInfo;
21574        //noinspection SimplifiableIfStatement
21575        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
21576                && li.mOnDragListener.onDrag(this, event)) {
21577            result = true;
21578        } else {
21579            result = onDragEvent(event);
21580        }
21581
21582        switch (event.mAction) {
21583            case DragEvent.ACTION_DRAG_ENTERED: {
21584                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
21585                refreshDrawableState();
21586            } break;
21587            case DragEvent.ACTION_DRAG_EXITED: {
21588                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
21589                refreshDrawableState();
21590            } break;
21591            case DragEvent.ACTION_DRAG_ENDED: {
21592                mPrivateFlags2 &= ~View.DRAG_MASK;
21593                refreshDrawableState();
21594            } break;
21595        }
21596
21597        return result;
21598    }
21599
21600    boolean canAcceptDrag() {
21601        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
21602    }
21603
21604    /**
21605     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
21606     * it is ever exposed at all.
21607     * @hide
21608     */
21609    public void onCloseSystemDialogs(String reason) {
21610    }
21611
21612    /**
21613     * Given a Drawable whose bounds have been set to draw into this view,
21614     * update a Region being computed for
21615     * {@link #gatherTransparentRegion(android.graphics.Region)} so
21616     * that any non-transparent parts of the Drawable are removed from the
21617     * given transparent region.
21618     *
21619     * @param dr The Drawable whose transparency is to be applied to the region.
21620     * @param region A Region holding the current transparency information,
21621     * where any parts of the region that are set are considered to be
21622     * transparent.  On return, this region will be modified to have the
21623     * transparency information reduced by the corresponding parts of the
21624     * Drawable that are not transparent.
21625     * {@hide}
21626     */
21627    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
21628        if (DBG) {
21629            Log.i("View", "Getting transparent region for: " + this);
21630        }
21631        final Region r = dr.getTransparentRegion();
21632        final Rect db = dr.getBounds();
21633        final AttachInfo attachInfo = mAttachInfo;
21634        if (r != null && attachInfo != null) {
21635            final int w = getRight()-getLeft();
21636            final int h = getBottom()-getTop();
21637            if (db.left > 0) {
21638                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
21639                r.op(0, 0, db.left, h, Region.Op.UNION);
21640            }
21641            if (db.right < w) {
21642                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
21643                r.op(db.right, 0, w, h, Region.Op.UNION);
21644            }
21645            if (db.top > 0) {
21646                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
21647                r.op(0, 0, w, db.top, Region.Op.UNION);
21648            }
21649            if (db.bottom < h) {
21650                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
21651                r.op(0, db.bottom, w, h, Region.Op.UNION);
21652            }
21653            final int[] location = attachInfo.mTransparentLocation;
21654            getLocationInWindow(location);
21655            r.translate(location[0], location[1]);
21656            region.op(r, Region.Op.INTERSECT);
21657        } else {
21658            region.op(db, Region.Op.DIFFERENCE);
21659        }
21660    }
21661
21662    private void checkForLongClick(int delayOffset, float x, float y) {
21663        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
21664            mHasPerformedLongPress = false;
21665
21666            if (mPendingCheckForLongPress == null) {
21667                mPendingCheckForLongPress = new CheckForLongPress();
21668            }
21669            mPendingCheckForLongPress.setAnchor(x, y);
21670            mPendingCheckForLongPress.rememberWindowAttachCount();
21671            mPendingCheckForLongPress.rememberPressedState();
21672            postDelayed(mPendingCheckForLongPress,
21673                    ViewConfiguration.getLongPressTimeout() - delayOffset);
21674        }
21675    }
21676
21677    /**
21678     * Inflate a view from an XML resource.  This convenience method wraps the {@link
21679     * LayoutInflater} class, which provides a full range of options for view inflation.
21680     *
21681     * @param context The Context object for your activity or application.
21682     * @param resource The resource ID to inflate
21683     * @param root A view group that will be the parent.  Used to properly inflate the
21684     * layout_* parameters.
21685     * @see LayoutInflater
21686     */
21687    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
21688        LayoutInflater factory = LayoutInflater.from(context);
21689        return factory.inflate(resource, root);
21690    }
21691
21692    /**
21693     * Scroll the view with standard behavior for scrolling beyond the normal
21694     * content boundaries. Views that call this method should override
21695     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
21696     * results of an over-scroll operation.
21697     *
21698     * Views can use this method to handle any touch or fling-based scrolling.
21699     *
21700     * @param deltaX Change in X in pixels
21701     * @param deltaY Change in Y in pixels
21702     * @param scrollX Current X scroll value in pixels before applying deltaX
21703     * @param scrollY Current Y scroll value in pixels before applying deltaY
21704     * @param scrollRangeX Maximum content scroll range along the X axis
21705     * @param scrollRangeY Maximum content scroll range along the Y axis
21706     * @param maxOverScrollX Number of pixels to overscroll by in either direction
21707     *          along the X axis.
21708     * @param maxOverScrollY Number of pixels to overscroll by in either direction
21709     *          along the Y axis.
21710     * @param isTouchEvent true if this scroll operation is the result of a touch event.
21711     * @return true if scrolling was clamped to an over-scroll boundary along either
21712     *          axis, false otherwise.
21713     */
21714    @SuppressWarnings({"UnusedParameters"})
21715    protected boolean overScrollBy(int deltaX, int deltaY,
21716            int scrollX, int scrollY,
21717            int scrollRangeX, int scrollRangeY,
21718            int maxOverScrollX, int maxOverScrollY,
21719            boolean isTouchEvent) {
21720        final int overScrollMode = mOverScrollMode;
21721        final boolean canScrollHorizontal =
21722                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21723        final boolean canScrollVertical =
21724                computeVerticalScrollRange() > computeVerticalScrollExtent();
21725        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21726                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21727        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21728                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21729
21730        int newScrollX = scrollX + deltaX;
21731        if (!overScrollHorizontal) {
21732            maxOverScrollX = 0;
21733        }
21734
21735        int newScrollY = scrollY + deltaY;
21736        if (!overScrollVertical) {
21737            maxOverScrollY = 0;
21738        }
21739
21740        // Clamp values if at the limits and record
21741        final int left = -maxOverScrollX;
21742        final int right = maxOverScrollX + scrollRangeX;
21743        final int top = -maxOverScrollY;
21744        final int bottom = maxOverScrollY + scrollRangeY;
21745
21746        boolean clampedX = false;
21747        if (newScrollX > right) {
21748            newScrollX = right;
21749            clampedX = true;
21750        } else if (newScrollX < left) {
21751            newScrollX = left;
21752            clampedX = true;
21753        }
21754
21755        boolean clampedY = false;
21756        if (newScrollY > bottom) {
21757            newScrollY = bottom;
21758            clampedY = true;
21759        } else if (newScrollY < top) {
21760            newScrollY = top;
21761            clampedY = true;
21762        }
21763
21764        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
21765
21766        return clampedX || clampedY;
21767    }
21768
21769    /**
21770     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
21771     * respond to the results of an over-scroll operation.
21772     *
21773     * @param scrollX New X scroll value in pixels
21774     * @param scrollY New Y scroll value in pixels
21775     * @param clampedX True if scrollX was clamped to an over-scroll boundary
21776     * @param clampedY True if scrollY was clamped to an over-scroll boundary
21777     */
21778    protected void onOverScrolled(int scrollX, int scrollY,
21779            boolean clampedX, boolean clampedY) {
21780        // Intentionally empty.
21781    }
21782
21783    /**
21784     * Returns the over-scroll mode for this view. The result will be
21785     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21786     * (allow over-scrolling only if the view content is larger than the container),
21787     * or {@link #OVER_SCROLL_NEVER}.
21788     *
21789     * @return This view's over-scroll mode.
21790     */
21791    public int getOverScrollMode() {
21792        return mOverScrollMode;
21793    }
21794
21795    /**
21796     * Set the over-scroll mode for this view. Valid over-scroll modes are
21797     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21798     * (allow over-scrolling only if the view content is larger than the container),
21799     * or {@link #OVER_SCROLL_NEVER}.
21800     *
21801     * Setting the over-scroll mode of a view will have an effect only if the
21802     * view is capable of scrolling.
21803     *
21804     * @param overScrollMode The new over-scroll mode for this view.
21805     */
21806    public void setOverScrollMode(int overScrollMode) {
21807        if (overScrollMode != OVER_SCROLL_ALWAYS &&
21808                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
21809                overScrollMode != OVER_SCROLL_NEVER) {
21810            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
21811        }
21812        mOverScrollMode = overScrollMode;
21813    }
21814
21815    /**
21816     * Enable or disable nested scrolling for this view.
21817     *
21818     * <p>If this property is set to true the view will be permitted to initiate nested
21819     * scrolling operations with a compatible parent view in the current hierarchy. If this
21820     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
21821     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
21822     * the nested scroll.</p>
21823     *
21824     * @param enabled true to enable nested scrolling, false to disable
21825     *
21826     * @see #isNestedScrollingEnabled()
21827     */
21828    public void setNestedScrollingEnabled(boolean enabled) {
21829        if (enabled) {
21830            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
21831        } else {
21832            stopNestedScroll();
21833            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
21834        }
21835    }
21836
21837    /**
21838     * Returns true if nested scrolling is enabled for this view.
21839     *
21840     * <p>If nested scrolling is enabled and this View class implementation supports it,
21841     * this view will act as a nested scrolling child view when applicable, forwarding data
21842     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21843     * parent.</p>
21844     *
21845     * @return true if nested scrolling is enabled
21846     *
21847     * @see #setNestedScrollingEnabled(boolean)
21848     */
21849    public boolean isNestedScrollingEnabled() {
21850        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21851                PFLAG3_NESTED_SCROLLING_ENABLED;
21852    }
21853
21854    /**
21855     * Begin a nestable scroll operation along the given axes.
21856     *
21857     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21858     *
21859     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21860     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21861     * In the case of touch scrolling the nested scroll will be terminated automatically in
21862     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21863     * In the event of programmatic scrolling the caller must explicitly call
21864     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21865     *
21866     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21867     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21868     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21869     *
21870     * <p>At each incremental step of the scroll the caller should invoke
21871     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21872     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21873     * parent at least partially consumed the scroll and the caller should adjust the amount it
21874     * scrolls by.</p>
21875     *
21876     * <p>After applying the remainder of the scroll delta the caller should invoke
21877     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21878     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21879     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21880     * </p>
21881     *
21882     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21883     *             {@link #SCROLL_AXIS_VERTICAL}.
21884     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21885     *         the current gesture.
21886     *
21887     * @see #stopNestedScroll()
21888     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21889     * @see #dispatchNestedScroll(int, int, int, int, int[])
21890     */
21891    public boolean startNestedScroll(int axes) {
21892        if (hasNestedScrollingParent()) {
21893            // Already in progress
21894            return true;
21895        }
21896        if (isNestedScrollingEnabled()) {
21897            ViewParent p = getParent();
21898            View child = this;
21899            while (p != null) {
21900                try {
21901                    if (p.onStartNestedScroll(child, this, axes)) {
21902                        mNestedScrollingParent = p;
21903                        p.onNestedScrollAccepted(child, this, axes);
21904                        return true;
21905                    }
21906                } catch (AbstractMethodError e) {
21907                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21908                            "method onStartNestedScroll", e);
21909                    // Allow the search upward to continue
21910                }
21911                if (p instanceof View) {
21912                    child = (View) p;
21913                }
21914                p = p.getParent();
21915            }
21916        }
21917        return false;
21918    }
21919
21920    /**
21921     * Stop a nested scroll in progress.
21922     *
21923     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21924     *
21925     * @see #startNestedScroll(int)
21926     */
21927    public void stopNestedScroll() {
21928        if (mNestedScrollingParent != null) {
21929            mNestedScrollingParent.onStopNestedScroll(this);
21930            mNestedScrollingParent = null;
21931        }
21932    }
21933
21934    /**
21935     * Returns true if this view has a nested scrolling parent.
21936     *
21937     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21938     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21939     *
21940     * @return whether this view has a nested scrolling parent
21941     */
21942    public boolean hasNestedScrollingParent() {
21943        return mNestedScrollingParent != null;
21944    }
21945
21946    /**
21947     * Dispatch one step of a nested scroll in progress.
21948     *
21949     * <p>Implementations of views that support nested scrolling should call this to report
21950     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21951     * is not currently in progress or nested scrolling is not
21952     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21953     *
21954     * <p>Compatible View implementations should also call
21955     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21956     * consuming a component of the scroll event themselves.</p>
21957     *
21958     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21959     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21960     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21961     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21962     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21963     *                       in local view coordinates of this view from before this operation
21964     *                       to after it completes. View implementations may use this to adjust
21965     *                       expected input coordinate tracking.
21966     * @return true if the event was dispatched, false if it could not be dispatched.
21967     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21968     */
21969    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21970            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21971        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21972            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21973                int startX = 0;
21974                int startY = 0;
21975                if (offsetInWindow != null) {
21976                    getLocationInWindow(offsetInWindow);
21977                    startX = offsetInWindow[0];
21978                    startY = offsetInWindow[1];
21979                }
21980
21981                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21982                        dxUnconsumed, dyUnconsumed);
21983
21984                if (offsetInWindow != null) {
21985                    getLocationInWindow(offsetInWindow);
21986                    offsetInWindow[0] -= startX;
21987                    offsetInWindow[1] -= startY;
21988                }
21989                return true;
21990            } else if (offsetInWindow != null) {
21991                // No motion, no dispatch. Keep offsetInWindow up to date.
21992                offsetInWindow[0] = 0;
21993                offsetInWindow[1] = 0;
21994            }
21995        }
21996        return false;
21997    }
21998
21999    /**
22000     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
22001     *
22002     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
22003     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
22004     * scrolling operation to consume some or all of the scroll operation before the child view
22005     * consumes it.</p>
22006     *
22007     * @param dx Horizontal scroll distance in pixels
22008     * @param dy Vertical scroll distance in pixels
22009     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
22010     *                 and consumed[1] the consumed dy.
22011     * @param offsetInWindow Optional. If not null, on return this will contain the offset
22012     *                       in local view coordinates of this view from before this operation
22013     *                       to after it completes. View implementations may use this to adjust
22014     *                       expected input coordinate tracking.
22015     * @return true if the parent consumed some or all of the scroll delta
22016     * @see #dispatchNestedScroll(int, int, int, int, int[])
22017     */
22018    public boolean dispatchNestedPreScroll(int dx, int dy,
22019            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
22020        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22021            if (dx != 0 || dy != 0) {
22022                int startX = 0;
22023                int startY = 0;
22024                if (offsetInWindow != null) {
22025                    getLocationInWindow(offsetInWindow);
22026                    startX = offsetInWindow[0];
22027                    startY = offsetInWindow[1];
22028                }
22029
22030                if (consumed == null) {
22031                    if (mTempNestedScrollConsumed == null) {
22032                        mTempNestedScrollConsumed = new int[2];
22033                    }
22034                    consumed = mTempNestedScrollConsumed;
22035                }
22036                consumed[0] = 0;
22037                consumed[1] = 0;
22038                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
22039
22040                if (offsetInWindow != null) {
22041                    getLocationInWindow(offsetInWindow);
22042                    offsetInWindow[0] -= startX;
22043                    offsetInWindow[1] -= startY;
22044                }
22045                return consumed[0] != 0 || consumed[1] != 0;
22046            } else if (offsetInWindow != null) {
22047                offsetInWindow[0] = 0;
22048                offsetInWindow[1] = 0;
22049            }
22050        }
22051        return false;
22052    }
22053
22054    /**
22055     * Dispatch a fling to a nested scrolling parent.
22056     *
22057     * <p>This method should be used to indicate that a nested scrolling child has detected
22058     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
22059     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
22060     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
22061     * along a scrollable axis.</p>
22062     *
22063     * <p>If a nested scrolling child view would normally fling but it is at the edge of
22064     * its own content, it can use this method to delegate the fling to its nested scrolling
22065     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
22066     *
22067     * @param velocityX Horizontal fling velocity in pixels per second
22068     * @param velocityY Vertical fling velocity in pixels per second
22069     * @param consumed true if the child consumed the fling, false otherwise
22070     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
22071     */
22072    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
22073        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22074            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
22075        }
22076        return false;
22077    }
22078
22079    /**
22080     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
22081     *
22082     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
22083     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
22084     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
22085     * before the child view consumes it. If this method returns <code>true</code>, a nested
22086     * parent view consumed the fling and this view should not scroll as a result.</p>
22087     *
22088     * <p>For a better user experience, only one view in a nested scrolling chain should consume
22089     * the fling at a time. If a parent view consumed the fling this method will return false.
22090     * Custom view implementations should account for this in two ways:</p>
22091     *
22092     * <ul>
22093     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
22094     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
22095     *     position regardless.</li>
22096     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
22097     *     even to settle back to a valid idle position.</li>
22098     * </ul>
22099     *
22100     * <p>Views should also not offer fling velocities to nested parent views along an axis
22101     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
22102     * should not offer a horizontal fling velocity to its parents since scrolling along that
22103     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
22104     *
22105     * @param velocityX Horizontal fling velocity in pixels per second
22106     * @param velocityY Vertical fling velocity in pixels per second
22107     * @return true if a nested scrolling parent consumed the fling
22108     */
22109    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
22110        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22111            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
22112        }
22113        return false;
22114    }
22115
22116    /**
22117     * Gets a scale factor that determines the distance the view should scroll
22118     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
22119     * @return The vertical scroll scale factor.
22120     * @hide
22121     */
22122    protected float getVerticalScrollFactor() {
22123        if (mVerticalScrollFactor == 0) {
22124            TypedValue outValue = new TypedValue();
22125            if (!mContext.getTheme().resolveAttribute(
22126                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
22127                throw new IllegalStateException(
22128                        "Expected theme to define listPreferredItemHeight.");
22129            }
22130            mVerticalScrollFactor = outValue.getDimension(
22131                    mContext.getResources().getDisplayMetrics());
22132        }
22133        return mVerticalScrollFactor;
22134    }
22135
22136    /**
22137     * Gets a scale factor that determines the distance the view should scroll
22138     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
22139     * @return The horizontal scroll scale factor.
22140     * @hide
22141     */
22142    protected float getHorizontalScrollFactor() {
22143        // TODO: Should use something else.
22144        return getVerticalScrollFactor();
22145    }
22146
22147    /**
22148     * Return the value specifying the text direction or policy that was set with
22149     * {@link #setTextDirection(int)}.
22150     *
22151     * @return the defined text direction. It can be one of:
22152     *
22153     * {@link #TEXT_DIRECTION_INHERIT},
22154     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22155     * {@link #TEXT_DIRECTION_ANY_RTL},
22156     * {@link #TEXT_DIRECTION_LTR},
22157     * {@link #TEXT_DIRECTION_RTL},
22158     * {@link #TEXT_DIRECTION_LOCALE},
22159     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22160     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22161     *
22162     * @attr ref android.R.styleable#View_textDirection
22163     *
22164     * @hide
22165     */
22166    @ViewDebug.ExportedProperty(category = "text", mapping = {
22167            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22168            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22169            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22170            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22171            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22172            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22173            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22174            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22175    })
22176    public int getRawTextDirection() {
22177        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
22178    }
22179
22180    /**
22181     * Set the text direction.
22182     *
22183     * @param textDirection the direction to set. Should be one of:
22184     *
22185     * {@link #TEXT_DIRECTION_INHERIT},
22186     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22187     * {@link #TEXT_DIRECTION_ANY_RTL},
22188     * {@link #TEXT_DIRECTION_LTR},
22189     * {@link #TEXT_DIRECTION_RTL},
22190     * {@link #TEXT_DIRECTION_LOCALE}
22191     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22192     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
22193     *
22194     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
22195     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
22196     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
22197     *
22198     * @attr ref android.R.styleable#View_textDirection
22199     */
22200    public void setTextDirection(int textDirection) {
22201        if (getRawTextDirection() != textDirection) {
22202            // Reset the current text direction and the resolved one
22203            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
22204            resetResolvedTextDirection();
22205            // Set the new text direction
22206            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
22207            // Do resolution
22208            resolveTextDirection();
22209            // Notify change
22210            onRtlPropertiesChanged(getLayoutDirection());
22211            // Refresh
22212            requestLayout();
22213            invalidate(true);
22214        }
22215    }
22216
22217    /**
22218     * Return the resolved text direction.
22219     *
22220     * @return the resolved text direction. Returns one of:
22221     *
22222     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22223     * {@link #TEXT_DIRECTION_ANY_RTL},
22224     * {@link #TEXT_DIRECTION_LTR},
22225     * {@link #TEXT_DIRECTION_RTL},
22226     * {@link #TEXT_DIRECTION_LOCALE},
22227     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22228     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22229     *
22230     * @attr ref android.R.styleable#View_textDirection
22231     */
22232    @ViewDebug.ExportedProperty(category = "text", mapping = {
22233            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22234            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22235            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22236            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22237            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22238            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22239            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22240            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22241    })
22242    public int getTextDirection() {
22243        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
22244    }
22245
22246    /**
22247     * Resolve the text direction.
22248     *
22249     * @return true if resolution has been done, false otherwise.
22250     *
22251     * @hide
22252     */
22253    public boolean resolveTextDirection() {
22254        // Reset any previous text direction resolution
22255        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22256
22257        if (hasRtlSupport()) {
22258            // Set resolved text direction flag depending on text direction flag
22259            final int textDirection = getRawTextDirection();
22260            switch(textDirection) {
22261                case TEXT_DIRECTION_INHERIT:
22262                    if (!canResolveTextDirection()) {
22263                        // We cannot do the resolution if there is no parent, so use the default one
22264                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22265                        // Resolution will need to happen again later
22266                        return false;
22267                    }
22268
22269                    // Parent has not yet resolved, so we still return the default
22270                    try {
22271                        if (!mParent.isTextDirectionResolved()) {
22272                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22273                            // Resolution will need to happen again later
22274                            return false;
22275                        }
22276                    } catch (AbstractMethodError e) {
22277                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22278                                " does not fully implement ViewParent", e);
22279                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
22280                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22281                        return true;
22282                    }
22283
22284                    // Set current resolved direction to the same value as the parent's one
22285                    int parentResolvedDirection;
22286                    try {
22287                        parentResolvedDirection = mParent.getTextDirection();
22288                    } catch (AbstractMethodError e) {
22289                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22290                                " does not fully implement ViewParent", e);
22291                        parentResolvedDirection = TEXT_DIRECTION_LTR;
22292                    }
22293                    switch (parentResolvedDirection) {
22294                        case TEXT_DIRECTION_FIRST_STRONG:
22295                        case TEXT_DIRECTION_ANY_RTL:
22296                        case TEXT_DIRECTION_LTR:
22297                        case TEXT_DIRECTION_RTL:
22298                        case TEXT_DIRECTION_LOCALE:
22299                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
22300                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
22301                            mPrivateFlags2 |=
22302                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22303                            break;
22304                        default:
22305                            // Default resolved direction is "first strong" heuristic
22306                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22307                    }
22308                    break;
22309                case TEXT_DIRECTION_FIRST_STRONG:
22310                case TEXT_DIRECTION_ANY_RTL:
22311                case TEXT_DIRECTION_LTR:
22312                case TEXT_DIRECTION_RTL:
22313                case TEXT_DIRECTION_LOCALE:
22314                case TEXT_DIRECTION_FIRST_STRONG_LTR:
22315                case TEXT_DIRECTION_FIRST_STRONG_RTL:
22316                    // Resolved direction is the same as text direction
22317                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22318                    break;
22319                default:
22320                    // Default resolved direction is "first strong" heuristic
22321                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22322            }
22323        } else {
22324            // Default resolved direction is "first strong" heuristic
22325            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22326        }
22327
22328        // Set to resolved
22329        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
22330        return true;
22331    }
22332
22333    /**
22334     * Check if text direction resolution can be done.
22335     *
22336     * @return true if text direction resolution can be done otherwise return false.
22337     */
22338    public boolean canResolveTextDirection() {
22339        switch (getRawTextDirection()) {
22340            case TEXT_DIRECTION_INHERIT:
22341                if (mParent != null) {
22342                    try {
22343                        return mParent.canResolveTextDirection();
22344                    } catch (AbstractMethodError e) {
22345                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22346                                " does not fully implement ViewParent", e);
22347                    }
22348                }
22349                return false;
22350
22351            default:
22352                return true;
22353        }
22354    }
22355
22356    /**
22357     * Reset resolved text direction. Text direction will be resolved during a call to
22358     * {@link #onMeasure(int, int)}.
22359     *
22360     * @hide
22361     */
22362    public void resetResolvedTextDirection() {
22363        // Reset any previous text direction resolution
22364        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22365        // Set to default value
22366        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22367    }
22368
22369    /**
22370     * @return true if text direction is inherited.
22371     *
22372     * @hide
22373     */
22374    public boolean isTextDirectionInherited() {
22375        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
22376    }
22377
22378    /**
22379     * @return true if text direction is resolved.
22380     */
22381    public boolean isTextDirectionResolved() {
22382        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
22383    }
22384
22385    /**
22386     * Return the value specifying the text alignment or policy that was set with
22387     * {@link #setTextAlignment(int)}.
22388     *
22389     * @return the defined text alignment. It can be one of:
22390     *
22391     * {@link #TEXT_ALIGNMENT_INHERIT},
22392     * {@link #TEXT_ALIGNMENT_GRAVITY},
22393     * {@link #TEXT_ALIGNMENT_CENTER},
22394     * {@link #TEXT_ALIGNMENT_TEXT_START},
22395     * {@link #TEXT_ALIGNMENT_TEXT_END},
22396     * {@link #TEXT_ALIGNMENT_VIEW_START},
22397     * {@link #TEXT_ALIGNMENT_VIEW_END}
22398     *
22399     * @attr ref android.R.styleable#View_textAlignment
22400     *
22401     * @hide
22402     */
22403    @ViewDebug.ExportedProperty(category = "text", mapping = {
22404            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22405            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22406            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22407            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22408            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22409            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22410            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22411    })
22412    @TextAlignment
22413    public int getRawTextAlignment() {
22414        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
22415    }
22416
22417    /**
22418     * Set the text alignment.
22419     *
22420     * @param textAlignment The text alignment to set. Should be one of
22421     *
22422     * {@link #TEXT_ALIGNMENT_INHERIT},
22423     * {@link #TEXT_ALIGNMENT_GRAVITY},
22424     * {@link #TEXT_ALIGNMENT_CENTER},
22425     * {@link #TEXT_ALIGNMENT_TEXT_START},
22426     * {@link #TEXT_ALIGNMENT_TEXT_END},
22427     * {@link #TEXT_ALIGNMENT_VIEW_START},
22428     * {@link #TEXT_ALIGNMENT_VIEW_END}
22429     *
22430     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
22431     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
22432     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
22433     *
22434     * @attr ref android.R.styleable#View_textAlignment
22435     */
22436    public void setTextAlignment(@TextAlignment int textAlignment) {
22437        if (textAlignment != getRawTextAlignment()) {
22438            // Reset the current and resolved text alignment
22439            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
22440            resetResolvedTextAlignment();
22441            // Set the new text alignment
22442            mPrivateFlags2 |=
22443                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
22444            // Do resolution
22445            resolveTextAlignment();
22446            // Notify change
22447            onRtlPropertiesChanged(getLayoutDirection());
22448            // Refresh
22449            requestLayout();
22450            invalidate(true);
22451        }
22452    }
22453
22454    /**
22455     * Return the resolved text alignment.
22456     *
22457     * @return the resolved text alignment. Returns one of:
22458     *
22459     * {@link #TEXT_ALIGNMENT_GRAVITY},
22460     * {@link #TEXT_ALIGNMENT_CENTER},
22461     * {@link #TEXT_ALIGNMENT_TEXT_START},
22462     * {@link #TEXT_ALIGNMENT_TEXT_END},
22463     * {@link #TEXT_ALIGNMENT_VIEW_START},
22464     * {@link #TEXT_ALIGNMENT_VIEW_END}
22465     *
22466     * @attr ref android.R.styleable#View_textAlignment
22467     */
22468    @ViewDebug.ExportedProperty(category = "text", mapping = {
22469            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22470            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22471            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22472            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22473            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22474            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22475            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22476    })
22477    @TextAlignment
22478    public int getTextAlignment() {
22479        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
22480                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
22481    }
22482
22483    /**
22484     * Resolve the text alignment.
22485     *
22486     * @return true if resolution has been done, false otherwise.
22487     *
22488     * @hide
22489     */
22490    public boolean resolveTextAlignment() {
22491        // Reset any previous text alignment resolution
22492        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22493
22494        if (hasRtlSupport()) {
22495            // Set resolved text alignment flag depending on text alignment flag
22496            final int textAlignment = getRawTextAlignment();
22497            switch (textAlignment) {
22498                case TEXT_ALIGNMENT_INHERIT:
22499                    // Check if we can resolve the text alignment
22500                    if (!canResolveTextAlignment()) {
22501                        // We cannot do the resolution if there is no parent so use the default
22502                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22503                        // Resolution will need to happen again later
22504                        return false;
22505                    }
22506
22507                    // Parent has not yet resolved, so we still return the default
22508                    try {
22509                        if (!mParent.isTextAlignmentResolved()) {
22510                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22511                            // Resolution will need to happen again later
22512                            return false;
22513                        }
22514                    } catch (AbstractMethodError e) {
22515                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22516                                " does not fully implement ViewParent", e);
22517                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
22518                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22519                        return true;
22520                    }
22521
22522                    int parentResolvedTextAlignment;
22523                    try {
22524                        parentResolvedTextAlignment = mParent.getTextAlignment();
22525                    } catch (AbstractMethodError e) {
22526                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22527                                " does not fully implement ViewParent", e);
22528                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
22529                    }
22530                    switch (parentResolvedTextAlignment) {
22531                        case TEXT_ALIGNMENT_GRAVITY:
22532                        case TEXT_ALIGNMENT_TEXT_START:
22533                        case TEXT_ALIGNMENT_TEXT_END:
22534                        case TEXT_ALIGNMENT_CENTER:
22535                        case TEXT_ALIGNMENT_VIEW_START:
22536                        case TEXT_ALIGNMENT_VIEW_END:
22537                            // Resolved text alignment is the same as the parent resolved
22538                            // text alignment
22539                            mPrivateFlags2 |=
22540                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22541                            break;
22542                        default:
22543                            // Use default resolved text alignment
22544                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22545                    }
22546                    break;
22547                case TEXT_ALIGNMENT_GRAVITY:
22548                case TEXT_ALIGNMENT_TEXT_START:
22549                case TEXT_ALIGNMENT_TEXT_END:
22550                case TEXT_ALIGNMENT_CENTER:
22551                case TEXT_ALIGNMENT_VIEW_START:
22552                case TEXT_ALIGNMENT_VIEW_END:
22553                    // Resolved text alignment is the same as text alignment
22554                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22555                    break;
22556                default:
22557                    // Use default resolved text alignment
22558                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22559            }
22560        } else {
22561            // Use default resolved text alignment
22562            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22563        }
22564
22565        // Set the resolved
22566        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22567        return true;
22568    }
22569
22570    /**
22571     * Check if text alignment resolution can be done.
22572     *
22573     * @return true if text alignment resolution can be done otherwise return false.
22574     */
22575    public boolean canResolveTextAlignment() {
22576        switch (getRawTextAlignment()) {
22577            case TEXT_DIRECTION_INHERIT:
22578                if (mParent != null) {
22579                    try {
22580                        return mParent.canResolveTextAlignment();
22581                    } catch (AbstractMethodError e) {
22582                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22583                                " does not fully implement ViewParent", e);
22584                    }
22585                }
22586                return false;
22587
22588            default:
22589                return true;
22590        }
22591    }
22592
22593    /**
22594     * Reset resolved text alignment. Text alignment will be resolved during a call to
22595     * {@link #onMeasure(int, int)}.
22596     *
22597     * @hide
22598     */
22599    public void resetResolvedTextAlignment() {
22600        // Reset any previous text alignment resolution
22601        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22602        // Set to default
22603        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22604    }
22605
22606    /**
22607     * @return true if text alignment is inherited.
22608     *
22609     * @hide
22610     */
22611    public boolean isTextAlignmentInherited() {
22612        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
22613    }
22614
22615    /**
22616     * @return true if text alignment is resolved.
22617     */
22618    public boolean isTextAlignmentResolved() {
22619        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22620    }
22621
22622    /**
22623     * Generate a value suitable for use in {@link #setId(int)}.
22624     * This value will not collide with ID values generated at build time by aapt for R.id.
22625     *
22626     * @return a generated ID value
22627     */
22628    public static int generateViewId() {
22629        for (;;) {
22630            final int result = sNextGeneratedId.get();
22631            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
22632            int newValue = result + 1;
22633            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
22634            if (sNextGeneratedId.compareAndSet(result, newValue)) {
22635                return result;
22636            }
22637        }
22638    }
22639
22640    private static boolean isViewIdGenerated(int id) {
22641        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
22642    }
22643
22644    /**
22645     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
22646     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
22647     *                           a normal View or a ViewGroup with
22648     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
22649     * @hide
22650     */
22651    public void captureTransitioningViews(List<View> transitioningViews) {
22652        if (getVisibility() == View.VISIBLE) {
22653            transitioningViews.add(this);
22654        }
22655    }
22656
22657    /**
22658     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
22659     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
22660     * @hide
22661     */
22662    public void findNamedViews(Map<String, View> namedElements) {
22663        if (getVisibility() == VISIBLE || mGhostView != null) {
22664            String transitionName = getTransitionName();
22665            if (transitionName != null) {
22666                namedElements.put(transitionName, this);
22667            }
22668        }
22669    }
22670
22671    /**
22672     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
22673     * The default implementation does not care the location or event types, but some subclasses
22674     * may use it (such as WebViews).
22675     * @param event The MotionEvent from a mouse
22676     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
22677     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
22678     * @see PointerIcon
22679     */
22680    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
22681        final float x = event.getX(pointerIndex);
22682        final float y = event.getY(pointerIndex);
22683        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
22684            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
22685        }
22686        return mPointerIcon;
22687    }
22688
22689    /**
22690     * Set the pointer icon for the current view.
22691     * Passing {@code null} will restore the pointer icon to its default value.
22692     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
22693     */
22694    public void setPointerIcon(PointerIcon pointerIcon) {
22695        mPointerIcon = pointerIcon;
22696        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
22697            return;
22698        }
22699        try {
22700            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
22701        } catch (RemoteException e) {
22702        }
22703    }
22704
22705    /**
22706     * Gets the pointer icon for the current view.
22707     */
22708    public PointerIcon getPointerIcon() {
22709        return mPointerIcon;
22710    }
22711
22712    /**
22713     * Checks pointer capture status.
22714     *
22715     * @return true if the view has pointer capture.
22716     * @see #requestPointerCapture()
22717     * @see #hasPointerCapture()
22718     */
22719    public boolean hasPointerCapture() {
22720        final ViewRootImpl viewRootImpl = getViewRootImpl();
22721        if (viewRootImpl == null) {
22722            return false;
22723        }
22724        return viewRootImpl.hasPointerCapture();
22725    }
22726
22727    /**
22728     * Requests pointer capture mode.
22729     * <p>
22730     * When the window has pointer capture, the mouse pointer icon will disappear and will not
22731     * change its position. Further mouse will be dispatched with the source
22732     * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available
22733     * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events
22734     * (touchscreens, or stylus) will not be affected.
22735     * <p>
22736     * If the window already has pointer capture, this call does nothing.
22737     * <p>
22738     * The capture may be released through {@link #releasePointerCapture()}, or will be lost
22739     * automatically when the window loses focus.
22740     *
22741     * @see #releasePointerCapture()
22742     * @see #hasPointerCapture()
22743     */
22744    public void requestPointerCapture() {
22745        final ViewRootImpl viewRootImpl = getViewRootImpl();
22746        if (viewRootImpl != null) {
22747            viewRootImpl.requestPointerCapture(true);
22748        }
22749    }
22750
22751
22752    /**
22753     * Releases the pointer capture.
22754     * <p>
22755     * If the window does not have pointer capture, this call will do nothing.
22756     * @see #requestPointerCapture()
22757     * @see #hasPointerCapture()
22758     */
22759    public void releasePointerCapture() {
22760        final ViewRootImpl viewRootImpl = getViewRootImpl();
22761        if (viewRootImpl != null) {
22762            viewRootImpl.requestPointerCapture(false);
22763        }
22764    }
22765
22766    /**
22767     * Called when the window has just acquired or lost pointer capture.
22768     *
22769     * @param hasCapture True if the view now has pointerCapture, false otherwise.
22770     */
22771    @CallSuper
22772    public void onPointerCaptureChange(boolean hasCapture) {
22773    }
22774
22775    /**
22776     * @see #onPointerCaptureChange
22777     */
22778    public void dispatchPointerCaptureChanged(boolean hasCapture) {
22779        onPointerCaptureChange(hasCapture);
22780    }
22781
22782    /**
22783     * Implement this method to handle captured pointer events
22784     *
22785     * @param event The captured pointer event.
22786     * @return True if the event was handled, false otherwise.
22787     * @see #requestPointerCapture()
22788     */
22789    public boolean onCapturedPointerEvent(MotionEvent event) {
22790        return false;
22791    }
22792
22793    /**
22794     * Interface definition for a callback to be invoked when a captured pointer event
22795     * is being dispatched this view. The callback will be invoked before the event is
22796     * given to the view.
22797     */
22798    public interface OnCapturedPointerListener {
22799        /**
22800         * Called when a captured pointer event is dispatched to a view.
22801         * @param view The view this event has been dispatched to.
22802         * @param event The captured event.
22803         * @return True if the listener has consumed the event, false otherwise.
22804         */
22805        boolean onCapturedPointer(View view, MotionEvent event);
22806    }
22807
22808    /**
22809     * Set a listener to receive callbacks when the pointer capture state of a view changes.
22810     * @param l  The {@link OnCapturedPointerListener} to receive callbacks.
22811     */
22812    public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
22813        getListenerInfo().mOnCapturedPointerListener = l;
22814    }
22815
22816    // Properties
22817    //
22818    /**
22819     * A Property wrapper around the <code>alpha</code> functionality handled by the
22820     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
22821     */
22822    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
22823        @Override
22824        public void setValue(View object, float value) {
22825            object.setAlpha(value);
22826        }
22827
22828        @Override
22829        public Float get(View object) {
22830            return object.getAlpha();
22831        }
22832    };
22833
22834    /**
22835     * A Property wrapper around the <code>translationX</code> functionality handled by the
22836     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
22837     */
22838    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
22839        @Override
22840        public void setValue(View object, float value) {
22841            object.setTranslationX(value);
22842        }
22843
22844                @Override
22845        public Float get(View object) {
22846            return object.getTranslationX();
22847        }
22848    };
22849
22850    /**
22851     * A Property wrapper around the <code>translationY</code> functionality handled by the
22852     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
22853     */
22854    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
22855        @Override
22856        public void setValue(View object, float value) {
22857            object.setTranslationY(value);
22858        }
22859
22860        @Override
22861        public Float get(View object) {
22862            return object.getTranslationY();
22863        }
22864    };
22865
22866    /**
22867     * A Property wrapper around the <code>translationZ</code> functionality handled by the
22868     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
22869     */
22870    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
22871        @Override
22872        public void setValue(View object, float value) {
22873            object.setTranslationZ(value);
22874        }
22875
22876        @Override
22877        public Float get(View object) {
22878            return object.getTranslationZ();
22879        }
22880    };
22881
22882    /**
22883     * A Property wrapper around the <code>x</code> functionality handled by the
22884     * {@link View#setX(float)} and {@link View#getX()} methods.
22885     */
22886    public static final Property<View, Float> X = new FloatProperty<View>("x") {
22887        @Override
22888        public void setValue(View object, float value) {
22889            object.setX(value);
22890        }
22891
22892        @Override
22893        public Float get(View object) {
22894            return object.getX();
22895        }
22896    };
22897
22898    /**
22899     * A Property wrapper around the <code>y</code> functionality handled by the
22900     * {@link View#setY(float)} and {@link View#getY()} methods.
22901     */
22902    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
22903        @Override
22904        public void setValue(View object, float value) {
22905            object.setY(value);
22906        }
22907
22908        @Override
22909        public Float get(View object) {
22910            return object.getY();
22911        }
22912    };
22913
22914    /**
22915     * A Property wrapper around the <code>z</code> functionality handled by the
22916     * {@link View#setZ(float)} and {@link View#getZ()} methods.
22917     */
22918    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
22919        @Override
22920        public void setValue(View object, float value) {
22921            object.setZ(value);
22922        }
22923
22924        @Override
22925        public Float get(View object) {
22926            return object.getZ();
22927        }
22928    };
22929
22930    /**
22931     * A Property wrapper around the <code>rotation</code> functionality handled by the
22932     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
22933     */
22934    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
22935        @Override
22936        public void setValue(View object, float value) {
22937            object.setRotation(value);
22938        }
22939
22940        @Override
22941        public Float get(View object) {
22942            return object.getRotation();
22943        }
22944    };
22945
22946    /**
22947     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22948     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22949     */
22950    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22951        @Override
22952        public void setValue(View object, float value) {
22953            object.setRotationX(value);
22954        }
22955
22956        @Override
22957        public Float get(View object) {
22958            return object.getRotationX();
22959        }
22960    };
22961
22962    /**
22963     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22964     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22965     */
22966    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22967        @Override
22968        public void setValue(View object, float value) {
22969            object.setRotationY(value);
22970        }
22971
22972        @Override
22973        public Float get(View object) {
22974            return object.getRotationY();
22975        }
22976    };
22977
22978    /**
22979     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22980     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22981     */
22982    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22983        @Override
22984        public void setValue(View object, float value) {
22985            object.setScaleX(value);
22986        }
22987
22988        @Override
22989        public Float get(View object) {
22990            return object.getScaleX();
22991        }
22992    };
22993
22994    /**
22995     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22996     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22997     */
22998    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22999        @Override
23000        public void setValue(View object, float value) {
23001            object.setScaleY(value);
23002        }
23003
23004        @Override
23005        public Float get(View object) {
23006            return object.getScaleY();
23007        }
23008    };
23009
23010    /**
23011     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
23012     * Each MeasureSpec represents a requirement for either the width or the height.
23013     * A MeasureSpec is comprised of a size and a mode. There are three possible
23014     * modes:
23015     * <dl>
23016     * <dt>UNSPECIFIED</dt>
23017     * <dd>
23018     * The parent has not imposed any constraint on the child. It can be whatever size
23019     * it wants.
23020     * </dd>
23021     *
23022     * <dt>EXACTLY</dt>
23023     * <dd>
23024     * The parent has determined an exact size for the child. The child is going to be
23025     * given those bounds regardless of how big it wants to be.
23026     * </dd>
23027     *
23028     * <dt>AT_MOST</dt>
23029     * <dd>
23030     * The child can be as large as it wants up to the specified size.
23031     * </dd>
23032     * </dl>
23033     *
23034     * MeasureSpecs are implemented as ints to reduce object allocation. This class
23035     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
23036     */
23037    public static class MeasureSpec {
23038        private static final int MODE_SHIFT = 30;
23039        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
23040
23041        /** @hide */
23042        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
23043        @Retention(RetentionPolicy.SOURCE)
23044        public @interface MeasureSpecMode {}
23045
23046        /**
23047         * Measure specification mode: The parent has not imposed any constraint
23048         * on the child. It can be whatever size it wants.
23049         */
23050        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
23051
23052        /**
23053         * Measure specification mode: The parent has determined an exact size
23054         * for the child. The child is going to be given those bounds regardless
23055         * of how big it wants to be.
23056         */
23057        public static final int EXACTLY     = 1 << MODE_SHIFT;
23058
23059        /**
23060         * Measure specification mode: The child can be as large as it wants up
23061         * to the specified size.
23062         */
23063        public static final int AT_MOST     = 2 << MODE_SHIFT;
23064
23065        /**
23066         * Creates a measure specification based on the supplied size and mode.
23067         *
23068         * The mode must always be one of the following:
23069         * <ul>
23070         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
23071         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
23072         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
23073         * </ul>
23074         *
23075         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
23076         * implementation was such that the order of arguments did not matter
23077         * and overflow in either value could impact the resulting MeasureSpec.
23078         * {@link android.widget.RelativeLayout} was affected by this bug.
23079         * Apps targeting API levels greater than 17 will get the fixed, more strict
23080         * behavior.</p>
23081         *
23082         * @param size the size of the measure specification
23083         * @param mode the mode of the measure specification
23084         * @return the measure specification based on size and mode
23085         */
23086        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
23087                                          @MeasureSpecMode int mode) {
23088            if (sUseBrokenMakeMeasureSpec) {
23089                return size + mode;
23090            } else {
23091                return (size & ~MODE_MASK) | (mode & MODE_MASK);
23092            }
23093        }
23094
23095        /**
23096         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
23097         * will automatically get a size of 0. Older apps expect this.
23098         *
23099         * @hide internal use only for compatibility with system widgets and older apps
23100         */
23101        public static int makeSafeMeasureSpec(int size, int mode) {
23102            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
23103                return 0;
23104            }
23105            return makeMeasureSpec(size, mode);
23106        }
23107
23108        /**
23109         * Extracts the mode from the supplied measure specification.
23110         *
23111         * @param measureSpec the measure specification to extract the mode from
23112         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
23113         *         {@link android.view.View.MeasureSpec#AT_MOST} or
23114         *         {@link android.view.View.MeasureSpec#EXACTLY}
23115         */
23116        @MeasureSpecMode
23117        public static int getMode(int measureSpec) {
23118            //noinspection ResourceType
23119            return (measureSpec & MODE_MASK);
23120        }
23121
23122        /**
23123         * Extracts the size from the supplied measure specification.
23124         *
23125         * @param measureSpec the measure specification to extract the size from
23126         * @return the size in pixels defined in the supplied measure specification
23127         */
23128        public static int getSize(int measureSpec) {
23129            return (measureSpec & ~MODE_MASK);
23130        }
23131
23132        static int adjust(int measureSpec, int delta) {
23133            final int mode = getMode(measureSpec);
23134            int size = getSize(measureSpec);
23135            if (mode == UNSPECIFIED) {
23136                // No need to adjust size for UNSPECIFIED mode.
23137                return makeMeasureSpec(size, UNSPECIFIED);
23138            }
23139            size += delta;
23140            if (size < 0) {
23141                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
23142                        ") spec: " + toString(measureSpec) + " delta: " + delta);
23143                size = 0;
23144            }
23145            return makeMeasureSpec(size, mode);
23146        }
23147
23148        /**
23149         * Returns a String representation of the specified measure
23150         * specification.
23151         *
23152         * @param measureSpec the measure specification to convert to a String
23153         * @return a String with the following format: "MeasureSpec: MODE SIZE"
23154         */
23155        public static String toString(int measureSpec) {
23156            int mode = getMode(measureSpec);
23157            int size = getSize(measureSpec);
23158
23159            StringBuilder sb = new StringBuilder("MeasureSpec: ");
23160
23161            if (mode == UNSPECIFIED)
23162                sb.append("UNSPECIFIED ");
23163            else if (mode == EXACTLY)
23164                sb.append("EXACTLY ");
23165            else if (mode == AT_MOST)
23166                sb.append("AT_MOST ");
23167            else
23168                sb.append(mode).append(" ");
23169
23170            sb.append(size);
23171            return sb.toString();
23172        }
23173    }
23174
23175    private final class CheckForLongPress implements Runnable {
23176        private int mOriginalWindowAttachCount;
23177        private float mX;
23178        private float mY;
23179        private boolean mOriginalPressedState;
23180
23181        @Override
23182        public void run() {
23183            if ((mOriginalPressedState == isPressed()) && (mParent != null)
23184                    && mOriginalWindowAttachCount == mWindowAttachCount) {
23185                if (performLongClick(mX, mY)) {
23186                    mHasPerformedLongPress = true;
23187                }
23188            }
23189        }
23190
23191        public void setAnchor(float x, float y) {
23192            mX = x;
23193            mY = y;
23194        }
23195
23196        public void rememberWindowAttachCount() {
23197            mOriginalWindowAttachCount = mWindowAttachCount;
23198        }
23199
23200        public void rememberPressedState() {
23201            mOriginalPressedState = isPressed();
23202        }
23203    }
23204
23205    private final class CheckForTap implements Runnable {
23206        public float x;
23207        public float y;
23208
23209        @Override
23210        public void run() {
23211            mPrivateFlags &= ~PFLAG_PREPRESSED;
23212            setPressed(true, x, y);
23213            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
23214        }
23215    }
23216
23217    private final class PerformClick implements Runnable {
23218        @Override
23219        public void run() {
23220            performClick();
23221        }
23222    }
23223
23224    /**
23225     * This method returns a ViewPropertyAnimator object, which can be used to animate
23226     * specific properties on this View.
23227     *
23228     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
23229     */
23230    public ViewPropertyAnimator animate() {
23231        if (mAnimator == null) {
23232            mAnimator = new ViewPropertyAnimator(this);
23233        }
23234        return mAnimator;
23235    }
23236
23237    /**
23238     * Sets the name of the View to be used to identify Views in Transitions.
23239     * Names should be unique in the View hierarchy.
23240     *
23241     * @param transitionName The name of the View to uniquely identify it for Transitions.
23242     */
23243    public final void setTransitionName(String transitionName) {
23244        mTransitionName = transitionName;
23245    }
23246
23247    /**
23248     * Returns the name of the View to be used to identify Views in Transitions.
23249     * Names should be unique in the View hierarchy.
23250     *
23251     * <p>This returns null if the View has not been given a name.</p>
23252     *
23253     * @return The name used of the View to be used to identify Views in Transitions or null
23254     * if no name has been given.
23255     */
23256    @ViewDebug.ExportedProperty
23257    public String getTransitionName() {
23258        return mTransitionName;
23259    }
23260
23261    /**
23262     * @hide
23263     */
23264    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
23265        // Do nothing.
23266    }
23267
23268    /**
23269     * Interface definition for a callback to be invoked when a hardware key event is
23270     * dispatched to this view. The callback will be invoked before the key event is
23271     * given to the view. This is only useful for hardware keyboards; a software input
23272     * method has no obligation to trigger this listener.
23273     */
23274    public interface OnKeyListener {
23275        /**
23276         * Called when a hardware key is dispatched to a view. This allows listeners to
23277         * get a chance to respond before the target view.
23278         * <p>Key presses in software keyboards will generally NOT trigger this method,
23279         * although some may elect to do so in some situations. Do not assume a
23280         * software input method has to be key-based; even if it is, it may use key presses
23281         * in a different way than you expect, so there is no way to reliably catch soft
23282         * input key presses.
23283         *
23284         * @param v The view the key has been dispatched to.
23285         * @param keyCode The code for the physical key that was pressed
23286         * @param event The KeyEvent object containing full information about
23287         *        the event.
23288         * @return True if the listener has consumed the event, false otherwise.
23289         */
23290        boolean onKey(View v, int keyCode, KeyEvent event);
23291    }
23292
23293    /**
23294     * Interface definition for a callback to be invoked when a touch event is
23295     * dispatched to this view. The callback will be invoked before the touch
23296     * event is given to the view.
23297     */
23298    public interface OnTouchListener {
23299        /**
23300         * Called when a touch event is dispatched to a view. This allows listeners to
23301         * get a chance to respond before the target view.
23302         *
23303         * @param v The view the touch event has been dispatched to.
23304         * @param event The MotionEvent object containing full information about
23305         *        the event.
23306         * @return True if the listener has consumed the event, false otherwise.
23307         */
23308        boolean onTouch(View v, MotionEvent event);
23309    }
23310
23311    /**
23312     * Interface definition for a callback to be invoked when a hover event is
23313     * dispatched to this view. The callback will be invoked before the hover
23314     * event is given to the view.
23315     */
23316    public interface OnHoverListener {
23317        /**
23318         * Called when a hover event is dispatched to a view. This allows listeners to
23319         * get a chance to respond before the target view.
23320         *
23321         * @param v The view the hover event has been dispatched to.
23322         * @param event The MotionEvent object containing full information about
23323         *        the event.
23324         * @return True if the listener has consumed the event, false otherwise.
23325         */
23326        boolean onHover(View v, MotionEvent event);
23327    }
23328
23329    /**
23330     * Interface definition for a callback to be invoked when a generic motion event is
23331     * dispatched to this view. The callback will be invoked before the generic motion
23332     * event is given to the view.
23333     */
23334    public interface OnGenericMotionListener {
23335        /**
23336         * Called when a generic motion event is dispatched to a view. This allows listeners to
23337         * get a chance to respond before the target view.
23338         *
23339         * @param v The view the generic motion event has been dispatched to.
23340         * @param event The MotionEvent object containing full information about
23341         *        the event.
23342         * @return True if the listener has consumed the event, false otherwise.
23343         */
23344        boolean onGenericMotion(View v, MotionEvent event);
23345    }
23346
23347    /**
23348     * Interface definition for a callback to be invoked when a view has been clicked and held.
23349     */
23350    public interface OnLongClickListener {
23351        /**
23352         * Called when a view has been clicked and held.
23353         *
23354         * @param v The view that was clicked and held.
23355         *
23356         * @return true if the callback consumed the long click, false otherwise.
23357         */
23358        boolean onLongClick(View v);
23359    }
23360
23361    /**
23362     * Interface definition for a callback to be invoked when a drag is being dispatched
23363     * to this view.  The callback will be invoked before the hosting view's own
23364     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
23365     * onDrag(event) behavior, it should return 'false' from this callback.
23366     *
23367     * <div class="special reference">
23368     * <h3>Developer Guides</h3>
23369     * <p>For a guide to implementing drag and drop features, read the
23370     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
23371     * </div>
23372     */
23373    public interface OnDragListener {
23374        /**
23375         * Called when a drag event is dispatched to a view. This allows listeners
23376         * to get a chance to override base View behavior.
23377         *
23378         * @param v The View that received the drag event.
23379         * @param event The {@link android.view.DragEvent} object for the drag event.
23380         * @return {@code true} if the drag event was handled successfully, or {@code false}
23381         * if the drag event was not handled. Note that {@code false} will trigger the View
23382         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
23383         */
23384        boolean onDrag(View v, DragEvent event);
23385    }
23386
23387    /**
23388     * Interface definition for a callback to be invoked when the focus state of
23389     * a view changed.
23390     */
23391    public interface OnFocusChangeListener {
23392        /**
23393         * Called when the focus state of a view has changed.
23394         *
23395         * @param v The view whose state has changed.
23396         * @param hasFocus The new focus state of v.
23397         */
23398        void onFocusChange(View v, boolean hasFocus);
23399    }
23400
23401    /**
23402     * Interface definition for a callback to be invoked when a view is clicked.
23403     */
23404    public interface OnClickListener {
23405        /**
23406         * Called when a view has been clicked.
23407         *
23408         * @param v The view that was clicked.
23409         */
23410        void onClick(View v);
23411    }
23412
23413    /**
23414     * Interface definition for a callback to be invoked when a view is context clicked.
23415     */
23416    public interface OnContextClickListener {
23417        /**
23418         * Called when a view is context clicked.
23419         *
23420         * @param v The view that has been context clicked.
23421         * @return true if the callback consumed the context click, false otherwise.
23422         */
23423        boolean onContextClick(View v);
23424    }
23425
23426    /**
23427     * Interface definition for a callback to be invoked when the context menu
23428     * for this view is being built.
23429     */
23430    public interface OnCreateContextMenuListener {
23431        /**
23432         * Called when the context menu for this view is being built. It is not
23433         * safe to hold onto the menu after this method returns.
23434         *
23435         * @param menu The context menu that is being built
23436         * @param v The view for which the context menu is being built
23437         * @param menuInfo Extra information about the item for which the
23438         *            context menu should be shown. This information will vary
23439         *            depending on the class of v.
23440         */
23441        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
23442    }
23443
23444    /**
23445     * Interface definition for a callback to be invoked when the status bar changes
23446     * visibility.  This reports <strong>global</strong> changes to the system UI
23447     * state, not what the application is requesting.
23448     *
23449     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
23450     */
23451    public interface OnSystemUiVisibilityChangeListener {
23452        /**
23453         * Called when the status bar changes visibility because of a call to
23454         * {@link View#setSystemUiVisibility(int)}.
23455         *
23456         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23457         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
23458         * This tells you the <strong>global</strong> state of these UI visibility
23459         * flags, not what your app is currently applying.
23460         */
23461        public void onSystemUiVisibilityChange(int visibility);
23462    }
23463
23464    /**
23465     * Interface definition for a callback to be invoked when this view is attached
23466     * or detached from its window.
23467     */
23468    public interface OnAttachStateChangeListener {
23469        /**
23470         * Called when the view is attached to a window.
23471         * @param v The view that was attached
23472         */
23473        public void onViewAttachedToWindow(View v);
23474        /**
23475         * Called when the view is detached from a window.
23476         * @param v The view that was detached
23477         */
23478        public void onViewDetachedFromWindow(View v);
23479    }
23480
23481    /**
23482     * Listener for applying window insets on a view in a custom way.
23483     *
23484     * <p>Apps may choose to implement this interface if they want to apply custom policy
23485     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
23486     * is set, its
23487     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
23488     * method will be called instead of the View's own
23489     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
23490     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
23491     * the View's normal behavior as part of its own.</p>
23492     */
23493    public interface OnApplyWindowInsetsListener {
23494        /**
23495         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
23496         * on a View, this listener method will be called instead of the view's own
23497         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
23498         *
23499         * @param v The view applying window insets
23500         * @param insets The insets to apply
23501         * @return The insets supplied, minus any insets that were consumed
23502         */
23503        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
23504    }
23505
23506    private final class UnsetPressedState implements Runnable {
23507        @Override
23508        public void run() {
23509            setPressed(false);
23510        }
23511    }
23512
23513    /**
23514     * Base class for derived classes that want to save and restore their own
23515     * state in {@link android.view.View#onSaveInstanceState()}.
23516     */
23517    public static class BaseSavedState extends AbsSavedState {
23518        String mStartActivityRequestWhoSaved;
23519
23520        /**
23521         * Constructor used when reading from a parcel. Reads the state of the superclass.
23522         *
23523         * @param source parcel to read from
23524         */
23525        public BaseSavedState(Parcel source) {
23526            this(source, null);
23527        }
23528
23529        /**
23530         * Constructor used when reading from a parcel using a given class loader.
23531         * Reads the state of the superclass.
23532         *
23533         * @param source parcel to read from
23534         * @param loader ClassLoader to use for reading
23535         */
23536        public BaseSavedState(Parcel source, ClassLoader loader) {
23537            super(source, loader);
23538            mStartActivityRequestWhoSaved = source.readString();
23539        }
23540
23541        /**
23542         * Constructor called by derived classes when creating their SavedState objects
23543         *
23544         * @param superState The state of the superclass of this view
23545         */
23546        public BaseSavedState(Parcelable superState) {
23547            super(superState);
23548        }
23549
23550        @Override
23551        public void writeToParcel(Parcel out, int flags) {
23552            super.writeToParcel(out, flags);
23553            out.writeString(mStartActivityRequestWhoSaved);
23554        }
23555
23556        public static final Parcelable.Creator<BaseSavedState> CREATOR
23557                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
23558            @Override
23559            public BaseSavedState createFromParcel(Parcel in) {
23560                return new BaseSavedState(in);
23561            }
23562
23563            @Override
23564            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
23565                return new BaseSavedState(in, loader);
23566            }
23567
23568            @Override
23569            public BaseSavedState[] newArray(int size) {
23570                return new BaseSavedState[size];
23571            }
23572        };
23573    }
23574
23575    /**
23576     * A set of information given to a view when it is attached to its parent
23577     * window.
23578     */
23579    final static class AttachInfo {
23580        interface Callbacks {
23581            void playSoundEffect(int effectId);
23582            boolean performHapticFeedback(int effectId, boolean always);
23583        }
23584
23585        /**
23586         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
23587         * to a Handler. This class contains the target (View) to invalidate and
23588         * the coordinates of the dirty rectangle.
23589         *
23590         * For performance purposes, this class also implements a pool of up to
23591         * POOL_LIMIT objects that get reused. This reduces memory allocations
23592         * whenever possible.
23593         */
23594        static class InvalidateInfo {
23595            private static final int POOL_LIMIT = 10;
23596
23597            private static final SynchronizedPool<InvalidateInfo> sPool =
23598                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
23599
23600            View target;
23601
23602            int left;
23603            int top;
23604            int right;
23605            int bottom;
23606
23607            public static InvalidateInfo obtain() {
23608                InvalidateInfo instance = sPool.acquire();
23609                return (instance != null) ? instance : new InvalidateInfo();
23610            }
23611
23612            public void recycle() {
23613                target = null;
23614                sPool.release(this);
23615            }
23616        }
23617
23618        final IWindowSession mSession;
23619
23620        final IWindow mWindow;
23621
23622        final IBinder mWindowToken;
23623
23624        final Display mDisplay;
23625
23626        final Callbacks mRootCallbacks;
23627
23628        IWindowId mIWindowId;
23629        WindowId mWindowId;
23630
23631        /**
23632         * The top view of the hierarchy.
23633         */
23634        View mRootView;
23635
23636        IBinder mPanelParentWindowToken;
23637
23638        boolean mHardwareAccelerated;
23639        boolean mHardwareAccelerationRequested;
23640        ThreadedRenderer mThreadedRenderer;
23641        List<RenderNode> mPendingAnimatingRenderNodes;
23642
23643        /**
23644         * The state of the display to which the window is attached, as reported
23645         * by {@link Display#getState()}.  Note that the display state constants
23646         * declared by {@link Display} do not exactly line up with the screen state
23647         * constants declared by {@link View} (there are more display states than
23648         * screen states).
23649         */
23650        int mDisplayState = Display.STATE_UNKNOWN;
23651
23652        /**
23653         * Scale factor used by the compatibility mode
23654         */
23655        float mApplicationScale;
23656
23657        /**
23658         * Indicates whether the application is in compatibility mode
23659         */
23660        boolean mScalingRequired;
23661
23662        /**
23663         * Left position of this view's window
23664         */
23665        int mWindowLeft;
23666
23667        /**
23668         * Top position of this view's window
23669         */
23670        int mWindowTop;
23671
23672        /**
23673         * Indicates whether views need to use 32-bit drawing caches
23674         */
23675        boolean mUse32BitDrawingCache;
23676
23677        /**
23678         * For windows that are full-screen but using insets to layout inside
23679         * of the screen areas, these are the current insets to appear inside
23680         * the overscan area of the display.
23681         */
23682        final Rect mOverscanInsets = new Rect();
23683
23684        /**
23685         * For windows that are full-screen but using insets to layout inside
23686         * of the screen decorations, these are the current insets for the
23687         * content of the window.
23688         */
23689        final Rect mContentInsets = new Rect();
23690
23691        /**
23692         * For windows that are full-screen but using insets to layout inside
23693         * of the screen decorations, these are the current insets for the
23694         * actual visible parts of the window.
23695         */
23696        final Rect mVisibleInsets = new Rect();
23697
23698        /**
23699         * For windows that are full-screen but using insets to layout inside
23700         * of the screen decorations, these are the current insets for the
23701         * stable system windows.
23702         */
23703        final Rect mStableInsets = new Rect();
23704
23705        /**
23706         * For windows that include areas that are not covered by real surface these are the outsets
23707         * for real surface.
23708         */
23709        final Rect mOutsets = new Rect();
23710
23711        /**
23712         * In multi-window we force show the navigation bar. Because we don't want that the surface
23713         * size changes in this mode, we instead have a flag whether the navigation bar size should
23714         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
23715         */
23716        boolean mAlwaysConsumeNavBar;
23717
23718        /**
23719         * The internal insets given by this window.  This value is
23720         * supplied by the client (through
23721         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
23722         * be given to the window manager when changed to be used in laying
23723         * out windows behind it.
23724         */
23725        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
23726                = new ViewTreeObserver.InternalInsetsInfo();
23727
23728        /**
23729         * Set to true when mGivenInternalInsets is non-empty.
23730         */
23731        boolean mHasNonEmptyGivenInternalInsets;
23732
23733        /**
23734         * All views in the window's hierarchy that serve as scroll containers,
23735         * used to determine if the window can be resized or must be panned
23736         * to adjust for a soft input area.
23737         */
23738        final ArrayList<View> mScrollContainers = new ArrayList<View>();
23739
23740        final KeyEvent.DispatcherState mKeyDispatchState
23741                = new KeyEvent.DispatcherState();
23742
23743        /**
23744         * Indicates whether the view's window currently has the focus.
23745         */
23746        boolean mHasWindowFocus;
23747
23748        /**
23749         * The current visibility of the window.
23750         */
23751        int mWindowVisibility;
23752
23753        /**
23754         * Indicates the time at which drawing started to occur.
23755         */
23756        long mDrawingTime;
23757
23758        /**
23759         * Indicates whether or not ignoring the DIRTY_MASK flags.
23760         */
23761        boolean mIgnoreDirtyState;
23762
23763        /**
23764         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
23765         * to avoid clearing that flag prematurely.
23766         */
23767        boolean mSetIgnoreDirtyState = false;
23768
23769        /**
23770         * Indicates whether the view's window is currently in touch mode.
23771         */
23772        boolean mInTouchMode;
23773
23774        /**
23775         * Indicates whether the view has requested unbuffered input dispatching for the current
23776         * event stream.
23777         */
23778        boolean mUnbufferedDispatchRequested;
23779
23780        /**
23781         * Indicates that ViewAncestor should trigger a global layout change
23782         * the next time it performs a traversal
23783         */
23784        boolean mRecomputeGlobalAttributes;
23785
23786        /**
23787         * Always report new attributes at next traversal.
23788         */
23789        boolean mForceReportNewAttributes;
23790
23791        /**
23792         * Set during a traveral if any views want to keep the screen on.
23793         */
23794        boolean mKeepScreenOn;
23795
23796        /**
23797         * Set during a traveral if the light center needs to be updated.
23798         */
23799        boolean mNeedsUpdateLightCenter;
23800
23801        /**
23802         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
23803         */
23804        int mSystemUiVisibility;
23805
23806        /**
23807         * Hack to force certain system UI visibility flags to be cleared.
23808         */
23809        int mDisabledSystemUiVisibility;
23810
23811        /**
23812         * Last global system UI visibility reported by the window manager.
23813         */
23814        int mGlobalSystemUiVisibility = -1;
23815
23816        /**
23817         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
23818         * attached.
23819         */
23820        boolean mHasSystemUiListeners;
23821
23822        /**
23823         * Set if the window has requested to extend into the overscan region
23824         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
23825         */
23826        boolean mOverscanRequested;
23827
23828        /**
23829         * Set if the visibility of any views has changed.
23830         */
23831        boolean mViewVisibilityChanged;
23832
23833        /**
23834         * Set to true if a view has been scrolled.
23835         */
23836        boolean mViewScrollChanged;
23837
23838        /**
23839         * Set to true if high contrast mode enabled
23840         */
23841        boolean mHighContrastText;
23842
23843        /**
23844         * Set to true if a pointer event is currently being handled.
23845         */
23846        boolean mHandlingPointerEvent;
23847
23848        /**
23849         * Global to the view hierarchy used as a temporary for dealing with
23850         * x/y points in the transparent region computations.
23851         */
23852        final int[] mTransparentLocation = new int[2];
23853
23854        /**
23855         * Global to the view hierarchy used as a temporary for dealing with
23856         * x/y points in the ViewGroup.invalidateChild implementation.
23857         */
23858        final int[] mInvalidateChildLocation = new int[2];
23859
23860        /**
23861         * Global to the view hierarchy used as a temporary for dealing with
23862         * computing absolute on-screen location.
23863         */
23864        final int[] mTmpLocation = new int[2];
23865
23866        /**
23867         * Global to the view hierarchy used as a temporary for dealing with
23868         * x/y location when view is transformed.
23869         */
23870        final float[] mTmpTransformLocation = new float[2];
23871
23872        /**
23873         * The view tree observer used to dispatch global events like
23874         * layout, pre-draw, touch mode change, etc.
23875         */
23876        final ViewTreeObserver mTreeObserver;
23877
23878        /**
23879         * A Canvas used by the view hierarchy to perform bitmap caching.
23880         */
23881        Canvas mCanvas;
23882
23883        /**
23884         * The view root impl.
23885         */
23886        final ViewRootImpl mViewRootImpl;
23887
23888        /**
23889         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
23890         * handler can be used to pump events in the UI events queue.
23891         */
23892        final Handler mHandler;
23893
23894        /**
23895         * Temporary for use in computing invalidate rectangles while
23896         * calling up the hierarchy.
23897         */
23898        final Rect mTmpInvalRect = new Rect();
23899
23900        /**
23901         * Temporary for use in computing hit areas with transformed views
23902         */
23903        final RectF mTmpTransformRect = new RectF();
23904
23905        /**
23906         * Temporary for use in computing hit areas with transformed views
23907         */
23908        final RectF mTmpTransformRect1 = new RectF();
23909
23910        /**
23911         * Temporary list of rectanges.
23912         */
23913        final List<RectF> mTmpRectList = new ArrayList<>();
23914
23915        /**
23916         * Temporary for use in transforming invalidation rect
23917         */
23918        final Matrix mTmpMatrix = new Matrix();
23919
23920        /**
23921         * Temporary for use in transforming invalidation rect
23922         */
23923        final Transformation mTmpTransformation = new Transformation();
23924
23925        /**
23926         * Temporary for use in querying outlines from OutlineProviders
23927         */
23928        final Outline mTmpOutline = new Outline();
23929
23930        /**
23931         * Temporary list for use in collecting focusable descendents of a view.
23932         */
23933        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
23934
23935        /**
23936         * The id of the window for accessibility purposes.
23937         */
23938        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
23939
23940        /**
23941         * Flags related to accessibility processing.
23942         *
23943         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
23944         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
23945         */
23946        int mAccessibilityFetchFlags;
23947
23948        /**
23949         * The drawable for highlighting accessibility focus.
23950         */
23951        Drawable mAccessibilityFocusDrawable;
23952
23953        /**
23954         * Show where the margins, bounds and layout bounds are for each view.
23955         */
23956        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23957
23958        /**
23959         * Point used to compute visible regions.
23960         */
23961        final Point mPoint = new Point();
23962
23963        /**
23964         * Used to track which View originated a requestLayout() call, used when
23965         * requestLayout() is called during layout.
23966         */
23967        View mViewRequestingLayout;
23968
23969        /**
23970         * Used to track views that need (at least) a partial relayout at their current size
23971         * during the next traversal.
23972         */
23973        List<View> mPartialLayoutViews = new ArrayList<>();
23974
23975        /**
23976         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23977         * modification. Lazily assigned during ViewRootImpl layout.
23978         */
23979        List<View> mEmptyPartialLayoutViews;
23980
23981        /**
23982         * Used to track the identity of the current drag operation.
23983         */
23984        IBinder mDragToken;
23985
23986        /**
23987         * The drag shadow surface for the current drag operation.
23988         */
23989        public Surface mDragSurface;
23990
23991
23992        /**
23993         * The view that currently has a tooltip displayed.
23994         */
23995        View mTooltipHost;
23996
23997        /**
23998         * Creates a new set of attachment information with the specified
23999         * events handler and thread.
24000         *
24001         * @param handler the events handler the view must use
24002         */
24003        AttachInfo(IWindowSession session, IWindow window, Display display,
24004                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
24005                Context context) {
24006            mSession = session;
24007            mWindow = window;
24008            mWindowToken = window.asBinder();
24009            mDisplay = display;
24010            mViewRootImpl = viewRootImpl;
24011            mHandler = handler;
24012            mRootCallbacks = effectPlayer;
24013            mTreeObserver = new ViewTreeObserver(context);
24014        }
24015    }
24016
24017    /**
24018     * <p>ScrollabilityCache holds various fields used by a View when scrolling
24019     * is supported. This avoids keeping too many unused fields in most
24020     * instances of View.</p>
24021     */
24022    private static class ScrollabilityCache implements Runnable {
24023
24024        /**
24025         * Scrollbars are not visible
24026         */
24027        public static final int OFF = 0;
24028
24029        /**
24030         * Scrollbars are visible
24031         */
24032        public static final int ON = 1;
24033
24034        /**
24035         * Scrollbars are fading away
24036         */
24037        public static final int FADING = 2;
24038
24039        public boolean fadeScrollBars;
24040
24041        public int fadingEdgeLength;
24042        public int scrollBarDefaultDelayBeforeFade;
24043        public int scrollBarFadeDuration;
24044
24045        public int scrollBarSize;
24046        public ScrollBarDrawable scrollBar;
24047        public float[] interpolatorValues;
24048        public View host;
24049
24050        public final Paint paint;
24051        public final Matrix matrix;
24052        public Shader shader;
24053
24054        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
24055
24056        private static final float[] OPAQUE = { 255 };
24057        private static final float[] TRANSPARENT = { 0.0f };
24058
24059        /**
24060         * When fading should start. This time moves into the future every time
24061         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
24062         */
24063        public long fadeStartTime;
24064
24065
24066        /**
24067         * The current state of the scrollbars: ON, OFF, or FADING
24068         */
24069        public int state = OFF;
24070
24071        private int mLastColor;
24072
24073        public final Rect mScrollBarBounds = new Rect();
24074
24075        public static final int NOT_DRAGGING = 0;
24076        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
24077        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
24078        public int mScrollBarDraggingState = NOT_DRAGGING;
24079
24080        public float mScrollBarDraggingPos = 0;
24081
24082        public ScrollabilityCache(ViewConfiguration configuration, View host) {
24083            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
24084            scrollBarSize = configuration.getScaledScrollBarSize();
24085            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
24086            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
24087
24088            paint = new Paint();
24089            matrix = new Matrix();
24090            // use use a height of 1, and then wack the matrix each time we
24091            // actually use it.
24092            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
24093            paint.setShader(shader);
24094            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
24095
24096            this.host = host;
24097        }
24098
24099        public void setFadeColor(int color) {
24100            if (color != mLastColor) {
24101                mLastColor = color;
24102
24103                if (color != 0) {
24104                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
24105                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
24106                    paint.setShader(shader);
24107                    // Restore the default transfer mode (src_over)
24108                    paint.setXfermode(null);
24109                } else {
24110                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
24111                    paint.setShader(shader);
24112                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
24113                }
24114            }
24115        }
24116
24117        public void run() {
24118            long now = AnimationUtils.currentAnimationTimeMillis();
24119            if (now >= fadeStartTime) {
24120
24121                // the animation fades the scrollbars out by changing
24122                // the opacity (alpha) from fully opaque to fully
24123                // transparent
24124                int nextFrame = (int) now;
24125                int framesCount = 0;
24126
24127                Interpolator interpolator = scrollBarInterpolator;
24128
24129                // Start opaque
24130                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
24131
24132                // End transparent
24133                nextFrame += scrollBarFadeDuration;
24134                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
24135
24136                state = FADING;
24137
24138                // Kick off the fade animation
24139                host.invalidate(true);
24140            }
24141        }
24142    }
24143
24144    /**
24145     * Resuable callback for sending
24146     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
24147     */
24148    private class SendViewScrolledAccessibilityEvent implements Runnable {
24149        public volatile boolean mIsPending;
24150
24151        public void run() {
24152            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
24153            mIsPending = false;
24154        }
24155    }
24156
24157    /**
24158     * <p>
24159     * This class represents a delegate that can be registered in a {@link View}
24160     * to enhance accessibility support via composition rather via inheritance.
24161     * It is specifically targeted to widget developers that extend basic View
24162     * classes i.e. classes in package android.view, that would like their
24163     * applications to be backwards compatible.
24164     * </p>
24165     * <div class="special reference">
24166     * <h3>Developer Guides</h3>
24167     * <p>For more information about making applications accessible, read the
24168     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
24169     * developer guide.</p>
24170     * </div>
24171     * <p>
24172     * A scenario in which a developer would like to use an accessibility delegate
24173     * is overriding a method introduced in a later API version than the minimal API
24174     * version supported by the application. For example, the method
24175     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
24176     * in API version 4 when the accessibility APIs were first introduced. If a
24177     * developer would like his application to run on API version 4 devices (assuming
24178     * all other APIs used by the application are version 4 or lower) and take advantage
24179     * of this method, instead of overriding the method which would break the application's
24180     * backwards compatibility, he can override the corresponding method in this
24181     * delegate and register the delegate in the target View if the API version of
24182     * the system is high enough, i.e. the API version is the same as or higher than the API
24183     * version that introduced
24184     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
24185     * </p>
24186     * <p>
24187     * Here is an example implementation:
24188     * </p>
24189     * <code><pre><p>
24190     * if (Build.VERSION.SDK_INT >= 14) {
24191     *     // If the API version is equal of higher than the version in
24192     *     // which onInitializeAccessibilityNodeInfo was introduced we
24193     *     // register a delegate with a customized implementation.
24194     *     View view = findViewById(R.id.view_id);
24195     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
24196     *         public void onInitializeAccessibilityNodeInfo(View host,
24197     *                 AccessibilityNodeInfo info) {
24198     *             // Let the default implementation populate the info.
24199     *             super.onInitializeAccessibilityNodeInfo(host, info);
24200     *             // Set some other information.
24201     *             info.setEnabled(host.isEnabled());
24202     *         }
24203     *     });
24204     * }
24205     * </code></pre></p>
24206     * <p>
24207     * This delegate contains methods that correspond to the accessibility methods
24208     * in View. If a delegate has been specified the implementation in View hands
24209     * off handling to the corresponding method in this delegate. The default
24210     * implementation the delegate methods behaves exactly as the corresponding
24211     * method in View for the case of no accessibility delegate been set. Hence,
24212     * to customize the behavior of a View method, clients can override only the
24213     * corresponding delegate method without altering the behavior of the rest
24214     * accessibility related methods of the host view.
24215     * </p>
24216     * <p>
24217     * <strong>Note:</strong> On platform versions prior to
24218     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
24219     * views in the {@code android.widget.*} package are called <i>before</i>
24220     * host methods. This prevents certain properties such as class name from
24221     * being modified by overriding
24222     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
24223     * as any changes will be overwritten by the host class.
24224     * <p>
24225     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
24226     * methods are called <i>after</i> host methods, which all properties to be
24227     * modified without being overwritten by the host class.
24228     */
24229    public static class AccessibilityDelegate {
24230
24231        /**
24232         * Sends an accessibility event of the given type. If accessibility is not
24233         * enabled this method has no effect.
24234         * <p>
24235         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
24236         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
24237         * been set.
24238         * </p>
24239         *
24240         * @param host The View hosting the delegate.
24241         * @param eventType The type of the event to send.
24242         *
24243         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
24244         */
24245        public void sendAccessibilityEvent(View host, int eventType) {
24246            host.sendAccessibilityEventInternal(eventType);
24247        }
24248
24249        /**
24250         * Performs the specified accessibility action on the view. For
24251         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
24252         * <p>
24253         * The default implementation behaves as
24254         * {@link View#performAccessibilityAction(int, Bundle)
24255         *  View#performAccessibilityAction(int, Bundle)} for the case of
24256         *  no accessibility delegate been set.
24257         * </p>
24258         *
24259         * @param action The action to perform.
24260         * @return Whether the action was performed.
24261         *
24262         * @see View#performAccessibilityAction(int, Bundle)
24263         *      View#performAccessibilityAction(int, Bundle)
24264         */
24265        public boolean performAccessibilityAction(View host, int action, Bundle args) {
24266            return host.performAccessibilityActionInternal(action, args);
24267        }
24268
24269        /**
24270         * Sends an accessibility event. This method behaves exactly as
24271         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
24272         * empty {@link AccessibilityEvent} and does not perform a check whether
24273         * accessibility is enabled.
24274         * <p>
24275         * The default implementation behaves as
24276         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24277         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
24278         * the case of no accessibility delegate been set.
24279         * </p>
24280         *
24281         * @param host The View hosting the delegate.
24282         * @param event The event to send.
24283         *
24284         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24285         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24286         */
24287        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
24288            host.sendAccessibilityEventUncheckedInternal(event);
24289        }
24290
24291        /**
24292         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
24293         * to its children for adding their text content to the event.
24294         * <p>
24295         * The default implementation behaves as
24296         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24297         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
24298         * the case of no accessibility delegate been set.
24299         * </p>
24300         *
24301         * @param host The View hosting the delegate.
24302         * @param event The event.
24303         * @return True if the event population was completed.
24304         *
24305         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24306         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24307         */
24308        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24309            return host.dispatchPopulateAccessibilityEventInternal(event);
24310        }
24311
24312        /**
24313         * Gives a chance to the host View to populate the accessibility event with its
24314         * text content.
24315         * <p>
24316         * The default implementation behaves as
24317         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
24318         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
24319         * the case of no accessibility delegate been set.
24320         * </p>
24321         *
24322         * @param host The View hosting the delegate.
24323         * @param event The accessibility event which to populate.
24324         *
24325         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
24326         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
24327         */
24328        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24329            host.onPopulateAccessibilityEventInternal(event);
24330        }
24331
24332        /**
24333         * Initializes an {@link AccessibilityEvent} with information about the
24334         * the host View which is the event source.
24335         * <p>
24336         * The default implementation behaves as
24337         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
24338         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
24339         * the case of no accessibility delegate been set.
24340         * </p>
24341         *
24342         * @param host The View hosting the delegate.
24343         * @param event The event to initialize.
24344         *
24345         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
24346         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
24347         */
24348        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
24349            host.onInitializeAccessibilityEventInternal(event);
24350        }
24351
24352        /**
24353         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
24354         * <p>
24355         * The default implementation behaves as
24356         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24357         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
24358         * the case of no accessibility delegate been set.
24359         * </p>
24360         *
24361         * @param host The View hosting the delegate.
24362         * @param info The instance to initialize.
24363         *
24364         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24365         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24366         */
24367        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
24368            host.onInitializeAccessibilityNodeInfoInternal(info);
24369        }
24370
24371        /**
24372         * Called when a child of the host View has requested sending an
24373         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
24374         * to augment the event.
24375         * <p>
24376         * The default implementation behaves as
24377         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24378         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
24379         * the case of no accessibility delegate been set.
24380         * </p>
24381         *
24382         * @param host The View hosting the delegate.
24383         * @param child The child which requests sending the event.
24384         * @param event The event to be sent.
24385         * @return True if the event should be sent
24386         *
24387         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24388         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24389         */
24390        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
24391                AccessibilityEvent event) {
24392            return host.onRequestSendAccessibilityEventInternal(child, event);
24393        }
24394
24395        /**
24396         * Gets the provider for managing a virtual view hierarchy rooted at this View
24397         * and reported to {@link android.accessibilityservice.AccessibilityService}s
24398         * that explore the window content.
24399         * <p>
24400         * The default implementation behaves as
24401         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
24402         * the case of no accessibility delegate been set.
24403         * </p>
24404         *
24405         * @return The provider.
24406         *
24407         * @see AccessibilityNodeProvider
24408         */
24409        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
24410            return null;
24411        }
24412
24413        /**
24414         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
24415         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
24416         * This method is responsible for obtaining an accessibility node info from a
24417         * pool of reusable instances and calling
24418         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
24419         * view to initialize the former.
24420         * <p>
24421         * <strong>Note:</strong> The client is responsible for recycling the obtained
24422         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
24423         * creation.
24424         * </p>
24425         * <p>
24426         * The default implementation behaves as
24427         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
24428         * the case of no accessibility delegate been set.
24429         * </p>
24430         * @return A populated {@link AccessibilityNodeInfo}.
24431         *
24432         * @see AccessibilityNodeInfo
24433         *
24434         * @hide
24435         */
24436        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
24437            return host.createAccessibilityNodeInfoInternal();
24438        }
24439    }
24440
24441    private class MatchIdPredicate implements Predicate<View> {
24442        public int mId;
24443
24444        @Override
24445        public boolean apply(View view) {
24446            return (view.mID == mId);
24447        }
24448    }
24449
24450    private class MatchLabelForPredicate implements Predicate<View> {
24451        private int mLabeledId;
24452
24453        @Override
24454        public boolean apply(View view) {
24455            return (view.mLabelForId == mLabeledId);
24456        }
24457    }
24458
24459    private class SendViewStateChangedAccessibilityEvent implements Runnable {
24460        private int mChangeTypes = 0;
24461        private boolean mPosted;
24462        private boolean mPostedWithDelay;
24463        private long mLastEventTimeMillis;
24464
24465        @Override
24466        public void run() {
24467            mPosted = false;
24468            mPostedWithDelay = false;
24469            mLastEventTimeMillis = SystemClock.uptimeMillis();
24470            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
24471                final AccessibilityEvent event = AccessibilityEvent.obtain();
24472                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
24473                event.setContentChangeTypes(mChangeTypes);
24474                sendAccessibilityEventUnchecked(event);
24475            }
24476            mChangeTypes = 0;
24477        }
24478
24479        public void runOrPost(int changeType) {
24480            mChangeTypes |= changeType;
24481
24482            // If this is a live region or the child of a live region, collect
24483            // all events from this frame and send them on the next frame.
24484            if (inLiveRegion()) {
24485                // If we're already posted with a delay, remove that.
24486                if (mPostedWithDelay) {
24487                    removeCallbacks(this);
24488                    mPostedWithDelay = false;
24489                }
24490                // Only post if we're not already posted.
24491                if (!mPosted) {
24492                    post(this);
24493                    mPosted = true;
24494                }
24495                return;
24496            }
24497
24498            if (mPosted) {
24499                return;
24500            }
24501
24502            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
24503            final long minEventIntevalMillis =
24504                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
24505            if (timeSinceLastMillis >= minEventIntevalMillis) {
24506                removeCallbacks(this);
24507                run();
24508            } else {
24509                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
24510                mPostedWithDelay = true;
24511            }
24512        }
24513    }
24514
24515    private boolean inLiveRegion() {
24516        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24517            return true;
24518        }
24519
24520        ViewParent parent = getParent();
24521        while (parent instanceof View) {
24522            if (((View) parent).getAccessibilityLiveRegion()
24523                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24524                return true;
24525            }
24526            parent = parent.getParent();
24527        }
24528
24529        return false;
24530    }
24531
24532    /**
24533     * Dump all private flags in readable format, useful for documentation and
24534     * sanity checking.
24535     */
24536    private static void dumpFlags() {
24537        final HashMap<String, String> found = Maps.newHashMap();
24538        try {
24539            for (Field field : View.class.getDeclaredFields()) {
24540                final int modifiers = field.getModifiers();
24541                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
24542                    if (field.getType().equals(int.class)) {
24543                        final int value = field.getInt(null);
24544                        dumpFlag(found, field.getName(), value);
24545                    } else if (field.getType().equals(int[].class)) {
24546                        final int[] values = (int[]) field.get(null);
24547                        for (int i = 0; i < values.length; i++) {
24548                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
24549                        }
24550                    }
24551                }
24552            }
24553        } catch (IllegalAccessException e) {
24554            throw new RuntimeException(e);
24555        }
24556
24557        final ArrayList<String> keys = Lists.newArrayList();
24558        keys.addAll(found.keySet());
24559        Collections.sort(keys);
24560        for (String key : keys) {
24561            Log.d(VIEW_LOG_TAG, found.get(key));
24562        }
24563    }
24564
24565    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
24566        // Sort flags by prefix, then by bits, always keeping unique keys
24567        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
24568        final int prefix = name.indexOf('_');
24569        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
24570        final String output = bits + " " + name;
24571        found.put(key, output);
24572    }
24573
24574    /** {@hide} */
24575    public void encode(@NonNull ViewHierarchyEncoder stream) {
24576        stream.beginObject(this);
24577        encodeProperties(stream);
24578        stream.endObject();
24579    }
24580
24581    /** {@hide} */
24582    @CallSuper
24583    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
24584        Object resolveId = ViewDebug.resolveId(getContext(), mID);
24585        if (resolveId instanceof String) {
24586            stream.addProperty("id", (String) resolveId);
24587        } else {
24588            stream.addProperty("id", mID);
24589        }
24590
24591        stream.addProperty("misc:transformation.alpha",
24592                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
24593        stream.addProperty("misc:transitionName", getTransitionName());
24594
24595        // layout
24596        stream.addProperty("layout:left", mLeft);
24597        stream.addProperty("layout:right", mRight);
24598        stream.addProperty("layout:top", mTop);
24599        stream.addProperty("layout:bottom", mBottom);
24600        stream.addProperty("layout:width", getWidth());
24601        stream.addProperty("layout:height", getHeight());
24602        stream.addProperty("layout:layoutDirection", getLayoutDirection());
24603        stream.addProperty("layout:layoutRtl", isLayoutRtl());
24604        stream.addProperty("layout:hasTransientState", hasTransientState());
24605        stream.addProperty("layout:baseline", getBaseline());
24606
24607        // layout params
24608        ViewGroup.LayoutParams layoutParams = getLayoutParams();
24609        if (layoutParams != null) {
24610            stream.addPropertyKey("layoutParams");
24611            layoutParams.encode(stream);
24612        }
24613
24614        // scrolling
24615        stream.addProperty("scrolling:scrollX", mScrollX);
24616        stream.addProperty("scrolling:scrollY", mScrollY);
24617
24618        // padding
24619        stream.addProperty("padding:paddingLeft", mPaddingLeft);
24620        stream.addProperty("padding:paddingRight", mPaddingRight);
24621        stream.addProperty("padding:paddingTop", mPaddingTop);
24622        stream.addProperty("padding:paddingBottom", mPaddingBottom);
24623        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
24624        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
24625        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
24626        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
24627        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
24628
24629        // measurement
24630        stream.addProperty("measurement:minHeight", mMinHeight);
24631        stream.addProperty("measurement:minWidth", mMinWidth);
24632        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
24633        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
24634
24635        // drawing
24636        stream.addProperty("drawing:elevation", getElevation());
24637        stream.addProperty("drawing:translationX", getTranslationX());
24638        stream.addProperty("drawing:translationY", getTranslationY());
24639        stream.addProperty("drawing:translationZ", getTranslationZ());
24640        stream.addProperty("drawing:rotation", getRotation());
24641        stream.addProperty("drawing:rotationX", getRotationX());
24642        stream.addProperty("drawing:rotationY", getRotationY());
24643        stream.addProperty("drawing:scaleX", getScaleX());
24644        stream.addProperty("drawing:scaleY", getScaleY());
24645        stream.addProperty("drawing:pivotX", getPivotX());
24646        stream.addProperty("drawing:pivotY", getPivotY());
24647        stream.addProperty("drawing:opaque", isOpaque());
24648        stream.addProperty("drawing:alpha", getAlpha());
24649        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
24650        stream.addProperty("drawing:shadow", hasShadow());
24651        stream.addProperty("drawing:solidColor", getSolidColor());
24652        stream.addProperty("drawing:layerType", mLayerType);
24653        stream.addProperty("drawing:willNotDraw", willNotDraw());
24654        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
24655        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
24656        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
24657        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
24658
24659        // focus
24660        stream.addProperty("focus:hasFocus", hasFocus());
24661        stream.addProperty("focus:isFocused", isFocused());
24662        stream.addProperty("focus:isFocusable", isFocusable());
24663        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
24664
24665        stream.addProperty("misc:clickable", isClickable());
24666        stream.addProperty("misc:pressed", isPressed());
24667        stream.addProperty("misc:selected", isSelected());
24668        stream.addProperty("misc:touchMode", isInTouchMode());
24669        stream.addProperty("misc:hovered", isHovered());
24670        stream.addProperty("misc:activated", isActivated());
24671
24672        stream.addProperty("misc:visibility", getVisibility());
24673        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
24674        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
24675
24676        stream.addProperty("misc:enabled", isEnabled());
24677        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
24678        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
24679
24680        // theme attributes
24681        Resources.Theme theme = getContext().getTheme();
24682        if (theme != null) {
24683            stream.addPropertyKey("theme");
24684            theme.encode(stream);
24685        }
24686
24687        // view attribute information
24688        int n = mAttributes != null ? mAttributes.length : 0;
24689        stream.addProperty("meta:__attrCount__", n/2);
24690        for (int i = 0; i < n; i += 2) {
24691            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
24692        }
24693
24694        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
24695
24696        // text
24697        stream.addProperty("text:textDirection", getTextDirection());
24698        stream.addProperty("text:textAlignment", getTextAlignment());
24699
24700        // accessibility
24701        CharSequence contentDescription = getContentDescription();
24702        stream.addProperty("accessibility:contentDescription",
24703                contentDescription == null ? "" : contentDescription.toString());
24704        stream.addProperty("accessibility:labelFor", getLabelFor());
24705        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
24706    }
24707
24708    /**
24709     * Determine if this view is rendered on a round wearable device and is the main view
24710     * on the screen.
24711     */
24712    private boolean shouldDrawRoundScrollbar() {
24713        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
24714            return false;
24715        }
24716
24717        final View rootView = getRootView();
24718        final WindowInsets insets = getRootWindowInsets();
24719
24720        int height = getHeight();
24721        int width = getWidth();
24722        int displayHeight = rootView.getHeight();
24723        int displayWidth = rootView.getWidth();
24724
24725        if (height != displayHeight || width != displayWidth) {
24726            return false;
24727        }
24728
24729        getLocationOnScreen(mAttachInfo.mTmpLocation);
24730        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
24731                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
24732    }
24733
24734    /**
24735     * Sets the tooltip text which will be displayed in a small popup next to the view.
24736     * <p>
24737     * The tooltip will be displayed:
24738     * <li>On long click, unless is not handled otherwise (by OnLongClickListener or a context
24739     * menu). </li>
24740     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
24741     *
24742     * @param tooltipText the tooltip text, or null if no tooltip is required
24743     */
24744    public final void setTooltipText(@Nullable CharSequence tooltipText) {
24745        if (TextUtils.isEmpty(tooltipText)) {
24746            setFlags(0, TOOLTIP);
24747            hideTooltip();
24748            mTooltipInfo = null;
24749        } else {
24750            setFlags(TOOLTIP, TOOLTIP);
24751            if (mTooltipInfo == null) {
24752                mTooltipInfo = new TooltipInfo();
24753                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
24754                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
24755            }
24756            mTooltipInfo.mTooltipText = tooltipText;
24757            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
24758                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText);
24759            }
24760        }
24761    }
24762
24763    /**
24764     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
24765     */
24766    public void setTooltip(@Nullable CharSequence tooltipText) {
24767        setTooltipText(tooltipText);
24768    }
24769
24770    /**
24771     * Returns the view's tooltip text.
24772     *
24773     * @return the tooltip text
24774     */
24775    @Nullable
24776    public final CharSequence getTooltipText() {
24777        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
24778    }
24779
24780    /**
24781     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
24782     */
24783    @Nullable
24784    public CharSequence getTooltip() {
24785        return getTooltipText();
24786    }
24787
24788    private boolean showTooltip(int x, int y, boolean fromLongClick) {
24789        if (mAttachInfo == null) {
24790            return false;
24791        }
24792        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
24793            return false;
24794        }
24795        final CharSequence tooltipText = getTooltipText();
24796        if (TextUtils.isEmpty(tooltipText)) {
24797            return false;
24798        }
24799        hideTooltip();
24800        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
24801        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
24802        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
24803        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, tooltipText);
24804        mAttachInfo.mTooltipHost = this;
24805        return true;
24806    }
24807
24808    void hideTooltip() {
24809        if (mTooltipInfo == null) {
24810            return;
24811        }
24812        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24813        if (mTooltipInfo.mTooltipPopup == null) {
24814            return;
24815        }
24816        mTooltipInfo.mTooltipPopup.hide();
24817        mTooltipInfo.mTooltipPopup = null;
24818        mTooltipInfo.mTooltipFromLongClick = false;
24819        if (mAttachInfo != null) {
24820            mAttachInfo.mTooltipHost = null;
24821        }
24822    }
24823
24824    private boolean showLongClickTooltip(int x, int y) {
24825        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24826        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24827        return showTooltip(x, y, true);
24828    }
24829
24830    private void showHoverTooltip() {
24831        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
24832    }
24833
24834    boolean dispatchTooltipHoverEvent(MotionEvent event) {
24835        if (mTooltipInfo == null) {
24836            return false;
24837        }
24838        switch(event.getAction()) {
24839            case MotionEvent.ACTION_HOVER_MOVE:
24840                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
24841                    break;
24842                }
24843                if (!mTooltipInfo.mTooltipFromLongClick) {
24844                    if (mTooltipInfo.mTooltipPopup == null) {
24845                        // Schedule showing the tooltip after a timeout.
24846                        mTooltipInfo.mAnchorX = (int) event.getX();
24847                        mTooltipInfo.mAnchorY = (int) event.getY();
24848                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24849                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
24850                                ViewConfiguration.getHoverTooltipShowTimeout());
24851                    }
24852
24853                    // Hide hover-triggered tooltip after a period of inactivity.
24854                    // Match the timeout used by NativeInputManager to hide the mouse pointer
24855                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
24856                    final int timeout;
24857                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
24858                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
24859                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
24860                    } else {
24861                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
24862                    }
24863                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24864                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
24865                }
24866                return true;
24867
24868            case MotionEvent.ACTION_HOVER_EXIT:
24869                if (!mTooltipInfo.mTooltipFromLongClick) {
24870                    hideTooltip();
24871                }
24872                break;
24873        }
24874        return false;
24875    }
24876
24877    void handleTooltipKey(KeyEvent event) {
24878        switch (event.getAction()) {
24879            case KeyEvent.ACTION_DOWN:
24880                if (event.getRepeatCount() == 0) {
24881                    hideTooltip();
24882                }
24883                break;
24884
24885            case KeyEvent.ACTION_UP:
24886                handleTooltipUp();
24887                break;
24888        }
24889    }
24890
24891    private void handleTooltipUp() {
24892        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24893            return;
24894        }
24895        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24896        postDelayed(mTooltipInfo.mHideTooltipRunnable,
24897                ViewConfiguration.getLongPressTooltipHideTimeout());
24898    }
24899
24900    private int getFocusableAttribute(TypedArray attributes) {
24901        TypedValue val = new TypedValue();
24902        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
24903            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
24904                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
24905            } else {
24906                return val.data;
24907            }
24908        } else {
24909            return FOCUSABLE_AUTO;
24910        }
24911    }
24912
24913    /**
24914     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
24915     * is not showing.
24916     * @hide
24917     */
24918    @TestApi
24919    public View getTooltipView() {
24920        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24921            return null;
24922        }
24923        return mTooltipInfo.mTooltipPopup.getContentView();
24924    }
24925}
24926