View.java revision 2de950d5a8b47c7b4648ada1b1260ce4b7342798
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.AutoFillType;
108import android.view.autofill.AutoFillValue;
109import android.view.autofill.VirtualViewDelegate;
110import android.view.inputmethod.EditorInfo;
111import android.view.inputmethod.InputConnection;
112import android.view.inputmethod.InputMethodManager;
113import android.widget.Checkable;
114import android.widget.FrameLayout;
115import android.widget.ScrollBarDrawable;
116
117import com.android.internal.R;
118import com.android.internal.util.Predicate;
119import com.android.internal.view.TooltipPopup;
120import com.android.internal.view.menu.MenuBuilder;
121import com.android.internal.widget.ScrollBarUtils;
122
123import com.google.android.collect.Lists;
124import com.google.android.collect.Maps;
125
126import java.lang.annotation.Retention;
127import java.lang.annotation.RetentionPolicy;
128import java.lang.ref.WeakReference;
129import java.lang.reflect.Field;
130import java.lang.reflect.InvocationTargetException;
131import java.lang.reflect.Method;
132import java.lang.reflect.Modifier;
133import java.util.ArrayList;
134import java.util.Arrays;
135import java.util.Collection;
136import java.util.Collections;
137import java.util.HashMap;
138import java.util.List;
139import java.util.Locale;
140import java.util.Map;
141import java.util.concurrent.CopyOnWriteArrayList;
142import java.util.concurrent.atomic.AtomicInteger;
143
144/**
145 * <p>
146 * This class represents the basic building block for user interface components. A View
147 * occupies a rectangular area on the screen and is responsible for drawing and
148 * event handling. View is the base class for <em>widgets</em>, which are
149 * used to create interactive UI components (buttons, text fields, etc.). The
150 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
151 * are invisible containers that hold other Views (or other ViewGroups) and define
152 * their layout properties.
153 * </p>
154 *
155 * <div class="special reference">
156 * <h3>Developer Guides</h3>
157 * <p>For information about using this class to develop your application's user interface,
158 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
159 * </div>
160 *
161 * <a name="Using"></a>
162 * <h3>Using Views</h3>
163 * <p>
164 * All of the views in a window are arranged in a single tree. You can add views
165 * either from code or by specifying a tree of views in one or more XML layout
166 * files. There are many specialized subclasses of views that act as controls or
167 * are capable of displaying text, images, or other content.
168 * </p>
169 * <p>
170 * Once you have created a tree of views, there are typically a few types of
171 * common operations you may wish to perform:
172 * <ul>
173 * <li><strong>Set properties:</strong> for example setting the text of a
174 * {@link android.widget.TextView}. The available properties and the methods
175 * that set them will vary among the different subclasses of views. Note that
176 * properties that are known at build time can be set in the XML layout
177 * files.</li>
178 * <li><strong>Set focus:</strong> The framework will handle moving focus in
179 * response to user input. To force focus to a specific view, call
180 * {@link #requestFocus}.</li>
181 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
182 * that will be notified when something interesting happens to the view. For
183 * example, all views will let you set a listener to be notified when the view
184 * gains or loses focus. You can register such a listener using
185 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
186 * Other view subclasses offer more specialized listeners. For example, a Button
187 * exposes a listener to notify clients when the button is clicked.</li>
188 * <li><strong>Set visibility:</strong> You can hide or show views using
189 * {@link #setVisibility(int)}.</li>
190 * </ul>
191 * </p>
192 * <p><em>
193 * Note: The Android framework is responsible for measuring, laying out and
194 * drawing views. You should not call methods that perform these actions on
195 * views yourself unless you are actually implementing a
196 * {@link android.view.ViewGroup}.
197 * </em></p>
198 *
199 * <a name="Lifecycle"></a>
200 * <h3>Implementing a Custom View</h3>
201 *
202 * <p>
203 * To implement a custom view, you will usually begin by providing overrides for
204 * some of the standard methods that the framework calls on all views. You do
205 * not need to override all of these methods. In fact, you can start by just
206 * overriding {@link #onDraw(android.graphics.Canvas)}.
207 * <table border="2" width="85%" align="center" cellpadding="5">
208 *     <thead>
209 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
210 *     </thead>
211 *
212 *     <tbody>
213 *     <tr>
214 *         <td rowspan="2">Creation</td>
215 *         <td>Constructors</td>
216 *         <td>There is a form of the constructor that are called when the view
217 *         is created from code and a form that is called when the view is
218 *         inflated from a layout file. The second form should parse and apply
219 *         any attributes defined in the layout file.
220 *         </td>
221 *     </tr>
222 *     <tr>
223 *         <td><code>{@link #onFinishInflate()}</code></td>
224 *         <td>Called after a view and all of its children has been inflated
225 *         from XML.</td>
226 *     </tr>
227 *
228 *     <tr>
229 *         <td rowspan="3">Layout</td>
230 *         <td><code>{@link #onMeasure(int, int)}</code></td>
231 *         <td>Called to determine the size requirements for this view and all
232 *         of its children.
233 *         </td>
234 *     </tr>
235 *     <tr>
236 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
237 *         <td>Called when this view should assign a size and position to all
238 *         of its children.
239 *         </td>
240 *     </tr>
241 *     <tr>
242 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
243 *         <td>Called when the size of this view has changed.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td>Drawing</td>
249 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
250 *         <td>Called when the view should render its content.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td rowspan="4">Event processing</td>
256 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
257 *         <td>Called when a new hardware key event occurs.
258 *         </td>
259 *     </tr>
260 *     <tr>
261 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
262 *         <td>Called when a hardware key up event occurs.
263 *         </td>
264 *     </tr>
265 *     <tr>
266 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
267 *         <td>Called when a trackball motion event occurs.
268 *         </td>
269 *     </tr>
270 *     <tr>
271 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
272 *         <td>Called when a touch screen motion event occurs.
273 *         </td>
274 *     </tr>
275 *
276 *     <tr>
277 *         <td rowspan="2">Focus</td>
278 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
279 *         <td>Called when the view gains or loses focus.
280 *         </td>
281 *     </tr>
282 *
283 *     <tr>
284 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
285 *         <td>Called when the window containing the view gains or loses focus.
286 *         </td>
287 *     </tr>
288 *
289 *     <tr>
290 *         <td rowspan="3">Attaching</td>
291 *         <td><code>{@link #onAttachedToWindow()}</code></td>
292 *         <td>Called when the view is attached to a window.
293 *         </td>
294 *     </tr>
295 *
296 *     <tr>
297 *         <td><code>{@link #onDetachedFromWindow}</code></td>
298 *         <td>Called when the view is detached from its window.
299 *         </td>
300 *     </tr>
301 *
302 *     <tr>
303 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
304 *         <td>Called when the visibility of the window containing the view
305 *         has changed.
306 *         </td>
307 *     </tr>
308 *     </tbody>
309 *
310 * </table>
311 * </p>
312 *
313 * <a name="IDs"></a>
314 * <h3>IDs</h3>
315 * Views may have an integer id associated with them. These ids are typically
316 * assigned in the layout XML files, and are used to find specific views within
317 * the view tree. A common pattern is to:
318 * <ul>
319 * <li>Define a Button in the layout file and assign it a unique ID.
320 * <pre>
321 * &lt;Button
322 *     android:id="@+id/my_button"
323 *     android:layout_width="wrap_content"
324 *     android:layout_height="wrap_content"
325 *     android:text="@string/my_button_text"/&gt;
326 * </pre></li>
327 * <li>From the onCreate method of an Activity, find the Button
328 * <pre class="prettyprint">
329 *      Button myButton = (Button) findViewById(R.id.my_button);
330 * </pre></li>
331 * </ul>
332 * <p>
333 * View IDs need not be unique throughout the tree, but it is good practice to
334 * ensure that they are at least unique within the part of the tree you are
335 * searching.
336 * </p>
337 *
338 * <a name="Position"></a>
339 * <h3>Position</h3>
340 * <p>
341 * The geometry of a view is that of a rectangle. A view has a location,
342 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
343 * two dimensions, expressed as a width and a height. The unit for location
344 * and dimensions is the pixel.
345 * </p>
346 *
347 * <p>
348 * It is possible to retrieve the location of a view by invoking the methods
349 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
350 * coordinate of the rectangle representing the view. The latter returns the
351 * top, or Y, coordinate of the rectangle representing the view. These methods
352 * both return the location of the view relative to its parent. For instance,
353 * when getLeft() returns 20, that means the view is located 20 pixels to the
354 * right of the left edge of its direct parent.
355 * </p>
356 *
357 * <p>
358 * In addition, several convenience methods are offered to avoid unnecessary
359 * computations, namely {@link #getRight()} and {@link #getBottom()}.
360 * These methods return the coordinates of the right and bottom edges of the
361 * rectangle representing the view. For instance, calling {@link #getRight()}
362 * is similar to the following computation: <code>getLeft() + getWidth()</code>
363 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
364 * </p>
365 *
366 * <a name="SizePaddingMargins"></a>
367 * <h3>Size, padding and margins</h3>
368 * <p>
369 * The size of a view is expressed with a width and a height. A view actually
370 * possess two pairs of width and height values.
371 * </p>
372 *
373 * <p>
374 * The first pair is known as <em>measured width</em> and
375 * <em>measured height</em>. These dimensions define how big a view wants to be
376 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
377 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
378 * and {@link #getMeasuredHeight()}.
379 * </p>
380 *
381 * <p>
382 * The second pair is simply known as <em>width</em> and <em>height</em>, or
383 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
384 * dimensions define the actual size of the view on screen, at drawing time and
385 * after layout. These values may, but do not have to, be different from the
386 * measured width and height. The width and height can be obtained by calling
387 * {@link #getWidth()} and {@link #getHeight()}.
388 * </p>
389 *
390 * <p>
391 * To measure its dimensions, a view takes into account its padding. The padding
392 * is expressed in pixels for the left, top, right and bottom parts of the view.
393 * Padding can be used to offset the content of the view by a specific amount of
394 * pixels. For instance, a left padding of 2 will push the view's content by
395 * 2 pixels to the right of the left edge. Padding can be set using the
396 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
397 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
398 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
399 * {@link #getPaddingEnd()}.
400 * </p>
401 *
402 * <p>
403 * Even though a view can define a padding, it does not provide any support for
404 * margins. However, view groups provide such a support. Refer to
405 * {@link android.view.ViewGroup} and
406 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
407 * </p>
408 *
409 * <a name="Layout"></a>
410 * <h3>Layout</h3>
411 * <p>
412 * Layout is a two pass process: a measure pass and a layout pass. The measuring
413 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
414 * of the view tree. Each view pushes dimension specifications down the tree
415 * during the recursion. At the end of the measure pass, every view has stored
416 * its measurements. The second pass happens in
417 * {@link #layout(int,int,int,int)} and is also top-down. During
418 * this pass each parent is responsible for positioning all of its children
419 * using the sizes computed in the measure pass.
420 * </p>
421 *
422 * <p>
423 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
424 * {@link #getMeasuredHeight()} values must be set, along with those for all of
425 * that view's descendants. A view's measured width and measured height values
426 * must respect the constraints imposed by the view's parents. This guarantees
427 * that at the end of the measure pass, all parents accept all of their
428 * children's measurements. A parent view may call measure() more than once on
429 * its children. For example, the parent may measure each child once with
430 * unspecified dimensions to find out how big they want to be, then call
431 * measure() on them again with actual numbers if the sum of all the children's
432 * unconstrained sizes is too big or too small.
433 * </p>
434 *
435 * <p>
436 * The measure pass uses two classes to communicate dimensions. The
437 * {@link MeasureSpec} class is used by views to tell their parents how they
438 * want to be measured and positioned. The base LayoutParams class just
439 * describes how big the view wants to be for both width and height. For each
440 * dimension, it can specify one of:
441 * <ul>
442 * <li> an exact number
443 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
444 * (minus padding)
445 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
446 * enclose its content (plus padding).
447 * </ul>
448 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
449 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
450 * an X and Y value.
451 * </p>
452 *
453 * <p>
454 * MeasureSpecs are used to push requirements down the tree from parent to
455 * child. A MeasureSpec can be in one of three modes:
456 * <ul>
457 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
458 * of a child view. For example, a LinearLayout may call measure() on its child
459 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
460 * tall the child view wants to be given a width of 240 pixels.
461 * <li>EXACTLY: This is used by the parent to impose an exact size on the
462 * child. The child must use this size, and guarantee that all of its
463 * descendants will fit within this size.
464 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
465 * child. The child must guarantee that it and all of its descendants will fit
466 * within this size.
467 * </ul>
468 * </p>
469 *
470 * <p>
471 * To initiate a layout, call {@link #requestLayout}. This method is typically
472 * called by a view on itself when it believes that is can no longer fit within
473 * its current bounds.
474 * </p>
475 *
476 * <a name="Drawing"></a>
477 * <h3>Drawing</h3>
478 * <p>
479 * Drawing is handled by walking the tree and recording the drawing commands of
480 * any View that needs to update. After this, the drawing commands of the
481 * entire tree are issued to screen, clipped to the newly damaged area.
482 * </p>
483 *
484 * <p>
485 * The tree is largely recorded and drawn in order, with parents drawn before
486 * (i.e., behind) their children, with siblings drawn in the order they appear
487 * in the tree. If you set a background drawable for a View, then the View will
488 * draw it before calling back to its <code>onDraw()</code> method. The child
489 * drawing order can be overridden with
490 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
491 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
492 * </p>
493 *
494 * <p>
495 * To force a view to draw, call {@link #invalidate()}.
496 * </p>
497 *
498 * <a name="EventHandlingThreading"></a>
499 * <h3>Event Handling and Threading</h3>
500 * <p>
501 * The basic cycle of a view is as follows:
502 * <ol>
503 * <li>An event comes in and is dispatched to the appropriate view. The view
504 * handles the event and notifies any listeners.</li>
505 * <li>If in the course of processing the event, the view's bounds may need
506 * to be changed, the view will call {@link #requestLayout()}.</li>
507 * <li>Similarly, if in the course of processing the event the view's appearance
508 * may need to be changed, the view will call {@link #invalidate()}.</li>
509 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
510 * the framework will take care of measuring, laying out, and drawing the tree
511 * as appropriate.</li>
512 * </ol>
513 * </p>
514 *
515 * <p><em>Note: The entire view tree is single threaded. You must always be on
516 * the UI thread when calling any method on any view.</em>
517 * If you are doing work on other threads and want to update the state of a view
518 * from that thread, you should use a {@link Handler}.
519 * </p>
520 *
521 * <a name="FocusHandling"></a>
522 * <h3>Focus Handling</h3>
523 * <p>
524 * The framework will handle routine focus movement in response to user input.
525 * This includes changing the focus as views are removed or hidden, or as new
526 * views become available. Views indicate their willingness to take focus
527 * through the {@link #isFocusable} method. To change whether a view can take
528 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
529 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
530 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
531 * </p>
532 * <p>
533 * Focus movement is based on an algorithm which finds the nearest neighbor in a
534 * given direction. In rare cases, the default algorithm may not match the
535 * intended behavior of the developer. In these situations, you can provide
536 * explicit overrides by using these XML attributes in the layout file:
537 * <pre>
538 * nextFocusDown
539 * nextFocusLeft
540 * nextFocusRight
541 * nextFocusUp
542 * </pre>
543 * </p>
544 *
545 *
546 * <p>
547 * To get a particular view to take focus, call {@link #requestFocus()}.
548 * </p>
549 *
550 * <a name="TouchMode"></a>
551 * <h3>Touch Mode</h3>
552 * <p>
553 * When a user is navigating a user interface via directional keys such as a D-pad, it is
554 * necessary to give focus to actionable items such as buttons so the user can see
555 * what will take input.  If the device has touch capabilities, however, and the user
556 * begins interacting with the interface by touching it, it is no longer necessary to
557 * always highlight, or give focus to, a particular view.  This motivates a mode
558 * for interaction named 'touch mode'.
559 * </p>
560 * <p>
561 * For a touch capable device, once the user touches the screen, the device
562 * will enter touch mode.  From this point onward, only views for which
563 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
564 * Other views that are touchable, like buttons, will not take focus when touched; they will
565 * only fire the on click listeners.
566 * </p>
567 * <p>
568 * Any time a user hits a directional key, such as a D-pad direction, the view device will
569 * exit touch mode, and find a view to take focus, so that the user may resume interacting
570 * with the user interface without touching the screen again.
571 * </p>
572 * <p>
573 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
574 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
575 * </p>
576 *
577 * <a name="Scrolling"></a>
578 * <h3>Scrolling</h3>
579 * <p>
580 * The framework provides basic support for views that wish to internally
581 * scroll their content. This includes keeping track of the X and Y scroll
582 * offset as well as mechanisms for drawing scrollbars. See
583 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
584 * {@link #awakenScrollBars()} for more details.
585 * </p>
586 *
587 * <a name="Tags"></a>
588 * <h3>Tags</h3>
589 * <p>
590 * Unlike IDs, tags are not used to identify views. Tags are essentially an
591 * extra piece of information that can be associated with a view. They are most
592 * often used as a convenience to store data related to views in the views
593 * themselves rather than by putting them in a separate structure.
594 * </p>
595 * <p>
596 * Tags may be specified with character sequence values in layout XML as either
597 * a single tag using the {@link android.R.styleable#View_tag android:tag}
598 * attribute or multiple tags using the {@code <tag>} child element:
599 * <pre>
600 *     &ltView ...
601 *           android:tag="@string/mytag_value" /&gt;
602 *     &ltView ...&gt;
603 *         &lttag android:id="@+id/mytag"
604 *              android:value="@string/mytag_value" /&gt;
605 *     &lt/View>
606 * </pre>
607 * </p>
608 * <p>
609 * Tags may also be specified with arbitrary objects from code using
610 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
611 * </p>
612 *
613 * <a name="Themes"></a>
614 * <h3>Themes</h3>
615 * <p>
616 * By default, Views are created using the theme of the Context object supplied
617 * to their constructor; however, a different theme may be specified by using
618 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
619 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
620 * code.
621 * </p>
622 * <p>
623 * When the {@link android.R.styleable#View_theme android:theme} attribute is
624 * used in XML, the specified theme is applied on top of the inflation
625 * context's theme (see {@link LayoutInflater}) and used for the view itself as
626 * well as any child elements.
627 * </p>
628 * <p>
629 * In the following example, both views will be created using the Material dark
630 * color scheme; however, because an overlay theme is used which only defines a
631 * subset of attributes, the value of
632 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
633 * the inflation context's theme (e.g. the Activity theme) will be preserved.
634 * <pre>
635 *     &ltLinearLayout
636 *             ...
637 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
638 *         &ltView ...&gt;
639 *     &lt/LinearLayout&gt;
640 * </pre>
641 * </p>
642 *
643 * <a name="Properties"></a>
644 * <h3>Properties</h3>
645 * <p>
646 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
647 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
648 * available both in the {@link Property} form as well as in similarly-named setter/getter
649 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
650 * be used to set persistent state associated with these rendering-related properties on the view.
651 * The properties and methods can also be used in conjunction with
652 * {@link android.animation.Animator Animator}-based animations, described more in the
653 * <a href="#Animation">Animation</a> section.
654 * </p>
655 *
656 * <a name="Animation"></a>
657 * <h3>Animation</h3>
658 * <p>
659 * Starting with Android 3.0, the preferred way of animating views is to use the
660 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
661 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
662 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
663 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
664 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
665 * makes animating these View properties particularly easy and efficient.
666 * </p>
667 * <p>
668 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
669 * You can attach an {@link Animation} object to a view using
670 * {@link #setAnimation(Animation)} or
671 * {@link #startAnimation(Animation)}. The animation can alter the scale,
672 * rotation, translation and alpha of a view over time. If the animation is
673 * attached to a view that has children, the animation will affect the entire
674 * subtree rooted by that node. When an animation is started, the framework will
675 * take care of redrawing the appropriate views until the animation completes.
676 * </p>
677 *
678 * <a name="Security"></a>
679 * <h3>Security</h3>
680 * <p>
681 * Sometimes it is essential that an application be able to verify that an action
682 * is being performed with the full knowledge and consent of the user, such as
683 * granting a permission request, making a purchase or clicking on an advertisement.
684 * Unfortunately, a malicious application could try to spoof the user into
685 * performing these actions, unaware, by concealing the intended purpose of the view.
686 * As a remedy, the framework offers a touch filtering mechanism that can be used to
687 * improve the security of views that provide access to sensitive functionality.
688 * </p><p>
689 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
690 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
691 * will discard touches that are received whenever the view's window is obscured by
692 * another visible window.  As a result, the view will not receive touches whenever a
693 * toast, dialog or other window appears above the view's window.
694 * </p><p>
695 * For more fine-grained control over security, consider overriding the
696 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
697 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
698 * </p>
699 *
700 * @attr ref android.R.styleable#View_alpha
701 * @attr ref android.R.styleable#View_background
702 * @attr ref android.R.styleable#View_clickable
703 * @attr ref android.R.styleable#View_contentDescription
704 * @attr ref android.R.styleable#View_drawingCacheQuality
705 * @attr ref android.R.styleable#View_duplicateParentState
706 * @attr ref android.R.styleable#View_id
707 * @attr ref android.R.styleable#View_requiresFadingEdge
708 * @attr ref android.R.styleable#View_fadeScrollbars
709 * @attr ref android.R.styleable#View_fadingEdgeLength
710 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
711 * @attr ref android.R.styleable#View_fitsSystemWindows
712 * @attr ref android.R.styleable#View_isScrollContainer
713 * @attr ref android.R.styleable#View_focusable
714 * @attr ref android.R.styleable#View_focusableInTouchMode
715 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
716 * @attr ref android.R.styleable#View_keepScreenOn
717 * @attr ref android.R.styleable#View_layerType
718 * @attr ref android.R.styleable#View_layoutDirection
719 * @attr ref android.R.styleable#View_longClickable
720 * @attr ref android.R.styleable#View_minHeight
721 * @attr ref android.R.styleable#View_minWidth
722 * @attr ref android.R.styleable#View_nextFocusDown
723 * @attr ref android.R.styleable#View_nextFocusLeft
724 * @attr ref android.R.styleable#View_nextFocusRight
725 * @attr ref android.R.styleable#View_nextFocusUp
726 * @attr ref android.R.styleable#View_onClick
727 * @attr ref android.R.styleable#View_padding
728 * @attr ref android.R.styleable#View_paddingBottom
729 * @attr ref android.R.styleable#View_paddingLeft
730 * @attr ref android.R.styleable#View_paddingRight
731 * @attr ref android.R.styleable#View_paddingTop
732 * @attr ref android.R.styleable#View_paddingStart
733 * @attr ref android.R.styleable#View_paddingEnd
734 * @attr ref android.R.styleable#View_saveEnabled
735 * @attr ref android.R.styleable#View_rotation
736 * @attr ref android.R.styleable#View_rotationX
737 * @attr ref android.R.styleable#View_rotationY
738 * @attr ref android.R.styleable#View_scaleX
739 * @attr ref android.R.styleable#View_scaleY
740 * @attr ref android.R.styleable#View_scrollX
741 * @attr ref android.R.styleable#View_scrollY
742 * @attr ref android.R.styleable#View_scrollbarSize
743 * @attr ref android.R.styleable#View_scrollbarStyle
744 * @attr ref android.R.styleable#View_scrollbars
745 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
746 * @attr ref android.R.styleable#View_scrollbarFadeDuration
747 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
748 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
749 * @attr ref android.R.styleable#View_scrollbarThumbVertical
750 * @attr ref android.R.styleable#View_scrollbarTrackVertical
751 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
752 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
753 * @attr ref android.R.styleable#View_stateListAnimator
754 * @attr ref android.R.styleable#View_transitionName
755 * @attr ref android.R.styleable#View_soundEffectsEnabled
756 * @attr ref android.R.styleable#View_tag
757 * @attr ref android.R.styleable#View_textAlignment
758 * @attr ref android.R.styleable#View_textDirection
759 * @attr ref android.R.styleable#View_transformPivotX
760 * @attr ref android.R.styleable#View_transformPivotY
761 * @attr ref android.R.styleable#View_translationX
762 * @attr ref android.R.styleable#View_translationY
763 * @attr ref android.R.styleable#View_translationZ
764 * @attr ref android.R.styleable#View_visibility
765 * @attr ref android.R.styleable#View_theme
766 *
767 * @see android.view.ViewGroup
768 */
769@UiThread
770public class View implements Drawable.Callback, KeyEvent.Callback,
771        AccessibilityEventSource {
772    private static final boolean DBG = false;
773
774    /** @hide */
775    public static boolean DEBUG_DRAW = false;
776
777    /**
778     * The logging tag used by this class with android.util.Log.
779     */
780    protected static final String VIEW_LOG_TAG = "View";
781
782    /**
783     * When set to true, apps will draw debugging information about their layouts.
784     *
785     * @hide
786     */
787    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
788
789    /**
790     * When set to true, this view will save its attribute data.
791     *
792     * @hide
793     */
794    public static boolean mDebugViewAttributes = false;
795
796    /**
797     * Used to mark a View that has no ID.
798     */
799    public static final int NO_ID = -1;
800
801    /**
802     * Signals that compatibility booleans have been initialized according to
803     * target SDK versions.
804     */
805    private static boolean sCompatibilityDone = false;
806
807    /**
808     * Use the old (broken) way of building MeasureSpecs.
809     */
810    private static boolean sUseBrokenMakeMeasureSpec = false;
811
812    /**
813     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
814     */
815    static boolean sUseZeroUnspecifiedMeasureSpec = false;
816
817    /**
818     * Ignore any optimizations using the measure cache.
819     */
820    private static boolean sIgnoreMeasureCache = false;
821
822    /**
823     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
824     */
825    private static boolean sAlwaysRemeasureExactly = false;
826
827    /**
828     * Relax constraints around whether setLayoutParams() must be called after
829     * modifying the layout params.
830     */
831    private static boolean sLayoutParamsAlwaysChanged = false;
832
833    /**
834     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
835     * without throwing
836     */
837    static boolean sTextureViewIgnoresDrawableSetters = false;
838
839    /**
840     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
841     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
842     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
843     * check is implemented for backwards compatibility.
844     *
845     * {@hide}
846     */
847    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
848
849    /**
850     * Prior to N, when drag enters into child of a view that has already received an
851     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
852     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
853     * false from its event handler for these events.
854     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
855     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
856     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
857     */
858    static boolean sCascadedDragDrop;
859
860    /** @hide */
861    @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO})
862    @Retention(RetentionPolicy.SOURCE)
863    public @interface Focusable {}
864
865    /**
866     * This view does not want keystrokes.
867     * <p>
868     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
869     * android:focusable}.
870     */
871    public static final int NOT_FOCUSABLE = 0x00000000;
872
873    /**
874     * This view wants keystrokes.
875     * <p>
876     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
877     * android:focusable}.
878     */
879    public static final int FOCUSABLE = 0x00000001;
880
881    /**
882     * This view determines focusability automatically. This is the default.
883     * <p>
884     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
885     * android:focusable}.
886     */
887    public static final int FOCUSABLE_AUTO = 0x00000010;
888
889    /**
890     * Mask for use with setFlags indicating bits used for focus.
891     */
892    private static final int FOCUSABLE_MASK = 0x00000011;
893
894    /**
895     * This view will adjust its padding to fit sytem windows (e.g. status bar)
896     */
897    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
898
899    /** @hide */
900    @IntDef({VISIBLE, INVISIBLE, GONE})
901    @Retention(RetentionPolicy.SOURCE)
902    public @interface Visibility {}
903
904    /**
905     * This view is visible.
906     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
907     * android:visibility}.
908     */
909    public static final int VISIBLE = 0x00000000;
910
911    /**
912     * This view is invisible, but it still takes up space for layout purposes.
913     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
914     * android:visibility}.
915     */
916    public static final int INVISIBLE = 0x00000004;
917
918    /**
919     * This view is invisible, and it doesn't take any space for layout
920     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
921     * android:visibility}.
922     */
923    public static final int GONE = 0x00000008;
924
925    /**
926     * Mask for use with setFlags indicating bits used for visibility.
927     * {@hide}
928     */
929    static final int VISIBILITY_MASK = 0x0000000C;
930
931    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
932
933    /**
934     * This view is enabled. Interpretation varies by subclass.
935     * Use with ENABLED_MASK when calling setFlags.
936     * {@hide}
937     */
938    static final int ENABLED = 0x00000000;
939
940    /**
941     * This view is disabled. Interpretation varies by subclass.
942     * Use with ENABLED_MASK when calling setFlags.
943     * {@hide}
944     */
945    static final int DISABLED = 0x00000020;
946
947   /**
948    * Mask for use with setFlags indicating bits used for indicating whether
949    * this view is enabled
950    * {@hide}
951    */
952    static final int ENABLED_MASK = 0x00000020;
953
954    /**
955     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
956     * called and further optimizations will be performed. It is okay to have
957     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
958     * {@hide}
959     */
960    static final int WILL_NOT_DRAW = 0x00000080;
961
962    /**
963     * Mask for use with setFlags indicating bits used for indicating whether
964     * this view is will draw
965     * {@hide}
966     */
967    static final int DRAW_MASK = 0x00000080;
968
969    /**
970     * <p>This view doesn't show scrollbars.</p>
971     * {@hide}
972     */
973    static final int SCROLLBARS_NONE = 0x00000000;
974
975    /**
976     * <p>This view shows horizontal scrollbars.</p>
977     * {@hide}
978     */
979    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
980
981    /**
982     * <p>This view shows vertical scrollbars.</p>
983     * {@hide}
984     */
985    static final int SCROLLBARS_VERTICAL = 0x00000200;
986
987    /**
988     * <p>Mask for use with setFlags indicating bits used for indicating which
989     * scrollbars are enabled.</p>
990     * {@hide}
991     */
992    static final int SCROLLBARS_MASK = 0x00000300;
993
994    /**
995     * Indicates that the view should filter touches when its window is obscured.
996     * Refer to the class comments for more information about this security feature.
997     * {@hide}
998     */
999    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
1000
1001    /**
1002     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
1003     * that they are optional and should be skipped if the window has
1004     * requested system UI flags that ignore those insets for layout.
1005     */
1006    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
1007
1008    /**
1009     * <p>This view doesn't show fading edges.</p>
1010     * {@hide}
1011     */
1012    static final int FADING_EDGE_NONE = 0x00000000;
1013
1014    /**
1015     * <p>This view shows horizontal fading edges.</p>
1016     * {@hide}
1017     */
1018    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1019
1020    /**
1021     * <p>This view shows vertical fading edges.</p>
1022     * {@hide}
1023     */
1024    static final int FADING_EDGE_VERTICAL = 0x00002000;
1025
1026    /**
1027     * <p>Mask for use with setFlags indicating bits used for indicating which
1028     * fading edges are enabled.</p>
1029     * {@hide}
1030     */
1031    static final int FADING_EDGE_MASK = 0x00003000;
1032
1033    /**
1034     * <p>Indicates this view can be clicked. When clickable, a View reacts
1035     * to clicks by notifying the OnClickListener.<p>
1036     * {@hide}
1037     */
1038    static final int CLICKABLE = 0x00004000;
1039
1040    /**
1041     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1042     * {@hide}
1043     */
1044    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1045
1046    /**
1047     * <p>Indicates that no icicle should be saved for this view.<p>
1048     * {@hide}
1049     */
1050    static final int SAVE_DISABLED = 0x000010000;
1051
1052    /**
1053     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1054     * property.</p>
1055     * {@hide}
1056     */
1057    static final int SAVE_DISABLED_MASK = 0x000010000;
1058
1059    /**
1060     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1061     * {@hide}
1062     */
1063    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1064
1065    /**
1066     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1067     * {@hide}
1068     */
1069    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1070
1071    /** @hide */
1072    @Retention(RetentionPolicy.SOURCE)
1073    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1074    public @interface DrawingCacheQuality {}
1075
1076    /**
1077     * <p>Enables low quality mode for the drawing cache.</p>
1078     */
1079    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1080
1081    /**
1082     * <p>Enables high quality mode for the drawing cache.</p>
1083     */
1084    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1085
1086    /**
1087     * <p>Enables automatic quality mode for the drawing cache.</p>
1088     */
1089    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1090
1091    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1092            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1093    };
1094
1095    /**
1096     * <p>Mask for use with setFlags indicating bits used for the cache
1097     * quality property.</p>
1098     * {@hide}
1099     */
1100    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1101
1102    /**
1103     * <p>
1104     * Indicates this view can be long clicked. When long clickable, a View
1105     * reacts to long clicks by notifying the OnLongClickListener or showing a
1106     * context menu.
1107     * </p>
1108     * {@hide}
1109     */
1110    static final int LONG_CLICKABLE = 0x00200000;
1111
1112    /**
1113     * <p>Indicates that this view gets its drawable states from its direct parent
1114     * and ignores its original internal states.</p>
1115     *
1116     * @hide
1117     */
1118    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1119
1120    /**
1121     * <p>
1122     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1123     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1124     * OnContextClickListener.
1125     * </p>
1126     * {@hide}
1127     */
1128    static final int CONTEXT_CLICKABLE = 0x00800000;
1129
1130
1131    /** @hide */
1132    @IntDef({
1133        SCROLLBARS_INSIDE_OVERLAY,
1134        SCROLLBARS_INSIDE_INSET,
1135        SCROLLBARS_OUTSIDE_OVERLAY,
1136        SCROLLBARS_OUTSIDE_INSET
1137    })
1138    @Retention(RetentionPolicy.SOURCE)
1139    public @interface ScrollBarStyle {}
1140
1141    /**
1142     * The scrollbar style to display the scrollbars inside the content area,
1143     * without increasing the padding. The scrollbars will be overlaid with
1144     * translucency on the view's content.
1145     */
1146    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1147
1148    /**
1149     * The scrollbar style to display the scrollbars inside the padded area,
1150     * increasing the padding of the view. The scrollbars will not overlap the
1151     * content area of the view.
1152     */
1153    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1154
1155    /**
1156     * The scrollbar style to display the scrollbars at the edge of the view,
1157     * without increasing the padding. The scrollbars will be overlaid with
1158     * translucency.
1159     */
1160    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1161
1162    /**
1163     * The scrollbar style to display the scrollbars at the edge of the view,
1164     * increasing the padding of the view. The scrollbars will only overlap the
1165     * background, if any.
1166     */
1167    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1168
1169    /**
1170     * Mask to check if the scrollbar style is overlay or inset.
1171     * {@hide}
1172     */
1173    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1174
1175    /**
1176     * Mask to check if the scrollbar style is inside or outside.
1177     * {@hide}
1178     */
1179    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1180
1181    /**
1182     * Mask for scrollbar style.
1183     * {@hide}
1184     */
1185    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1186
1187    /**
1188     * View flag indicating that the screen should remain on while the
1189     * window containing this view is visible to the user.  This effectively
1190     * takes care of automatically setting the WindowManager's
1191     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1192     */
1193    public static final int KEEP_SCREEN_ON = 0x04000000;
1194
1195    /**
1196     * View flag indicating whether this view should have sound effects enabled
1197     * for events such as clicking and touching.
1198     */
1199    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1200
1201    /**
1202     * View flag indicating whether this view should have haptic feedback
1203     * enabled for events such as long presses.
1204     */
1205    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1206
1207    /**
1208     * <p>Indicates that the view hierarchy should stop saving state when
1209     * it reaches this view.  If state saving is initiated immediately at
1210     * the view, it will be allowed.
1211     * {@hide}
1212     */
1213    static final int PARENT_SAVE_DISABLED = 0x20000000;
1214
1215    /**
1216     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1217     * {@hide}
1218     */
1219    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1220
1221    private static Paint sDebugPaint;
1222
1223    /**
1224     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1225     * {@hide}
1226     */
1227    static final int TOOLTIP = 0x40000000;
1228
1229    /** @hide */
1230    @IntDef(flag = true,
1231            value = {
1232                FOCUSABLES_ALL,
1233                FOCUSABLES_TOUCH_MODE
1234            })
1235    @Retention(RetentionPolicy.SOURCE)
1236    public @interface FocusableMode {}
1237
1238    /**
1239     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1240     * should add all focusable Views regardless if they are focusable in touch mode.
1241     */
1242    public static final int FOCUSABLES_ALL = 0x00000000;
1243
1244    /**
1245     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1246     * should add only Views focusable in touch mode.
1247     */
1248    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1249
1250    /** @hide */
1251    @IntDef({
1252            FOCUS_BACKWARD,
1253            FOCUS_FORWARD,
1254            FOCUS_LEFT,
1255            FOCUS_UP,
1256            FOCUS_RIGHT,
1257            FOCUS_DOWN
1258    })
1259    @Retention(RetentionPolicy.SOURCE)
1260    public @interface FocusDirection {}
1261
1262    /** @hide */
1263    @IntDef({
1264            FOCUS_LEFT,
1265            FOCUS_UP,
1266            FOCUS_RIGHT,
1267            FOCUS_DOWN
1268    })
1269    @Retention(RetentionPolicy.SOURCE)
1270    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1271
1272    /**
1273     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1274     * item.
1275     */
1276    public static final int FOCUS_BACKWARD = 0x00000001;
1277
1278    /**
1279     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1280     * item.
1281     */
1282    public static final int FOCUS_FORWARD = 0x00000002;
1283
1284    /**
1285     * Use with {@link #focusSearch(int)}. Move focus to the left.
1286     */
1287    public static final int FOCUS_LEFT = 0x00000011;
1288
1289    /**
1290     * Use with {@link #focusSearch(int)}. Move focus up.
1291     */
1292    public static final int FOCUS_UP = 0x00000021;
1293
1294    /**
1295     * Use with {@link #focusSearch(int)}. Move focus to the right.
1296     */
1297    public static final int FOCUS_RIGHT = 0x00000042;
1298
1299    /**
1300     * Use with {@link #focusSearch(int)}. Move focus down.
1301     */
1302    public static final int FOCUS_DOWN = 0x00000082;
1303
1304    /**
1305     * Bits of {@link #getMeasuredWidthAndState()} and
1306     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1307     */
1308    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1309
1310    /**
1311     * Bits of {@link #getMeasuredWidthAndState()} and
1312     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1313     */
1314    public static final int MEASURED_STATE_MASK = 0xff000000;
1315
1316    /**
1317     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1318     * for functions that combine both width and height into a single int,
1319     * such as {@link #getMeasuredState()} and the childState argument of
1320     * {@link #resolveSizeAndState(int, int, int)}.
1321     */
1322    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1323
1324    /**
1325     * Bit of {@link #getMeasuredWidthAndState()} and
1326     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1327     * is smaller that the space the view would like to have.
1328     */
1329    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1330
1331    /**
1332     * Base View state sets
1333     */
1334    // Singles
1335    /**
1336     * Indicates the view has no states set. States are used with
1337     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1338     * view depending on its state.
1339     *
1340     * @see android.graphics.drawable.Drawable
1341     * @see #getDrawableState()
1342     */
1343    protected static final int[] EMPTY_STATE_SET;
1344    /**
1345     * Indicates the view is enabled. States are used with
1346     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1347     * view depending on its state.
1348     *
1349     * @see android.graphics.drawable.Drawable
1350     * @see #getDrawableState()
1351     */
1352    protected static final int[] ENABLED_STATE_SET;
1353    /**
1354     * Indicates the view is focused. States are used with
1355     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1356     * view depending on its state.
1357     *
1358     * @see android.graphics.drawable.Drawable
1359     * @see #getDrawableState()
1360     */
1361    protected static final int[] FOCUSED_STATE_SET;
1362    /**
1363     * Indicates the view is selected. States are used with
1364     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1365     * view depending on its state.
1366     *
1367     * @see android.graphics.drawable.Drawable
1368     * @see #getDrawableState()
1369     */
1370    protected static final int[] SELECTED_STATE_SET;
1371    /**
1372     * Indicates the view is pressed. States are used with
1373     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1374     * view depending on its state.
1375     *
1376     * @see android.graphics.drawable.Drawable
1377     * @see #getDrawableState()
1378     */
1379    protected static final int[] PRESSED_STATE_SET;
1380    /**
1381     * Indicates the view's window has focus. States are used with
1382     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1383     * view depending on its state.
1384     *
1385     * @see android.graphics.drawable.Drawable
1386     * @see #getDrawableState()
1387     */
1388    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1389    // Doubles
1390    /**
1391     * Indicates the view is enabled and has the focus.
1392     *
1393     * @see #ENABLED_STATE_SET
1394     * @see #FOCUSED_STATE_SET
1395     */
1396    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1397    /**
1398     * Indicates the view is enabled and selected.
1399     *
1400     * @see #ENABLED_STATE_SET
1401     * @see #SELECTED_STATE_SET
1402     */
1403    protected static final int[] ENABLED_SELECTED_STATE_SET;
1404    /**
1405     * Indicates the view is enabled and that its window has focus.
1406     *
1407     * @see #ENABLED_STATE_SET
1408     * @see #WINDOW_FOCUSED_STATE_SET
1409     */
1410    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1411    /**
1412     * Indicates the view is focused and selected.
1413     *
1414     * @see #FOCUSED_STATE_SET
1415     * @see #SELECTED_STATE_SET
1416     */
1417    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1418    /**
1419     * Indicates the view has the focus and that its window has the focus.
1420     *
1421     * @see #FOCUSED_STATE_SET
1422     * @see #WINDOW_FOCUSED_STATE_SET
1423     */
1424    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1425    /**
1426     * Indicates the view is selected and that its window has the focus.
1427     *
1428     * @see #SELECTED_STATE_SET
1429     * @see #WINDOW_FOCUSED_STATE_SET
1430     */
1431    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1432    // Triples
1433    /**
1434     * Indicates the view is enabled, focused and selected.
1435     *
1436     * @see #ENABLED_STATE_SET
1437     * @see #FOCUSED_STATE_SET
1438     * @see #SELECTED_STATE_SET
1439     */
1440    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1441    /**
1442     * Indicates the view is enabled, focused and its window has the focus.
1443     *
1444     * @see #ENABLED_STATE_SET
1445     * @see #FOCUSED_STATE_SET
1446     * @see #WINDOW_FOCUSED_STATE_SET
1447     */
1448    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1449    /**
1450     * Indicates the view is enabled, selected and its window has the focus.
1451     *
1452     * @see #ENABLED_STATE_SET
1453     * @see #SELECTED_STATE_SET
1454     * @see #WINDOW_FOCUSED_STATE_SET
1455     */
1456    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1457    /**
1458     * Indicates the view is focused, selected and its window has the focus.
1459     *
1460     * @see #FOCUSED_STATE_SET
1461     * @see #SELECTED_STATE_SET
1462     * @see #WINDOW_FOCUSED_STATE_SET
1463     */
1464    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1465    /**
1466     * Indicates the view is enabled, focused, selected and its window
1467     * has the focus.
1468     *
1469     * @see #ENABLED_STATE_SET
1470     * @see #FOCUSED_STATE_SET
1471     * @see #SELECTED_STATE_SET
1472     * @see #WINDOW_FOCUSED_STATE_SET
1473     */
1474    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1475    /**
1476     * Indicates the view is pressed and its window has the focus.
1477     *
1478     * @see #PRESSED_STATE_SET
1479     * @see #WINDOW_FOCUSED_STATE_SET
1480     */
1481    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1482    /**
1483     * Indicates the view is pressed and selected.
1484     *
1485     * @see #PRESSED_STATE_SET
1486     * @see #SELECTED_STATE_SET
1487     */
1488    protected static final int[] PRESSED_SELECTED_STATE_SET;
1489    /**
1490     * Indicates the view is pressed, selected and its window has the focus.
1491     *
1492     * @see #PRESSED_STATE_SET
1493     * @see #SELECTED_STATE_SET
1494     * @see #WINDOW_FOCUSED_STATE_SET
1495     */
1496    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1497    /**
1498     * Indicates the view is pressed and focused.
1499     *
1500     * @see #PRESSED_STATE_SET
1501     * @see #FOCUSED_STATE_SET
1502     */
1503    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1504    /**
1505     * Indicates the view is pressed, focused and its window has the focus.
1506     *
1507     * @see #PRESSED_STATE_SET
1508     * @see #FOCUSED_STATE_SET
1509     * @see #WINDOW_FOCUSED_STATE_SET
1510     */
1511    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1512    /**
1513     * Indicates the view is pressed, focused and selected.
1514     *
1515     * @see #PRESSED_STATE_SET
1516     * @see #SELECTED_STATE_SET
1517     * @see #FOCUSED_STATE_SET
1518     */
1519    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1520    /**
1521     * Indicates the view is pressed, focused, selected and its window has the focus.
1522     *
1523     * @see #PRESSED_STATE_SET
1524     * @see #FOCUSED_STATE_SET
1525     * @see #SELECTED_STATE_SET
1526     * @see #WINDOW_FOCUSED_STATE_SET
1527     */
1528    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1529    /**
1530     * Indicates the view is pressed and enabled.
1531     *
1532     * @see #PRESSED_STATE_SET
1533     * @see #ENABLED_STATE_SET
1534     */
1535    protected static final int[] PRESSED_ENABLED_STATE_SET;
1536    /**
1537     * Indicates the view is pressed, enabled and its window has the focus.
1538     *
1539     * @see #PRESSED_STATE_SET
1540     * @see #ENABLED_STATE_SET
1541     * @see #WINDOW_FOCUSED_STATE_SET
1542     */
1543    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1544    /**
1545     * Indicates the view is pressed, enabled and selected.
1546     *
1547     * @see #PRESSED_STATE_SET
1548     * @see #ENABLED_STATE_SET
1549     * @see #SELECTED_STATE_SET
1550     */
1551    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1552    /**
1553     * Indicates the view is pressed, enabled, selected and its window has the
1554     * focus.
1555     *
1556     * @see #PRESSED_STATE_SET
1557     * @see #ENABLED_STATE_SET
1558     * @see #SELECTED_STATE_SET
1559     * @see #WINDOW_FOCUSED_STATE_SET
1560     */
1561    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1562    /**
1563     * Indicates the view is pressed, enabled and focused.
1564     *
1565     * @see #PRESSED_STATE_SET
1566     * @see #ENABLED_STATE_SET
1567     * @see #FOCUSED_STATE_SET
1568     */
1569    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1570    /**
1571     * Indicates the view is pressed, enabled, focused and its window has the
1572     * focus.
1573     *
1574     * @see #PRESSED_STATE_SET
1575     * @see #ENABLED_STATE_SET
1576     * @see #FOCUSED_STATE_SET
1577     * @see #WINDOW_FOCUSED_STATE_SET
1578     */
1579    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1580    /**
1581     * Indicates the view is pressed, enabled, focused and selected.
1582     *
1583     * @see #PRESSED_STATE_SET
1584     * @see #ENABLED_STATE_SET
1585     * @see #SELECTED_STATE_SET
1586     * @see #FOCUSED_STATE_SET
1587     */
1588    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1589    /**
1590     * Indicates the view is pressed, enabled, focused, selected and its window
1591     * has the focus.
1592     *
1593     * @see #PRESSED_STATE_SET
1594     * @see #ENABLED_STATE_SET
1595     * @see #SELECTED_STATE_SET
1596     * @see #FOCUSED_STATE_SET
1597     * @see #WINDOW_FOCUSED_STATE_SET
1598     */
1599    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1600
1601    static {
1602        EMPTY_STATE_SET = StateSet.get(0);
1603
1604        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1605
1606        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1607        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1608                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1609
1610        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1611        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1612                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1613        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1614                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1615        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1616                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1617                        | StateSet.VIEW_STATE_FOCUSED);
1618
1619        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1620        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1621                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1622        ENABLED_SELECTED_STATE_SET = StateSet.get(
1623                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1624        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1625                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1626                        | StateSet.VIEW_STATE_ENABLED);
1627        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1628                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1629        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1630                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1631                        | StateSet.VIEW_STATE_ENABLED);
1632        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1633                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1634                        | StateSet.VIEW_STATE_ENABLED);
1635        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1636                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1637                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1638
1639        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1640        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1641                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1642        PRESSED_SELECTED_STATE_SET = StateSet.get(
1643                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1644        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1645                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1646                        | StateSet.VIEW_STATE_PRESSED);
1647        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1648                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1649        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1650                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1651                        | StateSet.VIEW_STATE_PRESSED);
1652        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1653                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1654                        | StateSet.VIEW_STATE_PRESSED);
1655        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1656                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1657                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1658        PRESSED_ENABLED_STATE_SET = StateSet.get(
1659                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1660        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1661                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1662                        | StateSet.VIEW_STATE_PRESSED);
1663        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1664                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1665                        | StateSet.VIEW_STATE_PRESSED);
1666        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1667                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1668                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1669        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1670                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1671                        | StateSet.VIEW_STATE_PRESSED);
1672        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1673                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1674                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1675        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1676                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1677                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1678        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1679                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1680                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1681                        | StateSet.VIEW_STATE_PRESSED);
1682    }
1683
1684    /**
1685     * Accessibility event types that are dispatched for text population.
1686     */
1687    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1688            AccessibilityEvent.TYPE_VIEW_CLICKED
1689            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1690            | AccessibilityEvent.TYPE_VIEW_SELECTED
1691            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1692            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1693            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1694            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1695            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1696            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1697            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1698            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1699
1700    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
1701
1702    static final int DEBUG_CORNERS_SIZE_DIP = 8;
1703
1704    /**
1705     * Temporary Rect currently for use in setBackground().  This will probably
1706     * be extended in the future to hold our own class with more than just
1707     * a Rect. :)
1708     */
1709    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1710
1711    /**
1712     * Map used to store views' tags.
1713     */
1714    private SparseArray<Object> mKeyedTags;
1715
1716    /**
1717     * The next available accessibility id.
1718     */
1719    private static int sNextAccessibilityViewId;
1720
1721    /**
1722     * The animation currently associated with this view.
1723     * @hide
1724     */
1725    protected Animation mCurrentAnimation = null;
1726
1727    /**
1728     * Width as measured during measure pass.
1729     * {@hide}
1730     */
1731    @ViewDebug.ExportedProperty(category = "measurement")
1732    int mMeasuredWidth;
1733
1734    /**
1735     * Height as measured during measure pass.
1736     * {@hide}
1737     */
1738    @ViewDebug.ExportedProperty(category = "measurement")
1739    int mMeasuredHeight;
1740
1741    /**
1742     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1743     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1744     * its display list. This flag, used only when hw accelerated, allows us to clear the
1745     * flag while retaining this information until it's needed (at getDisplayList() time and
1746     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1747     *
1748     * {@hide}
1749     */
1750    boolean mRecreateDisplayList = false;
1751
1752    /**
1753     * The view's identifier.
1754     * {@hide}
1755     *
1756     * @see #setId(int)
1757     * @see #getId()
1758     */
1759    @IdRes
1760    @ViewDebug.ExportedProperty(resolveId = true)
1761    int mID = NO_ID;
1762
1763    /**
1764     * The stable ID of this view for accessibility purposes.
1765     */
1766    int mAccessibilityViewId = NO_ID;
1767
1768    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1769
1770    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1771
1772    /**
1773     * The view's tag.
1774     * {@hide}
1775     *
1776     * @see #setTag(Object)
1777     * @see #getTag()
1778     */
1779    protected Object mTag = null;
1780
1781    // for mPrivateFlags:
1782    /** {@hide} */
1783    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1784    /** {@hide} */
1785    static final int PFLAG_FOCUSED                     = 0x00000002;
1786    /** {@hide} */
1787    static final int PFLAG_SELECTED                    = 0x00000004;
1788    /** {@hide} */
1789    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1790    /** {@hide} */
1791    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1792    /** {@hide} */
1793    static final int PFLAG_DRAWN                       = 0x00000020;
1794    /**
1795     * When this flag is set, this view is running an animation on behalf of its
1796     * children and should therefore not cancel invalidate requests, even if they
1797     * lie outside of this view's bounds.
1798     *
1799     * {@hide}
1800     */
1801    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1802    /** {@hide} */
1803    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1804    /** {@hide} */
1805    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1806    /** {@hide} */
1807    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1808    /** {@hide} */
1809    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1810    /** {@hide} */
1811    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1812    /** {@hide} */
1813    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1814
1815    private static final int PFLAG_PRESSED             = 0x00004000;
1816
1817    /** {@hide} */
1818    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1819    /**
1820     * Flag used to indicate that this view should be drawn once more (and only once
1821     * more) after its animation has completed.
1822     * {@hide}
1823     */
1824    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1825
1826    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1827
1828    /**
1829     * Indicates that the View returned true when onSetAlpha() was called and that
1830     * the alpha must be restored.
1831     * {@hide}
1832     */
1833    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1834
1835    /**
1836     * Set by {@link #setScrollContainer(boolean)}.
1837     */
1838    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1839
1840    /**
1841     * Set by {@link #setScrollContainer(boolean)}.
1842     */
1843    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1844
1845    /**
1846     * View flag indicating whether this view was invalidated (fully or partially.)
1847     *
1848     * @hide
1849     */
1850    static final int PFLAG_DIRTY                       = 0x00200000;
1851
1852    /**
1853     * View flag indicating whether this view was invalidated by an opaque
1854     * invalidate request.
1855     *
1856     * @hide
1857     */
1858    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1859
1860    /**
1861     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1862     *
1863     * @hide
1864     */
1865    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1866
1867    /**
1868     * Indicates whether the background is opaque.
1869     *
1870     * @hide
1871     */
1872    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1873
1874    /**
1875     * Indicates whether the scrollbars are opaque.
1876     *
1877     * @hide
1878     */
1879    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1880
1881    /**
1882     * Indicates whether the view is opaque.
1883     *
1884     * @hide
1885     */
1886    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1887
1888    /**
1889     * Indicates a prepressed state;
1890     * the short time between ACTION_DOWN and recognizing
1891     * a 'real' press. Prepressed is used to recognize quick taps
1892     * even when they are shorter than ViewConfiguration.getTapTimeout().
1893     *
1894     * @hide
1895     */
1896    private static final int PFLAG_PREPRESSED          = 0x02000000;
1897
1898    /**
1899     * Indicates whether the view is temporarily detached.
1900     *
1901     * @hide
1902     */
1903    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1904
1905    /**
1906     * Indicates that we should awaken scroll bars once attached
1907     *
1908     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1909     * during window attachment and it is no longer needed. Feel free to repurpose it.
1910     *
1911     * @hide
1912     */
1913    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1914
1915    /**
1916     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1917     * @hide
1918     */
1919    private static final int PFLAG_HOVERED             = 0x10000000;
1920
1921    /**
1922     * no longer needed, should be reused
1923     */
1924    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1925
1926    /** {@hide} */
1927    static final int PFLAG_ACTIVATED                   = 0x40000000;
1928
1929    /**
1930     * Indicates that this view was specifically invalidated, not just dirtied because some
1931     * child view was invalidated. The flag is used to determine when we need to recreate
1932     * a view's display list (as opposed to just returning a reference to its existing
1933     * display list).
1934     *
1935     * @hide
1936     */
1937    static final int PFLAG_INVALIDATED                 = 0x80000000;
1938
1939    /**
1940     * Masks for mPrivateFlags2, as generated by dumpFlags():
1941     *
1942     * |-------|-------|-------|-------|
1943     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1944     *                                1  PFLAG2_DRAG_HOVERED
1945     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1946     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1947     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1948     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1949     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1950     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1951     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1952     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1953     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1954     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1955     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1956     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1957     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1958     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1959     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1960     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1961     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1962     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1963     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1964     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1965     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1966     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1967     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1968     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1969     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1970     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1971     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1972     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1973     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1974     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1975     *    1                              PFLAG2_PADDING_RESOLVED
1976     *   1                               PFLAG2_DRAWABLE_RESOLVED
1977     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1978     * |-------|-------|-------|-------|
1979     */
1980
1981    /**
1982     * Indicates that this view has reported that it can accept the current drag's content.
1983     * Cleared when the drag operation concludes.
1984     * @hide
1985     */
1986    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1987
1988    /**
1989     * Indicates that this view is currently directly under the drag location in a
1990     * drag-and-drop operation involving content that it can accept.  Cleared when
1991     * the drag exits the view, or when the drag operation concludes.
1992     * @hide
1993     */
1994    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1995
1996    /** @hide */
1997    @IntDef({
1998        LAYOUT_DIRECTION_LTR,
1999        LAYOUT_DIRECTION_RTL,
2000        LAYOUT_DIRECTION_INHERIT,
2001        LAYOUT_DIRECTION_LOCALE
2002    })
2003    @Retention(RetentionPolicy.SOURCE)
2004    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2005    public @interface LayoutDir {}
2006
2007    /** @hide */
2008    @IntDef({
2009        LAYOUT_DIRECTION_LTR,
2010        LAYOUT_DIRECTION_RTL
2011    })
2012    @Retention(RetentionPolicy.SOURCE)
2013    public @interface ResolvedLayoutDir {}
2014
2015    /**
2016     * A flag to indicate that the layout direction of this view has not been defined yet.
2017     * @hide
2018     */
2019    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2020
2021    /**
2022     * Horizontal layout direction of this view is from Left to Right.
2023     * Use with {@link #setLayoutDirection}.
2024     */
2025    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2026
2027    /**
2028     * Horizontal layout direction of this view is from Right to Left.
2029     * Use with {@link #setLayoutDirection}.
2030     */
2031    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2032
2033    /**
2034     * Horizontal layout direction of this view is inherited from its parent.
2035     * Use with {@link #setLayoutDirection}.
2036     */
2037    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2038
2039    /**
2040     * Horizontal layout direction of this view is from deduced from the default language
2041     * script for the locale. Use with {@link #setLayoutDirection}.
2042     */
2043    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2044
2045    /**
2046     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2047     * @hide
2048     */
2049    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2050
2051    /**
2052     * Mask for use with private flags indicating bits used for horizontal layout direction.
2053     * @hide
2054     */
2055    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2056
2057    /**
2058     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2059     * right-to-left direction.
2060     * @hide
2061     */
2062    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2063
2064    /**
2065     * Indicates whether the view horizontal layout direction has been resolved.
2066     * @hide
2067     */
2068    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2069
2070    /**
2071     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2072     * @hide
2073     */
2074    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2075            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2076
2077    /*
2078     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2079     * flag value.
2080     * @hide
2081     */
2082    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2083            LAYOUT_DIRECTION_LTR,
2084            LAYOUT_DIRECTION_RTL,
2085            LAYOUT_DIRECTION_INHERIT,
2086            LAYOUT_DIRECTION_LOCALE
2087    };
2088
2089    /**
2090     * Default horizontal layout direction.
2091     */
2092    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2093
2094    /**
2095     * Default horizontal layout direction.
2096     * @hide
2097     */
2098    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2099
2100    /**
2101     * Text direction is inherited through {@link ViewGroup}
2102     */
2103    public static final int TEXT_DIRECTION_INHERIT = 0;
2104
2105    /**
2106     * Text direction is using "first strong algorithm". The first strong directional character
2107     * determines the paragraph direction. If there is no strong directional character, the
2108     * paragraph direction is the view's resolved layout direction.
2109     */
2110    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2111
2112    /**
2113     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2114     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2115     * If there are neither, the paragraph direction is the view's resolved layout direction.
2116     */
2117    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2118
2119    /**
2120     * Text direction is forced to LTR.
2121     */
2122    public static final int TEXT_DIRECTION_LTR = 3;
2123
2124    /**
2125     * Text direction is forced to RTL.
2126     */
2127    public static final int TEXT_DIRECTION_RTL = 4;
2128
2129    /**
2130     * Text direction is coming from the system Locale.
2131     */
2132    public static final int TEXT_DIRECTION_LOCALE = 5;
2133
2134    /**
2135     * Text direction is using "first strong algorithm". The first strong directional character
2136     * determines the paragraph direction. If there is no strong directional character, the
2137     * paragraph direction is LTR.
2138     */
2139    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2140
2141    /**
2142     * Text direction is using "first strong algorithm". The first strong directional character
2143     * determines the paragraph direction. If there is no strong directional character, the
2144     * paragraph direction is RTL.
2145     */
2146    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2147
2148    /**
2149     * Default text direction is inherited
2150     */
2151    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2152
2153    /**
2154     * Default resolved text direction
2155     * @hide
2156     */
2157    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2158
2159    /**
2160     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2161     * @hide
2162     */
2163    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2164
2165    /**
2166     * Mask for use with private flags indicating bits used for text direction.
2167     * @hide
2168     */
2169    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2170            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2171
2172    /**
2173     * Array of text direction flags for mapping attribute "textDirection" to correct
2174     * flag value.
2175     * @hide
2176     */
2177    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2178            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2179            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2180            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2181            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2182            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2183            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2184            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2185            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2186    };
2187
2188    /**
2189     * Indicates whether the view text direction has been resolved.
2190     * @hide
2191     */
2192    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2193            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2194
2195    /**
2196     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2197     * @hide
2198     */
2199    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2200
2201    /**
2202     * Mask for use with private flags indicating bits used for resolved text direction.
2203     * @hide
2204     */
2205    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2206            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2207
2208    /**
2209     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2210     * @hide
2211     */
2212    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2213            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2214
2215    /** @hide */
2216    @IntDef({
2217        TEXT_ALIGNMENT_INHERIT,
2218        TEXT_ALIGNMENT_GRAVITY,
2219        TEXT_ALIGNMENT_CENTER,
2220        TEXT_ALIGNMENT_TEXT_START,
2221        TEXT_ALIGNMENT_TEXT_END,
2222        TEXT_ALIGNMENT_VIEW_START,
2223        TEXT_ALIGNMENT_VIEW_END
2224    })
2225    @Retention(RetentionPolicy.SOURCE)
2226    public @interface TextAlignment {}
2227
2228    /**
2229     * Default text alignment. The text alignment of this View is inherited from its parent.
2230     * Use with {@link #setTextAlignment(int)}
2231     */
2232    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2233
2234    /**
2235     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2236     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2237     *
2238     * Use with {@link #setTextAlignment(int)}
2239     */
2240    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2241
2242    /**
2243     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2244     *
2245     * Use with {@link #setTextAlignment(int)}
2246     */
2247    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2248
2249    /**
2250     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2251     *
2252     * Use with {@link #setTextAlignment(int)}
2253     */
2254    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2255
2256    /**
2257     * Center the paragraph, e.g. ALIGN_CENTER.
2258     *
2259     * Use with {@link #setTextAlignment(int)}
2260     */
2261    public static final int TEXT_ALIGNMENT_CENTER = 4;
2262
2263    /**
2264     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2265     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2266     *
2267     * Use with {@link #setTextAlignment(int)}
2268     */
2269    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2270
2271    /**
2272     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2273     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2274     *
2275     * Use with {@link #setTextAlignment(int)}
2276     */
2277    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2278
2279    /**
2280     * Default text alignment is inherited
2281     */
2282    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2283
2284    /**
2285     * Default resolved text alignment
2286     * @hide
2287     */
2288    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2289
2290    /**
2291      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2292      * @hide
2293      */
2294    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2295
2296    /**
2297      * Mask for use with private flags indicating bits used for text alignment.
2298      * @hide
2299      */
2300    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2301
2302    /**
2303     * Array of text direction flags for mapping attribute "textAlignment" to correct
2304     * flag value.
2305     * @hide
2306     */
2307    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2308            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2309            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2310            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2311            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2312            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2313            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2314            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2315    };
2316
2317    /**
2318     * Indicates whether the view text alignment has been resolved.
2319     * @hide
2320     */
2321    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2322
2323    /**
2324     * Bit shift to get the resolved text alignment.
2325     * @hide
2326     */
2327    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2328
2329    /**
2330     * Mask for use with private flags indicating bits used for text alignment.
2331     * @hide
2332     */
2333    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2334            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2335
2336    /**
2337     * Indicates whether if the view text alignment has been resolved to gravity
2338     */
2339    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2340            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2341
2342    // Accessiblity constants for mPrivateFlags2
2343
2344    /**
2345     * Shift for the bits in {@link #mPrivateFlags2} related to the
2346     * "importantForAccessibility" attribute.
2347     */
2348    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2349
2350    /**
2351     * Automatically determine whether a view is important for accessibility.
2352     */
2353    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2354
2355    /**
2356     * The view is important for accessibility.
2357     */
2358    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2359
2360    /**
2361     * The view is not important for accessibility.
2362     */
2363    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2364
2365    /**
2366     * The view is not important for accessibility, nor are any of its
2367     * descendant views.
2368     */
2369    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2370
2371    /**
2372     * The default whether the view is important for accessibility.
2373     */
2374    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2375
2376    /**
2377     * Mask for obtaining the bits which specify how to determine
2378     * whether a view is important for accessibility.
2379     */
2380    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2381        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2382        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2383        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2384
2385    /**
2386     * Shift for the bits in {@link #mPrivateFlags2} related to the
2387     * "accessibilityLiveRegion" attribute.
2388     */
2389    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2390
2391    /**
2392     * Live region mode specifying that accessibility services should not
2393     * automatically announce changes to this view. This is the default live
2394     * region mode for most views.
2395     * <p>
2396     * Use with {@link #setAccessibilityLiveRegion(int)}.
2397     */
2398    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2399
2400    /**
2401     * Live region mode specifying that accessibility services should announce
2402     * changes to this view.
2403     * <p>
2404     * Use with {@link #setAccessibilityLiveRegion(int)}.
2405     */
2406    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2407
2408    /**
2409     * Live region mode specifying that accessibility services should interrupt
2410     * ongoing speech to immediately announce changes to this view.
2411     * <p>
2412     * Use with {@link #setAccessibilityLiveRegion(int)}.
2413     */
2414    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2415
2416    /**
2417     * The default whether the view is important for accessibility.
2418     */
2419    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2420
2421    /**
2422     * Mask for obtaining the bits which specify a view's accessibility live
2423     * region mode.
2424     */
2425    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2426            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2427            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2428
2429    /**
2430     * Flag indicating whether a view has accessibility focus.
2431     */
2432    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2433
2434    /**
2435     * Flag whether the accessibility state of the subtree rooted at this view changed.
2436     */
2437    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2438
2439    /**
2440     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2441     * is used to check whether later changes to the view's transform should invalidate the
2442     * view to force the quickReject test to run again.
2443     */
2444    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2445
2446    /**
2447     * Flag indicating that start/end padding has been resolved into left/right padding
2448     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2449     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2450     * during measurement. In some special cases this is required such as when an adapter-based
2451     * view measures prospective children without attaching them to a window.
2452     */
2453    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2454
2455    /**
2456     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2457     */
2458    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2459
2460    /**
2461     * Indicates that the view is tracking some sort of transient state
2462     * that the app should not need to be aware of, but that the framework
2463     * should take special care to preserve.
2464     */
2465    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2466
2467    /**
2468     * Group of bits indicating that RTL properties resolution is done.
2469     */
2470    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2471            PFLAG2_TEXT_DIRECTION_RESOLVED |
2472            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2473            PFLAG2_PADDING_RESOLVED |
2474            PFLAG2_DRAWABLE_RESOLVED;
2475
2476    // There are a couple of flags left in mPrivateFlags2
2477
2478    /* End of masks for mPrivateFlags2 */
2479
2480    /**
2481     * Masks for mPrivateFlags3, as generated by dumpFlags():
2482     *
2483     * |-------|-------|-------|-------|
2484     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2485     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2486     *                               1   PFLAG3_IS_LAID_OUT
2487     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2488     *                             1     PFLAG3_CALLED_SUPER
2489     *                            1      PFLAG3_APPLYING_INSETS
2490     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2491     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2492     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2493     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2494     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2495     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2496     *                     1             PFLAG3_SCROLL_INDICATOR_START
2497     *                    1              PFLAG3_SCROLL_INDICATOR_END
2498     *                   1               PFLAG3_ASSIST_BLOCKED
2499     *                  1                PFLAG3_CLUSTER
2500     *                 x                 * NO LONGER NEEDED, SHOULD BE REUSED *
2501     *                1                  PFLAG3_FINGER_DOWN
2502     *               1                   PFLAG3_FOCUSED_BY_DEFAULT
2503     *           xxxx                    * NO LONGER NEEDED, SHOULD BE REUSED *
2504     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2505     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2506     *        1                          PFLAG3_TEMPORARY_DETACH
2507     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2508     * |-------|-------|-------|-------|
2509     */
2510
2511    /**
2512     * Flag indicating that view has a transform animation set on it. This is used to track whether
2513     * an animation is cleared between successive frames, in order to tell the associated
2514     * DisplayList to clear its animation matrix.
2515     */
2516    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2517
2518    /**
2519     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2520     * animation is cleared between successive frames, in order to tell the associated
2521     * DisplayList to restore its alpha value.
2522     */
2523    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2524
2525    /**
2526     * Flag indicating that the view has been through at least one layout since it
2527     * was last attached to a window.
2528     */
2529    static final int PFLAG3_IS_LAID_OUT = 0x4;
2530
2531    /**
2532     * Flag indicating that a call to measure() was skipped and should be done
2533     * instead when layout() is invoked.
2534     */
2535    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2536
2537    /**
2538     * Flag indicating that an overridden method correctly called down to
2539     * the superclass implementation as required by the API spec.
2540     */
2541    static final int PFLAG3_CALLED_SUPER = 0x10;
2542
2543    /**
2544     * Flag indicating that we're in the process of applying window insets.
2545     */
2546    static final int PFLAG3_APPLYING_INSETS = 0x20;
2547
2548    /**
2549     * Flag indicating that we're in the process of fitting system windows using the old method.
2550     */
2551    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2552
2553    /**
2554     * Flag indicating that nested scrolling is enabled for this view.
2555     * The view will optionally cooperate with views up its parent chain to allow for
2556     * integrated nested scrolling along the same axis.
2557     */
2558    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2559
2560    /**
2561     * Flag indicating that the bottom scroll indicator should be displayed
2562     * when this view can scroll up.
2563     */
2564    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2565
2566    /**
2567     * Flag indicating that the bottom scroll indicator should be displayed
2568     * when this view can scroll down.
2569     */
2570    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2571
2572    /**
2573     * Flag indicating that the left scroll indicator should be displayed
2574     * when this view can scroll left.
2575     */
2576    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2577
2578    /**
2579     * Flag indicating that the right scroll indicator should be displayed
2580     * when this view can scroll right.
2581     */
2582    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2583
2584    /**
2585     * Flag indicating that the start scroll indicator should be displayed
2586     * when this view can scroll in the start direction.
2587     */
2588    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2589
2590    /**
2591     * Flag indicating that the end scroll indicator should be displayed
2592     * when this view can scroll in the end direction.
2593     */
2594    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2595
2596    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2597
2598    static final int SCROLL_INDICATORS_NONE = 0x0000;
2599
2600    /**
2601     * Mask for use with setFlags indicating bits used for indicating which
2602     * scroll indicators are enabled.
2603     */
2604    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2605            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2606            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2607            | PFLAG3_SCROLL_INDICATOR_END;
2608
2609    /**
2610     * Left-shift required to translate between public scroll indicator flags
2611     * and internal PFLAGS3 flags. When used as a right-shift, translates
2612     * PFLAGS3 flags to public flags.
2613     */
2614    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2615
2616    /** @hide */
2617    @Retention(RetentionPolicy.SOURCE)
2618    @IntDef(flag = true,
2619            value = {
2620                    SCROLL_INDICATOR_TOP,
2621                    SCROLL_INDICATOR_BOTTOM,
2622                    SCROLL_INDICATOR_LEFT,
2623                    SCROLL_INDICATOR_RIGHT,
2624                    SCROLL_INDICATOR_START,
2625                    SCROLL_INDICATOR_END,
2626            })
2627    public @interface ScrollIndicators {}
2628
2629    /**
2630     * Scroll indicator direction for the top edge of the view.
2631     *
2632     * @see #setScrollIndicators(int)
2633     * @see #setScrollIndicators(int, int)
2634     * @see #getScrollIndicators()
2635     */
2636    public static final int SCROLL_INDICATOR_TOP =
2637            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2638
2639    /**
2640     * Scroll indicator direction for the bottom edge of the view.
2641     *
2642     * @see #setScrollIndicators(int)
2643     * @see #setScrollIndicators(int, int)
2644     * @see #getScrollIndicators()
2645     */
2646    public static final int SCROLL_INDICATOR_BOTTOM =
2647            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2648
2649    /**
2650     * Scroll indicator direction for the left edge of the view.
2651     *
2652     * @see #setScrollIndicators(int)
2653     * @see #setScrollIndicators(int, int)
2654     * @see #getScrollIndicators()
2655     */
2656    public static final int SCROLL_INDICATOR_LEFT =
2657            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2658
2659    /**
2660     * Scroll indicator direction for the right edge of the view.
2661     *
2662     * @see #setScrollIndicators(int)
2663     * @see #setScrollIndicators(int, int)
2664     * @see #getScrollIndicators()
2665     */
2666    public static final int SCROLL_INDICATOR_RIGHT =
2667            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2668
2669    /**
2670     * Scroll indicator direction for the starting edge of the view.
2671     * <p>
2672     * Resolved according to the view's layout direction, see
2673     * {@link #getLayoutDirection()} for more information.
2674     *
2675     * @see #setScrollIndicators(int)
2676     * @see #setScrollIndicators(int, int)
2677     * @see #getScrollIndicators()
2678     */
2679    public static final int SCROLL_INDICATOR_START =
2680            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2681
2682    /**
2683     * Scroll indicator direction for the ending edge of the view.
2684     * <p>
2685     * Resolved according to the view's layout direction, see
2686     * {@link #getLayoutDirection()} for more information.
2687     *
2688     * @see #setScrollIndicators(int)
2689     * @see #setScrollIndicators(int, int)
2690     * @see #getScrollIndicators()
2691     */
2692    public static final int SCROLL_INDICATOR_END =
2693            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2694
2695    /**
2696     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2697     * into this view.<p>
2698     */
2699    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2700
2701    /**
2702     * Flag indicating that the view is a root of a keyboard navigation cluster.
2703     *
2704     * @see #isKeyboardNavigationCluster()
2705     * @see #setKeyboardNavigationCluster(boolean)
2706     */
2707    private static final int PFLAG3_CLUSTER = 0x8000;
2708
2709    /**
2710     * Indicates that the user is currently touching the screen.
2711     * Currently used for the tooltip positioning only.
2712     */
2713    private static final int PFLAG3_FINGER_DOWN = 0x20000;
2714
2715    /**
2716     * Flag indicating that this view is the default-focus view.
2717     *
2718     * @see #isFocusedByDefault()
2719     * @see #setFocusedByDefault(boolean)
2720     */
2721    private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
2722
2723    /**
2724     * Whether this view has rendered elements that overlap (see {@link
2725     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2726     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2727     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2728     * determined by whatever {@link #hasOverlappingRendering()} returns.
2729     */
2730    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2731
2732    /**
2733     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2734     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2735     */
2736    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2737
2738    /**
2739     * Flag indicating that the view is temporarily detached from the parent view.
2740     *
2741     * @see #onStartTemporaryDetach()
2742     * @see #onFinishTemporaryDetach()
2743     */
2744    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2745
2746    /**
2747     * Flag indicating that the view does not wish to be revealed within its parent
2748     * hierarchy when it gains focus. Expressed in the negative since the historical
2749     * default behavior is to reveal on focus; this flag suppresses that behavior.
2750     *
2751     * @see #setRevealOnFocusHint(boolean)
2752     * @see #getRevealOnFocusHint()
2753     */
2754    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
2755
2756    /* End of masks for mPrivateFlags3 */
2757
2758    /**
2759     * Always allow a user to over-scroll this view, provided it is a
2760     * view that can scroll.
2761     *
2762     * @see #getOverScrollMode()
2763     * @see #setOverScrollMode(int)
2764     */
2765    public static final int OVER_SCROLL_ALWAYS = 0;
2766
2767    /**
2768     * Allow a user to over-scroll this view only if the content is large
2769     * enough to meaningfully scroll, provided it is a view that can scroll.
2770     *
2771     * @see #getOverScrollMode()
2772     * @see #setOverScrollMode(int)
2773     */
2774    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2775
2776    /**
2777     * Never allow a user to over-scroll this view.
2778     *
2779     * @see #getOverScrollMode()
2780     * @see #setOverScrollMode(int)
2781     */
2782    public static final int OVER_SCROLL_NEVER = 2;
2783
2784    /**
2785     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2786     * requested the system UI (status bar) to be visible (the default).
2787     *
2788     * @see #setSystemUiVisibility(int)
2789     */
2790    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2791
2792    /**
2793     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2794     * system UI to enter an unobtrusive "low profile" mode.
2795     *
2796     * <p>This is for use in games, book readers, video players, or any other
2797     * "immersive" application where the usual system chrome is deemed too distracting.
2798     *
2799     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2800     *
2801     * @see #setSystemUiVisibility(int)
2802     */
2803    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2804
2805    /**
2806     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2807     * system navigation be temporarily hidden.
2808     *
2809     * <p>This is an even less obtrusive state than that called for by
2810     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2811     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2812     * those to disappear. This is useful (in conjunction with the
2813     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2814     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2815     * window flags) for displaying content using every last pixel on the display.
2816     *
2817     * <p>There is a limitation: because navigation controls are so important, the least user
2818     * interaction will cause them to reappear immediately.  When this happens, both
2819     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2820     * so that both elements reappear at the same time.
2821     *
2822     * @see #setSystemUiVisibility(int)
2823     */
2824    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2825
2826    /**
2827     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2828     * into the normal fullscreen mode so that its content can take over the screen
2829     * while still allowing the user to interact with the application.
2830     *
2831     * <p>This has the same visual effect as
2832     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2833     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2834     * meaning that non-critical screen decorations (such as the status bar) will be
2835     * hidden while the user is in the View's window, focusing the experience on
2836     * that content.  Unlike the window flag, if you are using ActionBar in
2837     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2838     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2839     * hide the action bar.
2840     *
2841     * <p>This approach to going fullscreen is best used over the window flag when
2842     * it is a transient state -- that is, the application does this at certain
2843     * points in its user interaction where it wants to allow the user to focus
2844     * on content, but not as a continuous state.  For situations where the application
2845     * would like to simply stay full screen the entire time (such as a game that
2846     * wants to take over the screen), the
2847     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2848     * is usually a better approach.  The state set here will be removed by the system
2849     * in various situations (such as the user moving to another application) like
2850     * the other system UI states.
2851     *
2852     * <p>When using this flag, the application should provide some easy facility
2853     * for the user to go out of it.  A common example would be in an e-book
2854     * reader, where tapping on the screen brings back whatever screen and UI
2855     * decorations that had been hidden while the user was immersed in reading
2856     * the book.
2857     *
2858     * @see #setSystemUiVisibility(int)
2859     */
2860    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2861
2862    /**
2863     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2864     * flags, we would like a stable view of the content insets given to
2865     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2866     * will always represent the worst case that the application can expect
2867     * as a continuous state.  In the stock Android UI this is the space for
2868     * the system bar, nav bar, and status bar, but not more transient elements
2869     * such as an input method.
2870     *
2871     * The stable layout your UI sees is based on the system UI modes you can
2872     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2873     * then you will get a stable layout for changes of the
2874     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2875     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2876     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2877     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2878     * with a stable layout.  (Note that you should avoid using
2879     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2880     *
2881     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2882     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2883     * then a hidden status bar will be considered a "stable" state for purposes
2884     * here.  This allows your UI to continually hide the status bar, while still
2885     * using the system UI flags to hide the action bar while still retaining
2886     * a stable layout.  Note that changing the window fullscreen flag will never
2887     * provide a stable layout for a clean transition.
2888     *
2889     * <p>If you are using ActionBar in
2890     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2891     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2892     * insets it adds to those given to the application.
2893     */
2894    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2895
2896    /**
2897     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2898     * to be laid out as if it has requested
2899     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2900     * allows it to avoid artifacts when switching in and out of that mode, at
2901     * the expense that some of its user interface may be covered by screen
2902     * decorations when they are shown.  You can perform layout of your inner
2903     * UI elements to account for the navigation system UI through the
2904     * {@link #fitSystemWindows(Rect)} method.
2905     */
2906    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2907
2908    /**
2909     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2910     * to be laid out as if it has requested
2911     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2912     * allows it to avoid artifacts when switching in and out of that mode, at
2913     * the expense that some of its user interface may be covered by screen
2914     * decorations when they are shown.  You can perform layout of your inner
2915     * UI elements to account for non-fullscreen system UI through the
2916     * {@link #fitSystemWindows(Rect)} method.
2917     */
2918    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2919
2920    /**
2921     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2922     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2923     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2924     * user interaction.
2925     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2926     * has an effect when used in combination with that flag.</p>
2927     */
2928    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2929
2930    /**
2931     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2932     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2933     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2934     * experience while also hiding the system bars.  If this flag is not set,
2935     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2936     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2937     * if the user swipes from the top of the screen.
2938     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2939     * system gestures, such as swiping from the top of the screen.  These transient system bars
2940     * will overlay app’s content, may have some degree of transparency, and will automatically
2941     * hide after a short timeout.
2942     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2943     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2944     * with one or both of those flags.</p>
2945     */
2946    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2947
2948    /**
2949     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2950     * is compatible with light status bar backgrounds.
2951     *
2952     * <p>For this to take effect, the window must request
2953     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2954     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2955     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2956     *         FLAG_TRANSLUCENT_STATUS}.
2957     *
2958     * @see android.R.attr#windowLightStatusBar
2959     */
2960    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2961
2962    /**
2963     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
2964     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
2965     */
2966    private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
2967
2968    /**
2969     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
2970     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
2971     */
2972    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
2973
2974    /**
2975     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
2976     * that is compatible with light navigation bar backgrounds.
2977     *
2978     * <p>For this to take effect, the window must request
2979     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2980     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2981     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
2982     *         FLAG_TRANSLUCENT_NAVIGATION}.
2983     */
2984    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
2985
2986    /**
2987     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2988     */
2989    @Deprecated
2990    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2991
2992    /**
2993     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2994     */
2995    @Deprecated
2996    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2997
2998    /**
2999     * @hide
3000     *
3001     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3002     * out of the public fields to keep the undefined bits out of the developer's way.
3003     *
3004     * Flag to make the status bar not expandable.  Unless you also
3005     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3006     */
3007    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3008
3009    /**
3010     * @hide
3011     *
3012     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3013     * out of the public fields to keep the undefined bits out of the developer's way.
3014     *
3015     * Flag to hide notification icons and scrolling ticker text.
3016     */
3017    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3018
3019    /**
3020     * @hide
3021     *
3022     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3023     * out of the public fields to keep the undefined bits out of the developer's way.
3024     *
3025     * Flag to disable incoming notification alerts.  This will not block
3026     * icons, but it will block sound, vibrating and other visual or aural notifications.
3027     */
3028    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3029
3030    /**
3031     * @hide
3032     *
3033     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3034     * out of the public fields to keep the undefined bits out of the developer's way.
3035     *
3036     * Flag to hide only the scrolling ticker.  Note that
3037     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3038     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3039     */
3040    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3041
3042    /**
3043     * @hide
3044     *
3045     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3046     * out of the public fields to keep the undefined bits out of the developer's way.
3047     *
3048     * Flag to hide the center system info area.
3049     */
3050    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3051
3052    /**
3053     * @hide
3054     *
3055     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3056     * out of the public fields to keep the undefined bits out of the developer's way.
3057     *
3058     * Flag to hide only the home button.  Don't use this
3059     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3060     */
3061    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3062
3063    /**
3064     * @hide
3065     *
3066     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3067     * out of the public fields to keep the undefined bits out of the developer's way.
3068     *
3069     * Flag to hide only the back button. Don't use this
3070     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3071     */
3072    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3073
3074    /**
3075     * @hide
3076     *
3077     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3078     * out of the public fields to keep the undefined bits out of the developer's way.
3079     *
3080     * Flag to hide only the clock.  You might use this if your activity has
3081     * its own clock making the status bar's clock redundant.
3082     */
3083    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3084
3085    /**
3086     * @hide
3087     *
3088     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3089     * out of the public fields to keep the undefined bits out of the developer's way.
3090     *
3091     * Flag to hide only the recent apps button. Don't use this
3092     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3093     */
3094    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3095
3096    /**
3097     * @hide
3098     *
3099     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3100     * out of the public fields to keep the undefined bits out of the developer's way.
3101     *
3102     * Flag to disable the global search gesture. Don't use this
3103     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3104     */
3105    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3106
3107    /**
3108     * @hide
3109     *
3110     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3111     * out of the public fields to keep the undefined bits out of the developer's way.
3112     *
3113     * Flag to specify that the status bar is displayed in transient mode.
3114     */
3115    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3116
3117    /**
3118     * @hide
3119     *
3120     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3121     * out of the public fields to keep the undefined bits out of the developer's way.
3122     *
3123     * Flag to specify that the navigation bar is displayed in transient mode.
3124     */
3125    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3126
3127    /**
3128     * @hide
3129     *
3130     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3131     * out of the public fields to keep the undefined bits out of the developer's way.
3132     *
3133     * Flag to specify that the hidden status bar would like to be shown.
3134     */
3135    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3136
3137    /**
3138     * @hide
3139     *
3140     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3141     * out of the public fields to keep the undefined bits out of the developer's way.
3142     *
3143     * Flag to specify that the hidden navigation bar would like to be shown.
3144     */
3145    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3146
3147    /**
3148     * @hide
3149     *
3150     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3151     * out of the public fields to keep the undefined bits out of the developer's way.
3152     *
3153     * Flag to specify that the status bar is displayed in translucent mode.
3154     */
3155    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3156
3157    /**
3158     * @hide
3159     *
3160     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3161     * out of the public fields to keep the undefined bits out of the developer's way.
3162     *
3163     * Flag to specify that the navigation bar is displayed in translucent mode.
3164     */
3165    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3166
3167    /**
3168     * @hide
3169     *
3170     * Makes navigation bar transparent (but not the status bar).
3171     */
3172    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3173
3174    /**
3175     * @hide
3176     *
3177     * Makes status bar transparent (but not the navigation bar).
3178     */
3179    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3180
3181    /**
3182     * @hide
3183     *
3184     * Makes both status bar and navigation bar transparent.
3185     */
3186    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3187            | STATUS_BAR_TRANSPARENT;
3188
3189    /**
3190     * @hide
3191     */
3192    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3193
3194    /**
3195     * These are the system UI flags that can be cleared by events outside
3196     * of an application.  Currently this is just the ability to tap on the
3197     * screen while hiding the navigation bar to have it return.
3198     * @hide
3199     */
3200    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3201            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3202            | SYSTEM_UI_FLAG_FULLSCREEN;
3203
3204    /**
3205     * Flags that can impact the layout in relation to system UI.
3206     */
3207    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3208            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3209            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3210
3211    /** @hide */
3212    @IntDef(flag = true,
3213            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3214    @Retention(RetentionPolicy.SOURCE)
3215    public @interface FindViewFlags {}
3216
3217    /**
3218     * Find views that render the specified text.
3219     *
3220     * @see #findViewsWithText(ArrayList, CharSequence, int)
3221     */
3222    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3223
3224    /**
3225     * Find find views that contain the specified content description.
3226     *
3227     * @see #findViewsWithText(ArrayList, CharSequence, int)
3228     */
3229    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3230
3231    /**
3232     * Find views that contain {@link AccessibilityNodeProvider}. Such
3233     * a View is a root of virtual view hierarchy and may contain the searched
3234     * text. If this flag is set Views with providers are automatically
3235     * added and it is a responsibility of the client to call the APIs of
3236     * the provider to determine whether the virtual tree rooted at this View
3237     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3238     * representing the virtual views with this text.
3239     *
3240     * @see #findViewsWithText(ArrayList, CharSequence, int)
3241     *
3242     * @hide
3243     */
3244    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3245
3246    /**
3247     * The undefined cursor position.
3248     *
3249     * @hide
3250     */
3251    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3252
3253    /**
3254     * Indicates that the screen has changed state and is now off.
3255     *
3256     * @see #onScreenStateChanged(int)
3257     */
3258    public static final int SCREEN_STATE_OFF = 0x0;
3259
3260    /**
3261     * Indicates that the screen has changed state and is now on.
3262     *
3263     * @see #onScreenStateChanged(int)
3264     */
3265    public static final int SCREEN_STATE_ON = 0x1;
3266
3267    /**
3268     * Indicates no axis of view scrolling.
3269     */
3270    public static final int SCROLL_AXIS_NONE = 0;
3271
3272    /**
3273     * Indicates scrolling along the horizontal axis.
3274     */
3275    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3276
3277    /**
3278     * Indicates scrolling along the vertical axis.
3279     */
3280    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3281
3282    /**
3283     * Controls the over-scroll mode for this view.
3284     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3285     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3286     * and {@link #OVER_SCROLL_NEVER}.
3287     */
3288    private int mOverScrollMode;
3289
3290    /**
3291     * The parent this view is attached to.
3292     * {@hide}
3293     *
3294     * @see #getParent()
3295     */
3296    protected ViewParent mParent;
3297
3298    /**
3299     * {@hide}
3300     */
3301    AttachInfo mAttachInfo;
3302
3303    /**
3304     * {@hide}
3305     */
3306    @ViewDebug.ExportedProperty(flagMapping = {
3307        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3308                name = "FORCE_LAYOUT"),
3309        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3310                name = "LAYOUT_REQUIRED"),
3311        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3312            name = "DRAWING_CACHE_INVALID", outputIf = false),
3313        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3314        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3315        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3316        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3317    }, formatToHexString = true)
3318
3319    /* @hide */
3320    public int mPrivateFlags;
3321    int mPrivateFlags2;
3322    int mPrivateFlags3;
3323
3324    /**
3325     * This view's request for the visibility of the status bar.
3326     * @hide
3327     */
3328    @ViewDebug.ExportedProperty(flagMapping = {
3329        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3330                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3331                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3332        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3333                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3334                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3335        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3336                                equals = SYSTEM_UI_FLAG_VISIBLE,
3337                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3338    }, formatToHexString = true)
3339    int mSystemUiVisibility;
3340
3341    /**
3342     * Reference count for transient state.
3343     * @see #setHasTransientState(boolean)
3344     */
3345    int mTransientStateCount = 0;
3346
3347    /**
3348     * Count of how many windows this view has been attached to.
3349     */
3350    int mWindowAttachCount;
3351
3352    /**
3353     * The layout parameters associated with this view and used by the parent
3354     * {@link android.view.ViewGroup} to determine how this view should be
3355     * laid out.
3356     * {@hide}
3357     */
3358    protected ViewGroup.LayoutParams mLayoutParams;
3359
3360    /**
3361     * The view flags hold various views states.
3362     * {@hide}
3363     */
3364    @ViewDebug.ExportedProperty(formatToHexString = true)
3365    int mViewFlags;
3366
3367    static class TransformationInfo {
3368        /**
3369         * The transform matrix for the View. This transform is calculated internally
3370         * based on the translation, rotation, and scale properties.
3371         *
3372         * Do *not* use this variable directly; instead call getMatrix(), which will
3373         * load the value from the View's RenderNode.
3374         */
3375        private final Matrix mMatrix = new Matrix();
3376
3377        /**
3378         * The inverse transform matrix for the View. This transform is calculated
3379         * internally based on the translation, rotation, and scale properties.
3380         *
3381         * Do *not* use this variable directly; instead call getInverseMatrix(),
3382         * which will load the value from the View's RenderNode.
3383         */
3384        private Matrix mInverseMatrix;
3385
3386        /**
3387         * The opacity of the View. This is a value from 0 to 1, where 0 means
3388         * completely transparent and 1 means completely opaque.
3389         */
3390        @ViewDebug.ExportedProperty
3391        float mAlpha = 1f;
3392
3393        /**
3394         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3395         * property only used by transitions, which is composited with the other alpha
3396         * values to calculate the final visual alpha value.
3397         */
3398        float mTransitionAlpha = 1f;
3399    }
3400
3401    /** @hide */
3402    public TransformationInfo mTransformationInfo;
3403
3404    /**
3405     * Current clip bounds. to which all drawing of this view are constrained.
3406     */
3407    Rect mClipBounds = null;
3408
3409    private boolean mLastIsOpaque;
3410
3411    /**
3412     * The distance in pixels from the left edge of this view's parent
3413     * to the left edge of this view.
3414     * {@hide}
3415     */
3416    @ViewDebug.ExportedProperty(category = "layout")
3417    protected int mLeft;
3418    /**
3419     * The distance in pixels from the left edge of this view's parent
3420     * to the right edge of this view.
3421     * {@hide}
3422     */
3423    @ViewDebug.ExportedProperty(category = "layout")
3424    protected int mRight;
3425    /**
3426     * The distance in pixels from the top edge of this view's parent
3427     * to the top edge of this view.
3428     * {@hide}
3429     */
3430    @ViewDebug.ExportedProperty(category = "layout")
3431    protected int mTop;
3432    /**
3433     * The distance in pixels from the top edge of this view's parent
3434     * to the bottom edge of this view.
3435     * {@hide}
3436     */
3437    @ViewDebug.ExportedProperty(category = "layout")
3438    protected int mBottom;
3439
3440    /**
3441     * The offset, in pixels, by which the content of this view is scrolled
3442     * horizontally.
3443     * {@hide}
3444     */
3445    @ViewDebug.ExportedProperty(category = "scrolling")
3446    protected int mScrollX;
3447    /**
3448     * The offset, in pixels, by which the content of this view is scrolled
3449     * vertically.
3450     * {@hide}
3451     */
3452    @ViewDebug.ExportedProperty(category = "scrolling")
3453    protected int mScrollY;
3454
3455    /**
3456     * The left padding in pixels, that is the distance in pixels between the
3457     * left edge of this view and the left edge of its content.
3458     * {@hide}
3459     */
3460    @ViewDebug.ExportedProperty(category = "padding")
3461    protected int mPaddingLeft = 0;
3462    /**
3463     * The right padding in pixels, that is the distance in pixels between the
3464     * right edge of this view and the right edge of its content.
3465     * {@hide}
3466     */
3467    @ViewDebug.ExportedProperty(category = "padding")
3468    protected int mPaddingRight = 0;
3469    /**
3470     * The top padding in pixels, that is the distance in pixels between the
3471     * top edge of this view and the top edge of its content.
3472     * {@hide}
3473     */
3474    @ViewDebug.ExportedProperty(category = "padding")
3475    protected int mPaddingTop;
3476    /**
3477     * The bottom padding in pixels, that is the distance in pixels between the
3478     * bottom edge of this view and the bottom edge of its content.
3479     * {@hide}
3480     */
3481    @ViewDebug.ExportedProperty(category = "padding")
3482    protected int mPaddingBottom;
3483
3484    /**
3485     * The layout insets in pixels, that is the distance in pixels between the
3486     * visible edges of this view its bounds.
3487     */
3488    private Insets mLayoutInsets;
3489
3490    /**
3491     * Briefly describes the view and is primarily used for accessibility support.
3492     */
3493    private CharSequence mContentDescription;
3494
3495    /**
3496     * Specifies the id of a view for which this view serves as a label for
3497     * accessibility purposes.
3498     */
3499    private int mLabelForId = View.NO_ID;
3500
3501    /**
3502     * Predicate for matching labeled view id with its label for
3503     * accessibility purposes.
3504     */
3505    private MatchLabelForPredicate mMatchLabelForPredicate;
3506
3507    /**
3508     * Specifies a view before which this one is visited in accessibility traversal.
3509     */
3510    private int mAccessibilityTraversalBeforeId = NO_ID;
3511
3512    /**
3513     * Specifies a view after which this one is visited in accessibility traversal.
3514     */
3515    private int mAccessibilityTraversalAfterId = NO_ID;
3516
3517    /**
3518     * Predicate for matching a view by its id.
3519     */
3520    private MatchIdPredicate mMatchIdPredicate;
3521
3522    /**
3523     * Cache the paddingRight set by the user to append to the scrollbar's size.
3524     *
3525     * @hide
3526     */
3527    @ViewDebug.ExportedProperty(category = "padding")
3528    protected int mUserPaddingRight;
3529
3530    /**
3531     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3532     *
3533     * @hide
3534     */
3535    @ViewDebug.ExportedProperty(category = "padding")
3536    protected int mUserPaddingBottom;
3537
3538    /**
3539     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3540     *
3541     * @hide
3542     */
3543    @ViewDebug.ExportedProperty(category = "padding")
3544    protected int mUserPaddingLeft;
3545
3546    /**
3547     * Cache the paddingStart set by the user to append to the scrollbar's size.
3548     *
3549     */
3550    @ViewDebug.ExportedProperty(category = "padding")
3551    int mUserPaddingStart;
3552
3553    /**
3554     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3555     *
3556     */
3557    @ViewDebug.ExportedProperty(category = "padding")
3558    int mUserPaddingEnd;
3559
3560    /**
3561     * Cache initial left padding.
3562     *
3563     * @hide
3564     */
3565    int mUserPaddingLeftInitial;
3566
3567    /**
3568     * Cache initial right padding.
3569     *
3570     * @hide
3571     */
3572    int mUserPaddingRightInitial;
3573
3574    /**
3575     * Default undefined padding
3576     */
3577    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3578
3579    /**
3580     * Cache if a left padding has been defined
3581     */
3582    private boolean mLeftPaddingDefined = false;
3583
3584    /**
3585     * Cache if a right padding has been defined
3586     */
3587    private boolean mRightPaddingDefined = false;
3588
3589    /**
3590     * @hide
3591     */
3592    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3593    /**
3594     * @hide
3595     */
3596    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3597
3598    private LongSparseLongArray mMeasureCache;
3599
3600    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3601    private Drawable mBackground;
3602    private TintInfo mBackgroundTint;
3603
3604    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3605    private ForegroundInfo mForegroundInfo;
3606
3607    private Drawable mScrollIndicatorDrawable;
3608
3609    /**
3610     * RenderNode used for backgrounds.
3611     * <p>
3612     * When non-null and valid, this is expected to contain an up-to-date copy
3613     * of the background drawable. It is cleared on temporary detach, and reset
3614     * on cleanup.
3615     */
3616    private RenderNode mBackgroundRenderNode;
3617
3618    private int mBackgroundResource;
3619    private boolean mBackgroundSizeChanged;
3620
3621    private String mTransitionName;
3622
3623    static class TintInfo {
3624        ColorStateList mTintList;
3625        PorterDuff.Mode mTintMode;
3626        boolean mHasTintMode;
3627        boolean mHasTintList;
3628    }
3629
3630    private static class ForegroundInfo {
3631        private Drawable mDrawable;
3632        private TintInfo mTintInfo;
3633        private int mGravity = Gravity.FILL;
3634        private boolean mInsidePadding = true;
3635        private boolean mBoundsChanged = true;
3636        private final Rect mSelfBounds = new Rect();
3637        private final Rect mOverlayBounds = new Rect();
3638    }
3639
3640    static class ListenerInfo {
3641        /**
3642         * Listener used to dispatch focus change events.
3643         * This field should be made private, so it is hidden from the SDK.
3644         * {@hide}
3645         */
3646        protected OnFocusChangeListener mOnFocusChangeListener;
3647
3648        /**
3649         * Listeners for layout change events.
3650         */
3651        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3652
3653        protected OnScrollChangeListener mOnScrollChangeListener;
3654
3655        /**
3656         * Listeners for attach events.
3657         */
3658        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3659
3660        /**
3661         * Listener used to dispatch click events.
3662         * This field should be made private, so it is hidden from the SDK.
3663         * {@hide}
3664         */
3665        public OnClickListener mOnClickListener;
3666
3667        /**
3668         * Listener used to dispatch long click events.
3669         * This field should be made private, so it is hidden from the SDK.
3670         * {@hide}
3671         */
3672        protected OnLongClickListener mOnLongClickListener;
3673
3674        /**
3675         * Listener used to dispatch context click events. This field should be made private, so it
3676         * is hidden from the SDK.
3677         * {@hide}
3678         */
3679        protected OnContextClickListener mOnContextClickListener;
3680
3681        /**
3682         * Listener used to build the context menu.
3683         * This field should be made private, so it is hidden from the SDK.
3684         * {@hide}
3685         */
3686        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3687
3688        private OnKeyListener mOnKeyListener;
3689
3690        private OnTouchListener mOnTouchListener;
3691
3692        private OnHoverListener mOnHoverListener;
3693
3694        private OnGenericMotionListener mOnGenericMotionListener;
3695
3696        private OnDragListener mOnDragListener;
3697
3698        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3699
3700        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3701    }
3702
3703    ListenerInfo mListenerInfo;
3704
3705    private static class TooltipInfo {
3706        /**
3707         * Text to be displayed in a tooltip popup.
3708         */
3709        @Nullable
3710        CharSequence mTooltipText;
3711
3712        /**
3713         * View-relative position of the tooltip anchor point.
3714         */
3715        int mAnchorX;
3716        int mAnchorY;
3717
3718        /**
3719         * The tooltip popup.
3720         */
3721        @Nullable
3722        TooltipPopup mTooltipPopup;
3723
3724        /**
3725         * Set to true if the tooltip was shown as a result of a long click.
3726         */
3727        boolean mTooltipFromLongClick;
3728
3729        /**
3730         * Keep these Runnables so that they can be used to reschedule.
3731         */
3732        Runnable mShowTooltipRunnable;
3733        Runnable mHideTooltipRunnable;
3734    }
3735
3736    TooltipInfo mTooltipInfo;
3737
3738    // Temporary values used to hold (x,y) coordinates when delegating from the
3739    // two-arg performLongClick() method to the legacy no-arg version.
3740    private float mLongClickX = Float.NaN;
3741    private float mLongClickY = Float.NaN;
3742
3743    /**
3744     * The application environment this view lives in.
3745     * This field should be made private, so it is hidden from the SDK.
3746     * {@hide}
3747     */
3748    @ViewDebug.ExportedProperty(deepExport = true)
3749    protected Context mContext;
3750
3751    private final Resources mResources;
3752
3753    private ScrollabilityCache mScrollCache;
3754
3755    private int[] mDrawableState = null;
3756
3757    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3758
3759    /**
3760     * Animator that automatically runs based on state changes.
3761     */
3762    private StateListAnimator mStateListAnimator;
3763
3764    /**
3765     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3766     * the user may specify which view to go to next.
3767     */
3768    private int mNextFocusLeftId = View.NO_ID;
3769
3770    /**
3771     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3772     * the user may specify which view to go to next.
3773     */
3774    private int mNextFocusRightId = View.NO_ID;
3775
3776    /**
3777     * When this view has focus and the next focus is {@link #FOCUS_UP},
3778     * the user may specify which view to go to next.
3779     */
3780    private int mNextFocusUpId = View.NO_ID;
3781
3782    /**
3783     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3784     * the user may specify which view to go to next.
3785     */
3786    private int mNextFocusDownId = View.NO_ID;
3787
3788    /**
3789     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3790     * the user may specify which view to go to next.
3791     */
3792    int mNextFocusForwardId = View.NO_ID;
3793
3794    /**
3795     * User-specified next keyboard navigation cluster.
3796     */
3797    int mNextClusterForwardId = View.NO_ID;
3798
3799    private CheckForLongPress mPendingCheckForLongPress;
3800    private CheckForTap mPendingCheckForTap = null;
3801    private PerformClick mPerformClick;
3802    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3803
3804    private UnsetPressedState mUnsetPressedState;
3805
3806    /**
3807     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3808     * up event while a long press is invoked as soon as the long press duration is reached, so
3809     * a long press could be performed before the tap is checked, in which case the tap's action
3810     * should not be invoked.
3811     */
3812    private boolean mHasPerformedLongPress;
3813
3814    /**
3815     * Whether a context click button is currently pressed down. This is true when the stylus is
3816     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3817     * pressed. This is false once the button is released or if the stylus has been lifted.
3818     */
3819    private boolean mInContextButtonPress;
3820
3821    /**
3822     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3823     * true after a stylus button press has occured, when the next up event should not be recognized
3824     * as a tap.
3825     */
3826    private boolean mIgnoreNextUpEvent;
3827
3828    /**
3829     * The minimum height of the view. We'll try our best to have the height
3830     * of this view to at least this amount.
3831     */
3832    @ViewDebug.ExportedProperty(category = "measurement")
3833    private int mMinHeight;
3834
3835    /**
3836     * The minimum width of the view. We'll try our best to have the width
3837     * of this view to at least this amount.
3838     */
3839    @ViewDebug.ExportedProperty(category = "measurement")
3840    private int mMinWidth;
3841
3842    /**
3843     * The delegate to handle touch events that are physically in this view
3844     * but should be handled by another view.
3845     */
3846    private TouchDelegate mTouchDelegate = null;
3847
3848    /**
3849     * Solid color to use as a background when creating the drawing cache. Enables
3850     * the cache to use 16 bit bitmaps instead of 32 bit.
3851     */
3852    private int mDrawingCacheBackgroundColor = 0;
3853
3854    /**
3855     * Special tree observer used when mAttachInfo is null.
3856     */
3857    private ViewTreeObserver mFloatingTreeObserver;
3858
3859    /**
3860     * Cache the touch slop from the context that created the view.
3861     */
3862    private int mTouchSlop;
3863
3864    /**
3865     * Object that handles automatic animation of view properties.
3866     */
3867    private ViewPropertyAnimator mAnimator = null;
3868
3869    /**
3870     * List of registered FrameMetricsObservers.
3871     */
3872    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3873
3874    /**
3875     * Flag indicating that a drag can cross window boundaries.  When
3876     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3877     * with this flag set, all visible applications with targetSdkVersion >=
3878     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3879     * in the drag operation and receive the dragged content.
3880     *
3881     * <p>If this is the only flag set, then the drag recipient will only have access to text data
3882     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3883     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
3884     */
3885    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3886
3887    /**
3888     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3889     * request read access to the content URI(s) contained in the {@link ClipData} object.
3890     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3891     */
3892    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3893
3894    /**
3895     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3896     * request write access to the content URI(s) contained in the {@link ClipData} object.
3897     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3898     */
3899    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3900
3901    /**
3902     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3903     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3904     * reboots until explicitly revoked with
3905     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3906     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3907     */
3908    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3909            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3910
3911    /**
3912     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3913     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3914     * match against the original granted URI.
3915     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3916     */
3917    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3918            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3919
3920    /**
3921     * Flag indicating that the drag shadow will be opaque.  When
3922     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3923     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3924     */
3925    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3926
3927    /**
3928     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3929     */
3930    private float mVerticalScrollFactor;
3931
3932    /**
3933     * Position of the vertical scroll bar.
3934     */
3935    private int mVerticalScrollbarPosition;
3936
3937    /**
3938     * Position the scroll bar at the default position as determined by the system.
3939     */
3940    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3941
3942    /**
3943     * Position the scroll bar along the left edge.
3944     */
3945    public static final int SCROLLBAR_POSITION_LEFT = 1;
3946
3947    /**
3948     * Position the scroll bar along the right edge.
3949     */
3950    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3951
3952    /**
3953     * Indicates that the view does not have a layer.
3954     *
3955     * @see #getLayerType()
3956     * @see #setLayerType(int, android.graphics.Paint)
3957     * @see #LAYER_TYPE_SOFTWARE
3958     * @see #LAYER_TYPE_HARDWARE
3959     */
3960    public static final int LAYER_TYPE_NONE = 0;
3961
3962    /**
3963     * <p>Indicates that the view has a software layer. A software layer is backed
3964     * by a bitmap and causes the view to be rendered using Android's software
3965     * rendering pipeline, even if hardware acceleration is enabled.</p>
3966     *
3967     * <p>Software layers have various usages:</p>
3968     * <p>When the application is not using hardware acceleration, a software layer
3969     * is useful to apply a specific color filter and/or blending mode and/or
3970     * translucency to a view and all its children.</p>
3971     * <p>When the application is using hardware acceleration, a software layer
3972     * is useful to render drawing primitives not supported by the hardware
3973     * accelerated pipeline. It can also be used to cache a complex view tree
3974     * into a texture and reduce the complexity of drawing operations. For instance,
3975     * when animating a complex view tree with a translation, a software layer can
3976     * be used to render the view tree only once.</p>
3977     * <p>Software layers should be avoided when the affected view tree updates
3978     * often. Every update will require to re-render the software layer, which can
3979     * potentially be slow (particularly when hardware acceleration is turned on
3980     * since the layer will have to be uploaded into a hardware texture after every
3981     * update.)</p>
3982     *
3983     * @see #getLayerType()
3984     * @see #setLayerType(int, android.graphics.Paint)
3985     * @see #LAYER_TYPE_NONE
3986     * @see #LAYER_TYPE_HARDWARE
3987     */
3988    public static final int LAYER_TYPE_SOFTWARE = 1;
3989
3990    /**
3991     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3992     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3993     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3994     * rendering pipeline, but only if hardware acceleration is turned on for the
3995     * view hierarchy. When hardware acceleration is turned off, hardware layers
3996     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3997     *
3998     * <p>A hardware layer is useful to apply a specific color filter and/or
3999     * blending mode and/or translucency to a view and all its children.</p>
4000     * <p>A hardware layer can be used to cache a complex view tree into a
4001     * texture and reduce the complexity of drawing operations. For instance,
4002     * when animating a complex view tree with a translation, a hardware layer can
4003     * be used to render the view tree only once.</p>
4004     * <p>A hardware layer can also be used to increase the rendering quality when
4005     * rotation transformations are applied on a view. It can also be used to
4006     * prevent potential clipping issues when applying 3D transforms on a view.</p>
4007     *
4008     * @see #getLayerType()
4009     * @see #setLayerType(int, android.graphics.Paint)
4010     * @see #LAYER_TYPE_NONE
4011     * @see #LAYER_TYPE_SOFTWARE
4012     */
4013    public static final int LAYER_TYPE_HARDWARE = 2;
4014
4015    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4016            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
4017            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
4018            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
4019    })
4020    int mLayerType = LAYER_TYPE_NONE;
4021    Paint mLayerPaint;
4022
4023
4024    /**
4025     * Set when a request was made to decide if views in an {@link android.app.Activity} can be
4026     * auto-filled by an {@link android.service.autofill.AutoFillService}.
4027     *
4028     * <p>Since this request is made without a explicit user consent, the resulting
4029     * {@link android.app.assist.AssistStructure} should not contain any PII
4030     * (Personally Identifiable Information).
4031     *
4032     * <p>Examples:
4033     * <ul>
4034     * <li>{@link android.widget.TextView} texts should only be included when they were set by
4035     * static resources.
4036     * <li>{@link android.webkit.WebView} virtual children should be restricted to a subset of
4037     * input fields and tags (like {@code id}).
4038     * </ul>
4039     */
4040    // TODO(b/33197203) (b/34078930): improve documentation: mention all cases, show examples, etc.
4041    // In particular, be more specific about webview restrictions
4042    public static final int AUTO_FILL_FLAG_TYPE_FILL = 0x1;
4043
4044    /**
4045     * Set when the user explicitly asked a {@link android.service.autofill.AutoFillService} to save
4046     * the value of the {@link View}s in an {@link android.app.Activity}.
4047     *
4048     * <p>The resulting {@link android.app.assist.AssistStructure} can contain any kind of PII
4049     * (Personally Identifiable Information). For example, the text of password fields should be
4050     * included since that's what's typically saved.
4051     */
4052    public static final int AUTO_FILL_FLAG_TYPE_SAVE = 0x2;
4053
4054    /**
4055     * Set to true when drawing cache is enabled and cannot be created.
4056     *
4057     * @hide
4058     */
4059    public boolean mCachingFailed;
4060    private Bitmap mDrawingCache;
4061    private Bitmap mUnscaledDrawingCache;
4062
4063    /**
4064     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4065     * <p>
4066     * When non-null and valid, this is expected to contain an up-to-date copy
4067     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4068     * cleanup.
4069     */
4070    final RenderNode mRenderNode;
4071
4072    /**
4073     * Set to true when the view is sending hover accessibility events because it
4074     * is the innermost hovered view.
4075     */
4076    private boolean mSendingHoverAccessibilityEvents;
4077
4078    /**
4079     * Delegate for injecting accessibility functionality.
4080     */
4081    AccessibilityDelegate mAccessibilityDelegate;
4082
4083    /**
4084     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4085     * and add/remove objects to/from the overlay directly through the Overlay methods.
4086     */
4087    ViewOverlay mOverlay;
4088
4089    /**
4090     * The currently active parent view for receiving delegated nested scrolling events.
4091     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4092     * by {@link #stopNestedScroll()} at the same point where we clear
4093     * requestDisallowInterceptTouchEvent.
4094     */
4095    private ViewParent mNestedScrollingParent;
4096
4097    /**
4098     * Consistency verifier for debugging purposes.
4099     * @hide
4100     */
4101    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4102            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4103                    new InputEventConsistencyVerifier(this, 0) : null;
4104
4105    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4106
4107    private int[] mTempNestedScrollConsumed;
4108
4109    /**
4110     * An overlay is going to draw this View instead of being drawn as part of this
4111     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4112     * when this view is invalidated.
4113     */
4114    GhostView mGhostView;
4115
4116    /**
4117     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4118     * @hide
4119     */
4120    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4121    public String[] mAttributes;
4122
4123    /**
4124     * Maps a Resource id to its name.
4125     */
4126    private static SparseArray<String> mAttributeMap;
4127
4128    /**
4129     * Queue of pending runnables. Used to postpone calls to post() until this
4130     * view is attached and has a handler.
4131     */
4132    private HandlerActionQueue mRunQueue;
4133
4134    /**
4135     * The pointer icon when the mouse hovers on this view. The default is null.
4136     */
4137    private PointerIcon mPointerIcon;
4138
4139    /**
4140     * @hide
4141     */
4142    String mStartActivityRequestWho;
4143
4144    @Nullable
4145    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4146
4147    /**
4148     * Simple constructor to use when creating a view from code.
4149     *
4150     * @param context The Context the view is running in, through which it can
4151     *        access the current theme, resources, etc.
4152     */
4153    public View(Context context) {
4154        mContext = context;
4155        mResources = context != null ? context.getResources() : null;
4156        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO;
4157        // Set some flags defaults
4158        mPrivateFlags2 =
4159                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4160                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4161                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4162                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4163                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4164                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4165        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4166        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4167        mUserPaddingStart = UNDEFINED_PADDING;
4168        mUserPaddingEnd = UNDEFINED_PADDING;
4169        mRenderNode = RenderNode.create(getClass().getName(), this);
4170
4171        if (!sCompatibilityDone && context != null) {
4172            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4173
4174            // Older apps may need this compatibility hack for measurement.
4175            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4176
4177            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4178            // of whether a layout was requested on that View.
4179            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4180
4181            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4182
4183            // In M and newer, our widgets can pass a "hint" value in the size
4184            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4185            // know what the expected parent size is going to be, so e.g. list items can size
4186            // themselves at 1/3 the size of their container. It breaks older apps though,
4187            // specifically apps that use some popular open source libraries.
4188            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4189
4190            // Old versions of the platform would give different results from
4191            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4192            // modes, so we always need to run an additional EXACTLY pass.
4193            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4194
4195            // Prior to N, layout params could change without requiring a
4196            // subsequent call to setLayoutParams() and they would usually
4197            // work. Partial layout breaks this assumption.
4198            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4199
4200            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4201            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4202            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4203
4204            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4205            // in apps so we target check it to avoid breaking existing apps.
4206            sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N;
4207
4208            sCascadedDragDrop = targetSdkVersion < N;
4209
4210            sCompatibilityDone = true;
4211        }
4212    }
4213
4214    /**
4215     * Constructor that is called when inflating a view from XML. This is called
4216     * when a view is being constructed from an XML file, supplying attributes
4217     * that were specified in the XML file. This version uses a default style of
4218     * 0, so the only attribute values applied are those in the Context's Theme
4219     * and the given AttributeSet.
4220     *
4221     * <p>
4222     * The method onFinishInflate() will be called after all children have been
4223     * added.
4224     *
4225     * @param context The Context the view is running in, through which it can
4226     *        access the current theme, resources, etc.
4227     * @param attrs The attributes of the XML tag that is inflating the view.
4228     * @see #View(Context, AttributeSet, int)
4229     */
4230    public View(Context context, @Nullable AttributeSet attrs) {
4231        this(context, attrs, 0);
4232    }
4233
4234    /**
4235     * Perform inflation from XML and apply a class-specific base style from a
4236     * theme attribute. This constructor of View allows subclasses to use their
4237     * own base style when they are inflating. For example, a Button class's
4238     * constructor would call this version of the super class constructor and
4239     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4240     * allows the theme's button style to modify all of the base view attributes
4241     * (in particular its background) as well as the Button class's attributes.
4242     *
4243     * @param context The Context the view is running in, through which it can
4244     *        access the current theme, resources, etc.
4245     * @param attrs The attributes of the XML tag that is inflating the view.
4246     * @param defStyleAttr An attribute in the current theme that contains a
4247     *        reference to a style resource that supplies default values for
4248     *        the view. Can be 0 to not look for defaults.
4249     * @see #View(Context, AttributeSet)
4250     */
4251    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4252        this(context, attrs, defStyleAttr, 0);
4253    }
4254
4255    /**
4256     * Perform inflation from XML and apply a class-specific base style from a
4257     * theme attribute or style resource. This constructor of View allows
4258     * subclasses to use their own base style when they are inflating.
4259     * <p>
4260     * When determining the final value of a particular attribute, there are
4261     * four inputs that come into play:
4262     * <ol>
4263     * <li>Any attribute values in the given AttributeSet.
4264     * <li>The style resource specified in the AttributeSet (named "style").
4265     * <li>The default style specified by <var>defStyleAttr</var>.
4266     * <li>The default style specified by <var>defStyleRes</var>.
4267     * <li>The base values in this theme.
4268     * </ol>
4269     * <p>
4270     * Each of these inputs is considered in-order, with the first listed taking
4271     * precedence over the following ones. In other words, if in the
4272     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4273     * , then the button's text will <em>always</em> be black, regardless of
4274     * what is specified in any of the styles.
4275     *
4276     * @param context The Context the view is running in, through which it can
4277     *        access the current theme, resources, etc.
4278     * @param attrs The attributes of the XML tag that is inflating the view.
4279     * @param defStyleAttr An attribute in the current theme that contains a
4280     *        reference to a style resource that supplies default values for
4281     *        the view. Can be 0 to not look for defaults.
4282     * @param defStyleRes A resource identifier of a style resource that
4283     *        supplies default values for the view, used only if
4284     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4285     *        to not look for defaults.
4286     * @see #View(Context, AttributeSet, int)
4287     */
4288    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4289        this(context);
4290
4291        final TypedArray a = context.obtainStyledAttributes(
4292                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4293
4294        if (mDebugViewAttributes) {
4295            saveAttributeData(attrs, a);
4296        }
4297
4298        Drawable background = null;
4299
4300        int leftPadding = -1;
4301        int topPadding = -1;
4302        int rightPadding = -1;
4303        int bottomPadding = -1;
4304        int startPadding = UNDEFINED_PADDING;
4305        int endPadding = UNDEFINED_PADDING;
4306
4307        int padding = -1;
4308        int paddingHorizontal = -1;
4309        int paddingVertical = -1;
4310
4311        int viewFlagValues = 0;
4312        int viewFlagMasks = 0;
4313
4314        boolean setScrollContainer = false;
4315
4316        int x = 0;
4317        int y = 0;
4318
4319        float tx = 0;
4320        float ty = 0;
4321        float tz = 0;
4322        float elevation = 0;
4323        float rotation = 0;
4324        float rotationX = 0;
4325        float rotationY = 0;
4326        float sx = 1f;
4327        float sy = 1f;
4328        boolean transformSet = false;
4329
4330        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4331        int overScrollMode = mOverScrollMode;
4332        boolean initializeScrollbars = false;
4333        boolean initializeScrollIndicators = false;
4334
4335        boolean startPaddingDefined = false;
4336        boolean endPaddingDefined = false;
4337        boolean leftPaddingDefined = false;
4338        boolean rightPaddingDefined = false;
4339
4340        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4341
4342        // Set default values.
4343        viewFlagValues |= FOCUSABLE_AUTO;
4344        viewFlagMasks |= FOCUSABLE_AUTO;
4345
4346        final int N = a.getIndexCount();
4347        for (int i = 0; i < N; i++) {
4348            int attr = a.getIndex(i);
4349            switch (attr) {
4350                case com.android.internal.R.styleable.View_background:
4351                    background = a.getDrawable(attr);
4352                    break;
4353                case com.android.internal.R.styleable.View_padding:
4354                    padding = a.getDimensionPixelSize(attr, -1);
4355                    mUserPaddingLeftInitial = padding;
4356                    mUserPaddingRightInitial = padding;
4357                    leftPaddingDefined = true;
4358                    rightPaddingDefined = true;
4359                    break;
4360                case com.android.internal.R.styleable.View_paddingHorizontal:
4361                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
4362                    mUserPaddingLeftInitial = paddingHorizontal;
4363                    mUserPaddingRightInitial = paddingHorizontal;
4364                    leftPaddingDefined = true;
4365                    rightPaddingDefined = true;
4366                    break;
4367                case com.android.internal.R.styleable.View_paddingVertical:
4368                    paddingVertical = a.getDimensionPixelSize(attr, -1);
4369                    break;
4370                 case com.android.internal.R.styleable.View_paddingLeft:
4371                    leftPadding = a.getDimensionPixelSize(attr, -1);
4372                    mUserPaddingLeftInitial = leftPadding;
4373                    leftPaddingDefined = true;
4374                    break;
4375                case com.android.internal.R.styleable.View_paddingTop:
4376                    topPadding = a.getDimensionPixelSize(attr, -1);
4377                    break;
4378                case com.android.internal.R.styleable.View_paddingRight:
4379                    rightPadding = a.getDimensionPixelSize(attr, -1);
4380                    mUserPaddingRightInitial = rightPadding;
4381                    rightPaddingDefined = true;
4382                    break;
4383                case com.android.internal.R.styleable.View_paddingBottom:
4384                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4385                    break;
4386                case com.android.internal.R.styleable.View_paddingStart:
4387                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4388                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4389                    break;
4390                case com.android.internal.R.styleable.View_paddingEnd:
4391                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4392                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4393                    break;
4394                case com.android.internal.R.styleable.View_scrollX:
4395                    x = a.getDimensionPixelOffset(attr, 0);
4396                    break;
4397                case com.android.internal.R.styleable.View_scrollY:
4398                    y = a.getDimensionPixelOffset(attr, 0);
4399                    break;
4400                case com.android.internal.R.styleable.View_alpha:
4401                    setAlpha(a.getFloat(attr, 1f));
4402                    break;
4403                case com.android.internal.R.styleable.View_transformPivotX:
4404                    setPivotX(a.getDimension(attr, 0));
4405                    break;
4406                case com.android.internal.R.styleable.View_transformPivotY:
4407                    setPivotY(a.getDimension(attr, 0));
4408                    break;
4409                case com.android.internal.R.styleable.View_translationX:
4410                    tx = a.getDimension(attr, 0);
4411                    transformSet = true;
4412                    break;
4413                case com.android.internal.R.styleable.View_translationY:
4414                    ty = a.getDimension(attr, 0);
4415                    transformSet = true;
4416                    break;
4417                case com.android.internal.R.styleable.View_translationZ:
4418                    tz = a.getDimension(attr, 0);
4419                    transformSet = true;
4420                    break;
4421                case com.android.internal.R.styleable.View_elevation:
4422                    elevation = a.getDimension(attr, 0);
4423                    transformSet = true;
4424                    break;
4425                case com.android.internal.R.styleable.View_rotation:
4426                    rotation = a.getFloat(attr, 0);
4427                    transformSet = true;
4428                    break;
4429                case com.android.internal.R.styleable.View_rotationX:
4430                    rotationX = a.getFloat(attr, 0);
4431                    transformSet = true;
4432                    break;
4433                case com.android.internal.R.styleable.View_rotationY:
4434                    rotationY = a.getFloat(attr, 0);
4435                    transformSet = true;
4436                    break;
4437                case com.android.internal.R.styleable.View_scaleX:
4438                    sx = a.getFloat(attr, 1f);
4439                    transformSet = true;
4440                    break;
4441                case com.android.internal.R.styleable.View_scaleY:
4442                    sy = a.getFloat(attr, 1f);
4443                    transformSet = true;
4444                    break;
4445                case com.android.internal.R.styleable.View_id:
4446                    mID = a.getResourceId(attr, NO_ID);
4447                    break;
4448                case com.android.internal.R.styleable.View_tag:
4449                    mTag = a.getText(attr);
4450                    break;
4451                case com.android.internal.R.styleable.View_fitsSystemWindows:
4452                    if (a.getBoolean(attr, false)) {
4453                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4454                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4455                    }
4456                    break;
4457                case com.android.internal.R.styleable.View_focusable:
4458                    viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
4459                    if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
4460                        viewFlagMasks |= FOCUSABLE_MASK;
4461                    }
4462                    break;
4463                case com.android.internal.R.styleable.View_focusableInTouchMode:
4464                    if (a.getBoolean(attr, false)) {
4465                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4466                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4467                    }
4468                    break;
4469                case com.android.internal.R.styleable.View_clickable:
4470                    if (a.getBoolean(attr, false)) {
4471                        viewFlagValues |= CLICKABLE;
4472                        viewFlagMasks |= CLICKABLE;
4473                    }
4474                    break;
4475                case com.android.internal.R.styleable.View_longClickable:
4476                    if (a.getBoolean(attr, false)) {
4477                        viewFlagValues |= LONG_CLICKABLE;
4478                        viewFlagMasks |= LONG_CLICKABLE;
4479                    }
4480                    break;
4481                case com.android.internal.R.styleable.View_contextClickable:
4482                    if (a.getBoolean(attr, false)) {
4483                        viewFlagValues |= CONTEXT_CLICKABLE;
4484                        viewFlagMasks |= CONTEXT_CLICKABLE;
4485                    }
4486                    break;
4487                case com.android.internal.R.styleable.View_saveEnabled:
4488                    if (!a.getBoolean(attr, true)) {
4489                        viewFlagValues |= SAVE_DISABLED;
4490                        viewFlagMasks |= SAVE_DISABLED_MASK;
4491                    }
4492                    break;
4493                case com.android.internal.R.styleable.View_duplicateParentState:
4494                    if (a.getBoolean(attr, false)) {
4495                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4496                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4497                    }
4498                    break;
4499                case com.android.internal.R.styleable.View_visibility:
4500                    final int visibility = a.getInt(attr, 0);
4501                    if (visibility != 0) {
4502                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4503                        viewFlagMasks |= VISIBILITY_MASK;
4504                    }
4505                    break;
4506                case com.android.internal.R.styleable.View_layoutDirection:
4507                    // Clear any layout direction flags (included resolved bits) already set
4508                    mPrivateFlags2 &=
4509                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4510                    // Set the layout direction flags depending on the value of the attribute
4511                    final int layoutDirection = a.getInt(attr, -1);
4512                    final int value = (layoutDirection != -1) ?
4513                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4514                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4515                    break;
4516                case com.android.internal.R.styleable.View_drawingCacheQuality:
4517                    final int cacheQuality = a.getInt(attr, 0);
4518                    if (cacheQuality != 0) {
4519                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4520                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4521                    }
4522                    break;
4523                case com.android.internal.R.styleable.View_contentDescription:
4524                    setContentDescription(a.getString(attr));
4525                    break;
4526                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4527                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4528                    break;
4529                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4530                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4531                    break;
4532                case com.android.internal.R.styleable.View_labelFor:
4533                    setLabelFor(a.getResourceId(attr, NO_ID));
4534                    break;
4535                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4536                    if (!a.getBoolean(attr, true)) {
4537                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4538                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4539                    }
4540                    break;
4541                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4542                    if (!a.getBoolean(attr, true)) {
4543                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4544                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4545                    }
4546                    break;
4547                case R.styleable.View_scrollbars:
4548                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4549                    if (scrollbars != SCROLLBARS_NONE) {
4550                        viewFlagValues |= scrollbars;
4551                        viewFlagMasks |= SCROLLBARS_MASK;
4552                        initializeScrollbars = true;
4553                    }
4554                    break;
4555                //noinspection deprecation
4556                case R.styleable.View_fadingEdge:
4557                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4558                        // Ignore the attribute starting with ICS
4559                        break;
4560                    }
4561                    // With builds < ICS, fall through and apply fading edges
4562                case R.styleable.View_requiresFadingEdge:
4563                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4564                    if (fadingEdge != FADING_EDGE_NONE) {
4565                        viewFlagValues |= fadingEdge;
4566                        viewFlagMasks |= FADING_EDGE_MASK;
4567                        initializeFadingEdgeInternal(a);
4568                    }
4569                    break;
4570                case R.styleable.View_scrollbarStyle:
4571                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4572                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4573                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4574                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4575                    }
4576                    break;
4577                case R.styleable.View_isScrollContainer:
4578                    setScrollContainer = true;
4579                    if (a.getBoolean(attr, false)) {
4580                        setScrollContainer(true);
4581                    }
4582                    break;
4583                case com.android.internal.R.styleable.View_keepScreenOn:
4584                    if (a.getBoolean(attr, false)) {
4585                        viewFlagValues |= KEEP_SCREEN_ON;
4586                        viewFlagMasks |= KEEP_SCREEN_ON;
4587                    }
4588                    break;
4589                case R.styleable.View_filterTouchesWhenObscured:
4590                    if (a.getBoolean(attr, false)) {
4591                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4592                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4593                    }
4594                    break;
4595                case R.styleable.View_nextFocusLeft:
4596                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4597                    break;
4598                case R.styleable.View_nextFocusRight:
4599                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4600                    break;
4601                case R.styleable.View_nextFocusUp:
4602                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4603                    break;
4604                case R.styleable.View_nextFocusDown:
4605                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4606                    break;
4607                case R.styleable.View_nextFocusForward:
4608                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4609                    break;
4610                case R.styleable.View_nextClusterForward:
4611                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
4612                    break;
4613                case R.styleable.View_minWidth:
4614                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4615                    break;
4616                case R.styleable.View_minHeight:
4617                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4618                    break;
4619                case R.styleable.View_onClick:
4620                    if (context.isRestricted()) {
4621                        throw new IllegalStateException("The android:onClick attribute cannot "
4622                                + "be used within a restricted context");
4623                    }
4624
4625                    final String handlerName = a.getString(attr);
4626                    if (handlerName != null) {
4627                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4628                    }
4629                    break;
4630                case R.styleable.View_overScrollMode:
4631                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4632                    break;
4633                case R.styleable.View_verticalScrollbarPosition:
4634                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4635                    break;
4636                case R.styleable.View_layerType:
4637                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4638                    break;
4639                case R.styleable.View_textDirection:
4640                    // Clear any text direction flag already set
4641                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4642                    // Set the text direction flags depending on the value of the attribute
4643                    final int textDirection = a.getInt(attr, -1);
4644                    if (textDirection != -1) {
4645                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4646                    }
4647                    break;
4648                case R.styleable.View_textAlignment:
4649                    // Clear any text alignment flag already set
4650                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4651                    // Set the text alignment flag depending on the value of the attribute
4652                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4653                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4654                    break;
4655                case R.styleable.View_importantForAccessibility:
4656                    setImportantForAccessibility(a.getInt(attr,
4657                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4658                    break;
4659                case R.styleable.View_accessibilityLiveRegion:
4660                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4661                    break;
4662                case R.styleable.View_transitionName:
4663                    setTransitionName(a.getString(attr));
4664                    break;
4665                case R.styleable.View_nestedScrollingEnabled:
4666                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4667                    break;
4668                case R.styleable.View_stateListAnimator:
4669                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4670                            a.getResourceId(attr, 0)));
4671                    break;
4672                case R.styleable.View_backgroundTint:
4673                    // This will get applied later during setBackground().
4674                    if (mBackgroundTint == null) {
4675                        mBackgroundTint = new TintInfo();
4676                    }
4677                    mBackgroundTint.mTintList = a.getColorStateList(
4678                            R.styleable.View_backgroundTint);
4679                    mBackgroundTint.mHasTintList = true;
4680                    break;
4681                case R.styleable.View_backgroundTintMode:
4682                    // This will get applied later during setBackground().
4683                    if (mBackgroundTint == null) {
4684                        mBackgroundTint = new TintInfo();
4685                    }
4686                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4687                            R.styleable.View_backgroundTintMode, -1), null);
4688                    mBackgroundTint.mHasTintMode = true;
4689                    break;
4690                case R.styleable.View_outlineProvider:
4691                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4692                            PROVIDER_BACKGROUND));
4693                    break;
4694                case R.styleable.View_foreground:
4695                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4696                        setForeground(a.getDrawable(attr));
4697                    }
4698                    break;
4699                case R.styleable.View_foregroundGravity:
4700                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4701                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4702                    }
4703                    break;
4704                case R.styleable.View_foregroundTintMode:
4705                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4706                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4707                    }
4708                    break;
4709                case R.styleable.View_foregroundTint:
4710                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4711                        setForegroundTintList(a.getColorStateList(attr));
4712                    }
4713                    break;
4714                case R.styleable.View_foregroundInsidePadding:
4715                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4716                        if (mForegroundInfo == null) {
4717                            mForegroundInfo = new ForegroundInfo();
4718                        }
4719                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4720                                mForegroundInfo.mInsidePadding);
4721                    }
4722                    break;
4723                case R.styleable.View_scrollIndicators:
4724                    final int scrollIndicators =
4725                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4726                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4727                    if (scrollIndicators != 0) {
4728                        mPrivateFlags3 |= scrollIndicators;
4729                        initializeScrollIndicators = true;
4730                    }
4731                    break;
4732                case R.styleable.View_pointerIcon:
4733                    final int resourceId = a.getResourceId(attr, 0);
4734                    if (resourceId != 0) {
4735                        setPointerIcon(PointerIcon.load(
4736                                context.getResources(), resourceId));
4737                    } else {
4738                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4739                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4740                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4741                        }
4742                    }
4743                    break;
4744                case R.styleable.View_forceHasOverlappingRendering:
4745                    if (a.peekValue(attr) != null) {
4746                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4747                    }
4748                    break;
4749                case R.styleable.View_tooltipText:
4750                    setTooltipText(a.getText(attr));
4751                    break;
4752                case R.styleable.View_keyboardNavigationCluster:
4753                    if (a.peekValue(attr) != null) {
4754                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
4755                    }
4756                    break;
4757                case R.styleable.View_focusedByDefault:
4758                    if (a.peekValue(attr) != null) {
4759                        setFocusedByDefault(a.getBoolean(attr, true));
4760                    }
4761                    break;
4762            }
4763        }
4764
4765        setOverScrollMode(overScrollMode);
4766
4767        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4768        // the resolved layout direction). Those cached values will be used later during padding
4769        // resolution.
4770        mUserPaddingStart = startPadding;
4771        mUserPaddingEnd = endPadding;
4772
4773        if (background != null) {
4774            setBackground(background);
4775        }
4776
4777        // setBackground above will record that padding is currently provided by the background.
4778        // If we have padding specified via xml, record that here instead and use it.
4779        mLeftPaddingDefined = leftPaddingDefined;
4780        mRightPaddingDefined = rightPaddingDefined;
4781
4782        if (padding >= 0) {
4783            leftPadding = padding;
4784            topPadding = padding;
4785            rightPadding = padding;
4786            bottomPadding = padding;
4787            mUserPaddingLeftInitial = padding;
4788            mUserPaddingRightInitial = padding;
4789        } else {
4790            if (paddingHorizontal >= 0) {
4791                leftPadding = paddingHorizontal;
4792                rightPadding = paddingHorizontal;
4793                mUserPaddingLeftInitial = paddingHorizontal;
4794                mUserPaddingRightInitial = paddingHorizontal;
4795            }
4796            if (paddingVertical >= 0) {
4797                topPadding = paddingVertical;
4798                bottomPadding = paddingVertical;
4799            }
4800        }
4801
4802        if (isRtlCompatibilityMode()) {
4803            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4804            // left / right padding are used if defined (meaning here nothing to do). If they are not
4805            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4806            // start / end and resolve them as left / right (layout direction is not taken into account).
4807            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4808            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4809            // defined.
4810            if (!mLeftPaddingDefined && startPaddingDefined) {
4811                leftPadding = startPadding;
4812            }
4813            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4814            if (!mRightPaddingDefined && endPaddingDefined) {
4815                rightPadding = endPadding;
4816            }
4817            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4818        } else {
4819            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4820            // values defined. Otherwise, left /right values are used.
4821            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4822            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4823            // defined.
4824            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4825
4826            if (mLeftPaddingDefined && !hasRelativePadding) {
4827                mUserPaddingLeftInitial = leftPadding;
4828            }
4829            if (mRightPaddingDefined && !hasRelativePadding) {
4830                mUserPaddingRightInitial = rightPadding;
4831            }
4832        }
4833
4834        internalSetPadding(
4835                mUserPaddingLeftInitial,
4836                topPadding >= 0 ? topPadding : mPaddingTop,
4837                mUserPaddingRightInitial,
4838                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4839
4840        if (viewFlagMasks != 0) {
4841            setFlags(viewFlagValues, viewFlagMasks);
4842        }
4843
4844        if (initializeScrollbars) {
4845            initializeScrollbarsInternal(a);
4846        }
4847
4848        if (initializeScrollIndicators) {
4849            initializeScrollIndicatorsInternal();
4850        }
4851
4852        a.recycle();
4853
4854        // Needs to be called after mViewFlags is set
4855        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4856            recomputePadding();
4857        }
4858
4859        if (x != 0 || y != 0) {
4860            scrollTo(x, y);
4861        }
4862
4863        if (transformSet) {
4864            setTranslationX(tx);
4865            setTranslationY(ty);
4866            setTranslationZ(tz);
4867            setElevation(elevation);
4868            setRotation(rotation);
4869            setRotationX(rotationX);
4870            setRotationY(rotationY);
4871            setScaleX(sx);
4872            setScaleY(sy);
4873        }
4874
4875        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4876            setScrollContainer(true);
4877        }
4878
4879        computeOpaqueFlags();
4880    }
4881
4882    /**
4883     * An implementation of OnClickListener that attempts to lazily load a
4884     * named click handling method from a parent or ancestor context.
4885     */
4886    private static class DeclaredOnClickListener implements OnClickListener {
4887        private final View mHostView;
4888        private final String mMethodName;
4889
4890        private Method mResolvedMethod;
4891        private Context mResolvedContext;
4892
4893        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4894            mHostView = hostView;
4895            mMethodName = methodName;
4896        }
4897
4898        @Override
4899        public void onClick(@NonNull View v) {
4900            if (mResolvedMethod == null) {
4901                resolveMethod(mHostView.getContext(), mMethodName);
4902            }
4903
4904            try {
4905                mResolvedMethod.invoke(mResolvedContext, v);
4906            } catch (IllegalAccessException e) {
4907                throw new IllegalStateException(
4908                        "Could not execute non-public method for android:onClick", e);
4909            } catch (InvocationTargetException e) {
4910                throw new IllegalStateException(
4911                        "Could not execute method for android:onClick", e);
4912            }
4913        }
4914
4915        @NonNull
4916        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4917            while (context != null) {
4918                try {
4919                    if (!context.isRestricted()) {
4920                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4921                        if (method != null) {
4922                            mResolvedMethod = method;
4923                            mResolvedContext = context;
4924                            return;
4925                        }
4926                    }
4927                } catch (NoSuchMethodException e) {
4928                    // Failed to find method, keep searching up the hierarchy.
4929                }
4930
4931                if (context instanceof ContextWrapper) {
4932                    context = ((ContextWrapper) context).getBaseContext();
4933                } else {
4934                    // Can't search up the hierarchy, null out and fail.
4935                    context = null;
4936                }
4937            }
4938
4939            final int id = mHostView.getId();
4940            final String idText = id == NO_ID ? "" : " with id '"
4941                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4942            throw new IllegalStateException("Could not find method " + mMethodName
4943                    + "(View) in a parent or ancestor Context for android:onClick "
4944                    + "attribute defined on view " + mHostView.getClass() + idText);
4945        }
4946    }
4947
4948    /**
4949     * Non-public constructor for use in testing
4950     */
4951    View() {
4952        mResources = null;
4953        mRenderNode = RenderNode.create(getClass().getName(), this);
4954    }
4955
4956    final boolean debugDraw() {
4957        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
4958    }
4959
4960    private static SparseArray<String> getAttributeMap() {
4961        if (mAttributeMap == null) {
4962            mAttributeMap = new SparseArray<>();
4963        }
4964        return mAttributeMap;
4965    }
4966
4967    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4968        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4969        final int indexCount = t.getIndexCount();
4970        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4971
4972        int i = 0;
4973
4974        // Store raw XML attributes.
4975        for (int j = 0; j < attrsCount; ++j) {
4976            attributes[i] = attrs.getAttributeName(j);
4977            attributes[i + 1] = attrs.getAttributeValue(j);
4978            i += 2;
4979        }
4980
4981        // Store resolved styleable attributes.
4982        final Resources res = t.getResources();
4983        final SparseArray<String> attributeMap = getAttributeMap();
4984        for (int j = 0; j < indexCount; ++j) {
4985            final int index = t.getIndex(j);
4986            if (!t.hasValueOrEmpty(index)) {
4987                // Value is undefined. Skip it.
4988                continue;
4989            }
4990
4991            final int resourceId = t.getResourceId(index, 0);
4992            if (resourceId == 0) {
4993                // Value is not a reference. Skip it.
4994                continue;
4995            }
4996
4997            String resourceName = attributeMap.get(resourceId);
4998            if (resourceName == null) {
4999                try {
5000                    resourceName = res.getResourceName(resourceId);
5001                } catch (Resources.NotFoundException e) {
5002                    resourceName = "0x" + Integer.toHexString(resourceId);
5003                }
5004                attributeMap.put(resourceId, resourceName);
5005            }
5006
5007            attributes[i] = resourceName;
5008            attributes[i + 1] = t.getString(index);
5009            i += 2;
5010        }
5011
5012        // Trim to fit contents.
5013        final String[] trimmed = new String[i];
5014        System.arraycopy(attributes, 0, trimmed, 0, i);
5015        mAttributes = trimmed;
5016    }
5017
5018    public String toString() {
5019        StringBuilder out = new StringBuilder(128);
5020        out.append(getClass().getName());
5021        out.append('{');
5022        out.append(Integer.toHexString(System.identityHashCode(this)));
5023        out.append(' ');
5024        switch (mViewFlags&VISIBILITY_MASK) {
5025            case VISIBLE: out.append('V'); break;
5026            case INVISIBLE: out.append('I'); break;
5027            case GONE: out.append('G'); break;
5028            default: out.append('.'); break;
5029        }
5030        out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.');
5031        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
5032        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
5033        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
5034        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
5035        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
5036        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
5037        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
5038        out.append(' ');
5039        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
5040        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
5041        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
5042        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
5043            out.append('p');
5044        } else {
5045            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5046        }
5047        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5048        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5049        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5050        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5051        out.append(' ');
5052        out.append(mLeft);
5053        out.append(',');
5054        out.append(mTop);
5055        out.append('-');
5056        out.append(mRight);
5057        out.append(',');
5058        out.append(mBottom);
5059        final int id = getId();
5060        if (id != NO_ID) {
5061            out.append(" #");
5062            out.append(Integer.toHexString(id));
5063            final Resources r = mResources;
5064            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5065                try {
5066                    String pkgname;
5067                    switch (id&0xff000000) {
5068                        case 0x7f000000:
5069                            pkgname="app";
5070                            break;
5071                        case 0x01000000:
5072                            pkgname="android";
5073                            break;
5074                        default:
5075                            pkgname = r.getResourcePackageName(id);
5076                            break;
5077                    }
5078                    String typename = r.getResourceTypeName(id);
5079                    String entryname = r.getResourceEntryName(id);
5080                    out.append(" ");
5081                    out.append(pkgname);
5082                    out.append(":");
5083                    out.append(typename);
5084                    out.append("/");
5085                    out.append(entryname);
5086                } catch (Resources.NotFoundException e) {
5087                }
5088            }
5089        }
5090        out.append("}");
5091        return out.toString();
5092    }
5093
5094    /**
5095     * <p>
5096     * Initializes the fading edges from a given set of styled attributes. This
5097     * method should be called by subclasses that need fading edges and when an
5098     * instance of these subclasses is created programmatically rather than
5099     * being inflated from XML. This method is automatically called when the XML
5100     * is inflated.
5101     * </p>
5102     *
5103     * @param a the styled attributes set to initialize the fading edges from
5104     *
5105     * @removed
5106     */
5107    protected void initializeFadingEdge(TypedArray a) {
5108        // This method probably shouldn't have been included in the SDK to begin with.
5109        // It relies on 'a' having been initialized using an attribute filter array that is
5110        // not publicly available to the SDK. The old method has been renamed
5111        // to initializeFadingEdgeInternal and hidden for framework use only;
5112        // this one initializes using defaults to make it safe to call for apps.
5113
5114        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5115
5116        initializeFadingEdgeInternal(arr);
5117
5118        arr.recycle();
5119    }
5120
5121    /**
5122     * <p>
5123     * Initializes the fading edges from a given set of styled attributes. This
5124     * method should be called by subclasses that need fading edges and when an
5125     * instance of these subclasses is created programmatically rather than
5126     * being inflated from XML. This method is automatically called when the XML
5127     * is inflated.
5128     * </p>
5129     *
5130     * @param a the styled attributes set to initialize the fading edges from
5131     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5132     */
5133    protected void initializeFadingEdgeInternal(TypedArray a) {
5134        initScrollCache();
5135
5136        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5137                R.styleable.View_fadingEdgeLength,
5138                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5139    }
5140
5141    /**
5142     * Returns the size of the vertical faded edges used to indicate that more
5143     * content in this view is visible.
5144     *
5145     * @return The size in pixels of the vertical faded edge or 0 if vertical
5146     *         faded edges are not enabled for this view.
5147     * @attr ref android.R.styleable#View_fadingEdgeLength
5148     */
5149    public int getVerticalFadingEdgeLength() {
5150        if (isVerticalFadingEdgeEnabled()) {
5151            ScrollabilityCache cache = mScrollCache;
5152            if (cache != null) {
5153                return cache.fadingEdgeLength;
5154            }
5155        }
5156        return 0;
5157    }
5158
5159    /**
5160     * Set the size of the faded edge used to indicate that more content in this
5161     * view is available.  Will not change whether the fading edge is enabled; use
5162     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5163     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5164     * for the vertical or horizontal fading edges.
5165     *
5166     * @param length The size in pixels of the faded edge used to indicate that more
5167     *        content in this view is visible.
5168     */
5169    public void setFadingEdgeLength(int length) {
5170        initScrollCache();
5171        mScrollCache.fadingEdgeLength = length;
5172    }
5173
5174    /**
5175     * Returns the size of the horizontal faded edges used to indicate that more
5176     * content in this view is visible.
5177     *
5178     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5179     *         faded edges are not enabled for this view.
5180     * @attr ref android.R.styleable#View_fadingEdgeLength
5181     */
5182    public int getHorizontalFadingEdgeLength() {
5183        if (isHorizontalFadingEdgeEnabled()) {
5184            ScrollabilityCache cache = mScrollCache;
5185            if (cache != null) {
5186                return cache.fadingEdgeLength;
5187            }
5188        }
5189        return 0;
5190    }
5191
5192    /**
5193     * Returns the width of the vertical scrollbar.
5194     *
5195     * @return The width in pixels of the vertical scrollbar or 0 if there
5196     *         is no vertical scrollbar.
5197     */
5198    public int getVerticalScrollbarWidth() {
5199        ScrollabilityCache cache = mScrollCache;
5200        if (cache != null) {
5201            ScrollBarDrawable scrollBar = cache.scrollBar;
5202            if (scrollBar != null) {
5203                int size = scrollBar.getSize(true);
5204                if (size <= 0) {
5205                    size = cache.scrollBarSize;
5206                }
5207                return size;
5208            }
5209            return 0;
5210        }
5211        return 0;
5212    }
5213
5214    /**
5215     * Returns the height of the horizontal scrollbar.
5216     *
5217     * @return The height in pixels of the horizontal scrollbar or 0 if
5218     *         there is no horizontal scrollbar.
5219     */
5220    protected int getHorizontalScrollbarHeight() {
5221        ScrollabilityCache cache = mScrollCache;
5222        if (cache != null) {
5223            ScrollBarDrawable scrollBar = cache.scrollBar;
5224            if (scrollBar != null) {
5225                int size = scrollBar.getSize(false);
5226                if (size <= 0) {
5227                    size = cache.scrollBarSize;
5228                }
5229                return size;
5230            }
5231            return 0;
5232        }
5233        return 0;
5234    }
5235
5236    /**
5237     * <p>
5238     * Initializes the scrollbars from a given set of styled attributes. This
5239     * method should be called by subclasses that need scrollbars and when an
5240     * instance of these subclasses is created programmatically rather than
5241     * being inflated from XML. This method is automatically called when the XML
5242     * is inflated.
5243     * </p>
5244     *
5245     * @param a the styled attributes set to initialize the scrollbars from
5246     *
5247     * @removed
5248     */
5249    protected void initializeScrollbars(TypedArray a) {
5250        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5251        // using the View filter array which is not available to the SDK. As such, internal
5252        // framework usage now uses initializeScrollbarsInternal and we grab a default
5253        // TypedArray with the right filter instead here.
5254        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5255
5256        initializeScrollbarsInternal(arr);
5257
5258        // We ignored the method parameter. Recycle the one we actually did use.
5259        arr.recycle();
5260    }
5261
5262    /**
5263     * <p>
5264     * Initializes the scrollbars from a given set of styled attributes. This
5265     * method should be called by subclasses that need scrollbars and when an
5266     * instance of these subclasses is created programmatically rather than
5267     * being inflated from XML. This method is automatically called when the XML
5268     * is inflated.
5269     * </p>
5270     *
5271     * @param a the styled attributes set to initialize the scrollbars from
5272     * @hide
5273     */
5274    protected void initializeScrollbarsInternal(TypedArray a) {
5275        initScrollCache();
5276
5277        final ScrollabilityCache scrollabilityCache = mScrollCache;
5278
5279        if (scrollabilityCache.scrollBar == null) {
5280            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5281            scrollabilityCache.scrollBar.setState(getDrawableState());
5282            scrollabilityCache.scrollBar.setCallback(this);
5283        }
5284
5285        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5286
5287        if (!fadeScrollbars) {
5288            scrollabilityCache.state = ScrollabilityCache.ON;
5289        }
5290        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5291
5292
5293        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5294                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5295                        .getScrollBarFadeDuration());
5296        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5297                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5298                ViewConfiguration.getScrollDefaultDelay());
5299
5300
5301        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5302                com.android.internal.R.styleable.View_scrollbarSize,
5303                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5304
5305        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5306        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5307
5308        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5309        if (thumb != null) {
5310            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5311        }
5312
5313        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5314                false);
5315        if (alwaysDraw) {
5316            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5317        }
5318
5319        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5320        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5321
5322        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5323        if (thumb != null) {
5324            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5325        }
5326
5327        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5328                false);
5329        if (alwaysDraw) {
5330            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5331        }
5332
5333        // Apply layout direction to the new Drawables if needed
5334        final int layoutDirection = getLayoutDirection();
5335        if (track != null) {
5336            track.setLayoutDirection(layoutDirection);
5337        }
5338        if (thumb != null) {
5339            thumb.setLayoutDirection(layoutDirection);
5340        }
5341
5342        // Re-apply user/background padding so that scrollbar(s) get added
5343        resolvePadding();
5344    }
5345
5346    private void initializeScrollIndicatorsInternal() {
5347        // Some day maybe we'll break this into top/left/start/etc. and let the
5348        // client control it. Until then, you can have any scroll indicator you
5349        // want as long as it's a 1dp foreground-colored rectangle.
5350        if (mScrollIndicatorDrawable == null) {
5351            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5352        }
5353    }
5354
5355    /**
5356     * <p>
5357     * Initalizes the scrollability cache if necessary.
5358     * </p>
5359     */
5360    private void initScrollCache() {
5361        if (mScrollCache == null) {
5362            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5363        }
5364    }
5365
5366    private ScrollabilityCache getScrollCache() {
5367        initScrollCache();
5368        return mScrollCache;
5369    }
5370
5371    /**
5372     * Set the position of the vertical scroll bar. Should be one of
5373     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5374     * {@link #SCROLLBAR_POSITION_RIGHT}.
5375     *
5376     * @param position Where the vertical scroll bar should be positioned.
5377     */
5378    public void setVerticalScrollbarPosition(int position) {
5379        if (mVerticalScrollbarPosition != position) {
5380            mVerticalScrollbarPosition = position;
5381            computeOpaqueFlags();
5382            resolvePadding();
5383        }
5384    }
5385
5386    /**
5387     * @return The position where the vertical scroll bar will show, if applicable.
5388     * @see #setVerticalScrollbarPosition(int)
5389     */
5390    public int getVerticalScrollbarPosition() {
5391        return mVerticalScrollbarPosition;
5392    }
5393
5394    boolean isOnScrollbar(float x, float y) {
5395        if (mScrollCache == null) {
5396            return false;
5397        }
5398        x += getScrollX();
5399        y += getScrollY();
5400        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5401            final Rect bounds = mScrollCache.mScrollBarBounds;
5402            getVerticalScrollBarBounds(bounds);
5403            if (bounds.contains((int)x, (int)y)) {
5404                return true;
5405            }
5406        }
5407        if (isHorizontalScrollBarEnabled()) {
5408            final Rect bounds = mScrollCache.mScrollBarBounds;
5409            getHorizontalScrollBarBounds(bounds);
5410            if (bounds.contains((int)x, (int)y)) {
5411                return true;
5412            }
5413        }
5414        return false;
5415    }
5416
5417    boolean isOnScrollbarThumb(float x, float y) {
5418        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5419    }
5420
5421    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5422        if (mScrollCache == null) {
5423            return false;
5424        }
5425        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5426            x += getScrollX();
5427            y += getScrollY();
5428            final Rect bounds = mScrollCache.mScrollBarBounds;
5429            getVerticalScrollBarBounds(bounds);
5430            final int range = computeVerticalScrollRange();
5431            final int offset = computeVerticalScrollOffset();
5432            final int extent = computeVerticalScrollExtent();
5433            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5434                    extent, range);
5435            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5436                    extent, range, offset);
5437            final int thumbTop = bounds.top + thumbOffset;
5438            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5439                    && y <= thumbTop + thumbLength) {
5440                return true;
5441            }
5442        }
5443        return false;
5444    }
5445
5446    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5447        if (mScrollCache == null) {
5448            return false;
5449        }
5450        if (isHorizontalScrollBarEnabled()) {
5451            x += getScrollX();
5452            y += getScrollY();
5453            final Rect bounds = mScrollCache.mScrollBarBounds;
5454            getHorizontalScrollBarBounds(bounds);
5455            final int range = computeHorizontalScrollRange();
5456            final int offset = computeHorizontalScrollOffset();
5457            final int extent = computeHorizontalScrollExtent();
5458            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5459                    extent, range);
5460            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5461                    extent, range, offset);
5462            final int thumbLeft = bounds.left + thumbOffset;
5463            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5464                    && y <= bounds.bottom) {
5465                return true;
5466            }
5467        }
5468        return false;
5469    }
5470
5471    boolean isDraggingScrollBar() {
5472        return mScrollCache != null
5473                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5474    }
5475
5476    /**
5477     * Sets the state of all scroll indicators.
5478     * <p>
5479     * See {@link #setScrollIndicators(int, int)} for usage information.
5480     *
5481     * @param indicators a bitmask of indicators that should be enabled, or
5482     *                   {@code 0} to disable all indicators
5483     * @see #setScrollIndicators(int, int)
5484     * @see #getScrollIndicators()
5485     * @attr ref android.R.styleable#View_scrollIndicators
5486     */
5487    public void setScrollIndicators(@ScrollIndicators int indicators) {
5488        setScrollIndicators(indicators,
5489                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5490    }
5491
5492    /**
5493     * Sets the state of the scroll indicators specified by the mask. To change
5494     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5495     * <p>
5496     * When a scroll indicator is enabled, it will be displayed if the view
5497     * can scroll in the direction of the indicator.
5498     * <p>
5499     * Multiple indicator types may be enabled or disabled by passing the
5500     * logical OR of the desired types. If multiple types are specified, they
5501     * will all be set to the same enabled state.
5502     * <p>
5503     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5504     *
5505     * @param indicators the indicator direction, or the logical OR of multiple
5506     *             indicator directions. One or more of:
5507     *             <ul>
5508     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5509     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5510     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5511     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5512     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5513     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5514     *             </ul>
5515     * @see #setScrollIndicators(int)
5516     * @see #getScrollIndicators()
5517     * @attr ref android.R.styleable#View_scrollIndicators
5518     */
5519    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5520        // Shift and sanitize mask.
5521        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5522        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5523
5524        // Shift and mask indicators.
5525        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5526        indicators &= mask;
5527
5528        // Merge with non-masked flags.
5529        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5530
5531        if (mPrivateFlags3 != updatedFlags) {
5532            mPrivateFlags3 = updatedFlags;
5533
5534            if (indicators != 0) {
5535                initializeScrollIndicatorsInternal();
5536            }
5537            invalidate();
5538        }
5539    }
5540
5541    /**
5542     * Returns a bitmask representing the enabled scroll indicators.
5543     * <p>
5544     * For example, if the top and left scroll indicators are enabled and all
5545     * other indicators are disabled, the return value will be
5546     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5547     * <p>
5548     * To check whether the bottom scroll indicator is enabled, use the value
5549     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5550     *
5551     * @return a bitmask representing the enabled scroll indicators
5552     */
5553    @ScrollIndicators
5554    public int getScrollIndicators() {
5555        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5556                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5557    }
5558
5559    ListenerInfo getListenerInfo() {
5560        if (mListenerInfo != null) {
5561            return mListenerInfo;
5562        }
5563        mListenerInfo = new ListenerInfo();
5564        return mListenerInfo;
5565    }
5566
5567    /**
5568     * Register a callback to be invoked when the scroll X or Y positions of
5569     * this view change.
5570     * <p>
5571     * <b>Note:</b> Some views handle scrolling independently from View and may
5572     * have their own separate listeners for scroll-type events. For example,
5573     * {@link android.widget.ListView ListView} allows clients to register an
5574     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5575     * to listen for changes in list scroll position.
5576     *
5577     * @param l The listener to notify when the scroll X or Y position changes.
5578     * @see android.view.View#getScrollX()
5579     * @see android.view.View#getScrollY()
5580     */
5581    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5582        getListenerInfo().mOnScrollChangeListener = l;
5583    }
5584
5585    /**
5586     * Register a callback to be invoked when focus of this view changed.
5587     *
5588     * @param l The callback that will run.
5589     */
5590    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5591        getListenerInfo().mOnFocusChangeListener = l;
5592    }
5593
5594    /**
5595     * Add a listener that will be called when the bounds of the view change due to
5596     * layout processing.
5597     *
5598     * @param listener The listener that will be called when layout bounds change.
5599     */
5600    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5601        ListenerInfo li = getListenerInfo();
5602        if (li.mOnLayoutChangeListeners == null) {
5603            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5604        }
5605        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5606            li.mOnLayoutChangeListeners.add(listener);
5607        }
5608    }
5609
5610    /**
5611     * Remove a listener for layout changes.
5612     *
5613     * @param listener The listener for layout bounds change.
5614     */
5615    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5616        ListenerInfo li = mListenerInfo;
5617        if (li == null || li.mOnLayoutChangeListeners == null) {
5618            return;
5619        }
5620        li.mOnLayoutChangeListeners.remove(listener);
5621    }
5622
5623    /**
5624     * Add a listener for attach state changes.
5625     *
5626     * This listener will be called whenever this view is attached or detached
5627     * from a window. Remove the listener using
5628     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5629     *
5630     * @param listener Listener to attach
5631     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5632     */
5633    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5634        ListenerInfo li = getListenerInfo();
5635        if (li.mOnAttachStateChangeListeners == null) {
5636            li.mOnAttachStateChangeListeners
5637                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5638        }
5639        li.mOnAttachStateChangeListeners.add(listener);
5640    }
5641
5642    /**
5643     * Remove a listener for attach state changes. The listener will receive no further
5644     * notification of window attach/detach events.
5645     *
5646     * @param listener Listener to remove
5647     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5648     */
5649    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5650        ListenerInfo li = mListenerInfo;
5651        if (li == null || li.mOnAttachStateChangeListeners == null) {
5652            return;
5653        }
5654        li.mOnAttachStateChangeListeners.remove(listener);
5655    }
5656
5657    /**
5658     * Returns the focus-change callback registered for this view.
5659     *
5660     * @return The callback, or null if one is not registered.
5661     */
5662    public OnFocusChangeListener getOnFocusChangeListener() {
5663        ListenerInfo li = mListenerInfo;
5664        return li != null ? li.mOnFocusChangeListener : null;
5665    }
5666
5667    /**
5668     * Register a callback to be invoked when this view is clicked. If this view is not
5669     * clickable, it becomes clickable.
5670     *
5671     * @param l The callback that will run
5672     *
5673     * @see #setClickable(boolean)
5674     */
5675    public void setOnClickListener(@Nullable OnClickListener l) {
5676        if (!isClickable()) {
5677            setClickable(true);
5678        }
5679        getListenerInfo().mOnClickListener = l;
5680    }
5681
5682    /**
5683     * Return whether this view has an attached OnClickListener.  Returns
5684     * true if there is a listener, false if there is none.
5685     */
5686    public boolean hasOnClickListeners() {
5687        ListenerInfo li = mListenerInfo;
5688        return (li != null && li.mOnClickListener != null);
5689    }
5690
5691    /**
5692     * Register a callback to be invoked when this view is clicked and held. If this view is not
5693     * long clickable, it becomes long clickable.
5694     *
5695     * @param l The callback that will run
5696     *
5697     * @see #setLongClickable(boolean)
5698     */
5699    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5700        if (!isLongClickable()) {
5701            setLongClickable(true);
5702        }
5703        getListenerInfo().mOnLongClickListener = l;
5704    }
5705
5706    /**
5707     * Register a callback to be invoked when this view is context clicked. If the view is not
5708     * context clickable, it becomes context clickable.
5709     *
5710     * @param l The callback that will run
5711     * @see #setContextClickable(boolean)
5712     */
5713    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5714        if (!isContextClickable()) {
5715            setContextClickable(true);
5716        }
5717        getListenerInfo().mOnContextClickListener = l;
5718    }
5719
5720    /**
5721     * Register a callback to be invoked when the context menu for this view is
5722     * being built. If this view is not long clickable, it becomes long clickable.
5723     *
5724     * @param l The callback that will run
5725     *
5726     */
5727    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5728        if (!isLongClickable()) {
5729            setLongClickable(true);
5730        }
5731        getListenerInfo().mOnCreateContextMenuListener = l;
5732    }
5733
5734    /**
5735     * Set an observer to collect stats for each frame rendered for this view.
5736     *
5737     * @hide
5738     */
5739    public void addFrameMetricsListener(Window window,
5740            Window.OnFrameMetricsAvailableListener listener,
5741            Handler handler) {
5742        if (mAttachInfo != null) {
5743            if (mAttachInfo.mThreadedRenderer != null) {
5744                if (mFrameMetricsObservers == null) {
5745                    mFrameMetricsObservers = new ArrayList<>();
5746                }
5747
5748                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5749                        handler.getLooper(), listener);
5750                mFrameMetricsObservers.add(fmo);
5751                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
5752            } else {
5753                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5754            }
5755        } else {
5756            if (mFrameMetricsObservers == null) {
5757                mFrameMetricsObservers = new ArrayList<>();
5758            }
5759
5760            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5761                    handler.getLooper(), listener);
5762            mFrameMetricsObservers.add(fmo);
5763        }
5764    }
5765
5766    /**
5767     * Remove observer configured to collect frame stats for this view.
5768     *
5769     * @hide
5770     */
5771    public void removeFrameMetricsListener(
5772            Window.OnFrameMetricsAvailableListener listener) {
5773        ThreadedRenderer renderer = getThreadedRenderer();
5774        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5775        if (fmo == null) {
5776            throw new IllegalArgumentException(
5777                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5778        }
5779
5780        if (mFrameMetricsObservers != null) {
5781            mFrameMetricsObservers.remove(fmo);
5782            if (renderer != null) {
5783                renderer.removeFrameMetricsObserver(fmo);
5784            }
5785        }
5786    }
5787
5788    private void registerPendingFrameMetricsObservers() {
5789        if (mFrameMetricsObservers != null) {
5790            ThreadedRenderer renderer = getThreadedRenderer();
5791            if (renderer != null) {
5792                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5793                    renderer.addFrameMetricsObserver(fmo);
5794                }
5795            } else {
5796                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5797            }
5798        }
5799    }
5800
5801    private FrameMetricsObserver findFrameMetricsObserver(
5802            Window.OnFrameMetricsAvailableListener listener) {
5803        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5804            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5805            if (observer.mListener == listener) {
5806                return observer;
5807            }
5808        }
5809
5810        return null;
5811    }
5812
5813    /**
5814     * Call this view's OnClickListener, if it is defined.  Performs all normal
5815     * actions associated with clicking: reporting accessibility event, playing
5816     * a sound, etc.
5817     *
5818     * @return True there was an assigned OnClickListener that was called, false
5819     *         otherwise is returned.
5820     */
5821    public boolean performClick() {
5822        final boolean result;
5823        final ListenerInfo li = mListenerInfo;
5824        if (li != null && li.mOnClickListener != null) {
5825            playSoundEffect(SoundEffectConstants.CLICK);
5826            li.mOnClickListener.onClick(this);
5827            result = true;
5828        } else {
5829            result = false;
5830        }
5831
5832        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5833        return result;
5834    }
5835
5836    /**
5837     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5838     * this only calls the listener, and does not do any associated clicking
5839     * actions like reporting an accessibility event.
5840     *
5841     * @return True there was an assigned OnClickListener that was called, false
5842     *         otherwise is returned.
5843     */
5844    public boolean callOnClick() {
5845        ListenerInfo li = mListenerInfo;
5846        if (li != null && li.mOnClickListener != null) {
5847            li.mOnClickListener.onClick(this);
5848            return true;
5849        }
5850        return false;
5851    }
5852
5853    /**
5854     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5855     * context menu if the OnLongClickListener did not consume the event.
5856     *
5857     * @return {@code true} if one of the above receivers consumed the event,
5858     *         {@code false} otherwise
5859     */
5860    public boolean performLongClick() {
5861        return performLongClickInternal(mLongClickX, mLongClickY);
5862    }
5863
5864    /**
5865     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5866     * context menu if the OnLongClickListener did not consume the event,
5867     * anchoring it to an (x,y) coordinate.
5868     *
5869     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5870     *          to disable anchoring
5871     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5872     *          to disable anchoring
5873     * @return {@code true} if one of the above receivers consumed the event,
5874     *         {@code false} otherwise
5875     */
5876    public boolean performLongClick(float x, float y) {
5877        mLongClickX = x;
5878        mLongClickY = y;
5879        final boolean handled = performLongClick();
5880        mLongClickX = Float.NaN;
5881        mLongClickY = Float.NaN;
5882        return handled;
5883    }
5884
5885    /**
5886     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5887     * context menu if the OnLongClickListener did not consume the event,
5888     * optionally anchoring it to an (x,y) coordinate.
5889     *
5890     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5891     *          to disable anchoring
5892     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5893     *          to disable anchoring
5894     * @return {@code true} if one of the above receivers consumed the event,
5895     *         {@code false} otherwise
5896     */
5897    private boolean performLongClickInternal(float x, float y) {
5898        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5899
5900        boolean handled = false;
5901        final ListenerInfo li = mListenerInfo;
5902        if (li != null && li.mOnLongClickListener != null) {
5903            handled = li.mOnLongClickListener.onLongClick(View.this);
5904        }
5905        if (!handled) {
5906            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5907            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5908        }
5909        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
5910            if (!handled) {
5911                handled = showLongClickTooltip((int) x, (int) y);
5912            }
5913        }
5914        if (handled) {
5915            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5916        }
5917        return handled;
5918    }
5919
5920    /**
5921     * Call this view's OnContextClickListener, if it is defined.
5922     *
5923     * @param x the x coordinate of the context click
5924     * @param y the y coordinate of the context click
5925     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5926     *         otherwise.
5927     */
5928    public boolean performContextClick(float x, float y) {
5929        return performContextClick();
5930    }
5931
5932    /**
5933     * Call this view's OnContextClickListener, if it is defined.
5934     *
5935     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5936     *         otherwise.
5937     */
5938    public boolean performContextClick() {
5939        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5940
5941        boolean handled = false;
5942        ListenerInfo li = mListenerInfo;
5943        if (li != null && li.mOnContextClickListener != null) {
5944            handled = li.mOnContextClickListener.onContextClick(View.this);
5945        }
5946        if (handled) {
5947            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5948        }
5949        return handled;
5950    }
5951
5952    /**
5953     * Performs button-related actions during a touch down event.
5954     *
5955     * @param event The event.
5956     * @return True if the down was consumed.
5957     *
5958     * @hide
5959     */
5960    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5961        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5962            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5963            showContextMenu(event.getX(), event.getY());
5964            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5965            return true;
5966        }
5967        return false;
5968    }
5969
5970    /**
5971     * Shows the context menu for this view.
5972     *
5973     * @return {@code true} if the context menu was shown, {@code false}
5974     *         otherwise
5975     * @see #showContextMenu(float, float)
5976     */
5977    public boolean showContextMenu() {
5978        return getParent().showContextMenuForChild(this);
5979    }
5980
5981    /**
5982     * Shows the context menu for this view anchored to the specified
5983     * view-relative coordinate.
5984     *
5985     * @param x the X coordinate in pixels relative to the view to which the
5986     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5987     * @param y the Y coordinate in pixels relative to the view to which the
5988     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5989     * @return {@code true} if the context menu was shown, {@code false}
5990     *         otherwise
5991     */
5992    public boolean showContextMenu(float x, float y) {
5993        return getParent().showContextMenuForChild(this, x, y);
5994    }
5995
5996    /**
5997     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5998     *
5999     * @param callback Callback that will control the lifecycle of the action mode
6000     * @return The new action mode if it is started, null otherwise
6001     *
6002     * @see ActionMode
6003     * @see #startActionMode(android.view.ActionMode.Callback, int)
6004     */
6005    public ActionMode startActionMode(ActionMode.Callback callback) {
6006        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
6007    }
6008
6009    /**
6010     * Start an action mode with the given type.
6011     *
6012     * @param callback Callback that will control the lifecycle of the action mode
6013     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6014     * @return The new action mode if it is started, null otherwise
6015     *
6016     * @see ActionMode
6017     */
6018    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6019        ViewParent parent = getParent();
6020        if (parent == null) return null;
6021        try {
6022            return parent.startActionModeForChild(this, callback, type);
6023        } catch (AbstractMethodError ame) {
6024            // Older implementations of custom views might not implement this.
6025            return parent.startActionModeForChild(this, callback);
6026        }
6027    }
6028
6029    /**
6030     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
6031     * Context, creating a unique View identifier to retrieve the result.
6032     *
6033     * @param intent The Intent to be started.
6034     * @param requestCode The request code to use.
6035     * @hide
6036     */
6037    public void startActivityForResult(Intent intent, int requestCode) {
6038        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
6039        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
6040    }
6041
6042    /**
6043     * If this View corresponds to the calling who, dispatches the activity result.
6044     * @param who The identifier for the targeted View to receive the result.
6045     * @param requestCode The integer request code originally supplied to
6046     *                    startActivityForResult(), allowing you to identify who this
6047     *                    result came from.
6048     * @param resultCode The integer result code returned by the child activity
6049     *                   through its setResult().
6050     * @param data An Intent, which can return result data to the caller
6051     *               (various data can be attached to Intent "extras").
6052     * @return {@code true} if the activity result was dispatched.
6053     * @hide
6054     */
6055    public boolean dispatchActivityResult(
6056            String who, int requestCode, int resultCode, Intent data) {
6057        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6058            onActivityResult(requestCode, resultCode, data);
6059            mStartActivityRequestWho = null;
6060            return true;
6061        }
6062        return false;
6063    }
6064
6065    /**
6066     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6067     *
6068     * @param requestCode The integer request code originally supplied to
6069     *                    startActivityForResult(), allowing you to identify who this
6070     *                    result came from.
6071     * @param resultCode The integer result code returned by the child activity
6072     *                   through its setResult().
6073     * @param data An Intent, which can return result data to the caller
6074     *               (various data can be attached to Intent "extras").
6075     * @hide
6076     */
6077    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6078        // Do nothing.
6079    }
6080
6081    /**
6082     * Register a callback to be invoked when a hardware key is pressed in this view.
6083     * Key presses in software input methods will generally not trigger the methods of
6084     * this listener.
6085     * @param l the key listener to attach to this view
6086     */
6087    public void setOnKeyListener(OnKeyListener l) {
6088        getListenerInfo().mOnKeyListener = l;
6089    }
6090
6091    /**
6092     * Register a callback to be invoked when a touch event is sent to this view.
6093     * @param l the touch listener to attach to this view
6094     */
6095    public void setOnTouchListener(OnTouchListener l) {
6096        getListenerInfo().mOnTouchListener = l;
6097    }
6098
6099    /**
6100     * Register a callback to be invoked when a generic motion event is sent to this view.
6101     * @param l the generic motion listener to attach to this view
6102     */
6103    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6104        getListenerInfo().mOnGenericMotionListener = l;
6105    }
6106
6107    /**
6108     * Register a callback to be invoked when a hover event is sent to this view.
6109     * @param l the hover listener to attach to this view
6110     */
6111    public void setOnHoverListener(OnHoverListener l) {
6112        getListenerInfo().mOnHoverListener = l;
6113    }
6114
6115    /**
6116     * Register a drag event listener callback object for this View. The parameter is
6117     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6118     * View, the system calls the
6119     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6120     * @param l An implementation of {@link android.view.View.OnDragListener}.
6121     */
6122    public void setOnDragListener(OnDragListener l) {
6123        getListenerInfo().mOnDragListener = l;
6124    }
6125
6126    /**
6127     * Give this view focus. This will cause
6128     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6129     *
6130     * Note: this does not check whether this {@link View} should get focus, it just
6131     * gives it focus no matter what.  It should only be called internally by framework
6132     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6133     *
6134     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6135     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6136     *        focus moved when requestFocus() is called. It may not always
6137     *        apply, in which case use the default View.FOCUS_DOWN.
6138     * @param previouslyFocusedRect The rectangle of the view that had focus
6139     *        prior in this View's coordinate system.
6140     */
6141    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6142        if (DBG) {
6143            System.out.println(this + " requestFocus()");
6144        }
6145
6146        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6147            mPrivateFlags |= PFLAG_FOCUSED;
6148
6149            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6150
6151            if (mParent != null) {
6152                mParent.requestChildFocus(this, this);
6153                if (mParent instanceof ViewGroup) {
6154                    ((ViewGroup) mParent).setDefaultFocus(this);
6155                }
6156            }
6157
6158            if (mAttachInfo != null) {
6159                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6160            }
6161
6162            onFocusChanged(true, direction, previouslyFocusedRect);
6163            refreshDrawableState();
6164        }
6165    }
6166
6167    /**
6168     * Sets this view's preference for reveal behavior when it gains focus.
6169     *
6170     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6171     * this view would prefer to be brought fully into view when it gains focus.
6172     * For example, a text field that a user is meant to type into. Other views such
6173     * as scrolling containers may prefer to opt-out of this behavior.</p>
6174     *
6175     * <p>The default value for views is true, though subclasses may change this
6176     * based on their preferred behavior.</p>
6177     *
6178     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6179     *
6180     * @see #getRevealOnFocusHint()
6181     */
6182    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6183        if (revealOnFocus) {
6184            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6185        } else {
6186            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6187        }
6188    }
6189
6190    /**
6191     * Returns this view's preference for reveal behavior when it gains focus.
6192     *
6193     * <p>When this method returns true for a child view requesting focus, ancestor
6194     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6195     * should make a best effort to make the newly focused child fully visible to the user.
6196     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6197     * other properties affecting visibility to the user as part of the focus change.</p>
6198     *
6199     * @return true if this view would prefer to become fully visible when it gains focus,
6200     *         false if it would prefer not to disrupt scroll positioning
6201     *
6202     * @see #setRevealOnFocusHint(boolean)
6203     */
6204    public final boolean getRevealOnFocusHint() {
6205        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6206    }
6207
6208    /**
6209     * Populates <code>outRect</code> with the hotspot bounds. By default,
6210     * the hotspot bounds are identical to the screen bounds.
6211     *
6212     * @param outRect rect to populate with hotspot bounds
6213     * @hide Only for internal use by views and widgets.
6214     */
6215    public void getHotspotBounds(Rect outRect) {
6216        final Drawable background = getBackground();
6217        if (background != null) {
6218            background.getHotspotBounds(outRect);
6219        } else {
6220            getBoundsOnScreen(outRect);
6221        }
6222    }
6223
6224    /**
6225     * Request that a rectangle of this view be visible on the screen,
6226     * scrolling if necessary just enough.
6227     *
6228     * <p>A View should call this if it maintains some notion of which part
6229     * of its content is interesting.  For example, a text editing view
6230     * should call this when its cursor moves.
6231     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6232     * It should not be affected by which part of the View is currently visible or its scroll
6233     * position.
6234     *
6235     * @param rectangle The rectangle in the View's content coordinate space
6236     * @return Whether any parent scrolled.
6237     */
6238    public boolean requestRectangleOnScreen(Rect rectangle) {
6239        return requestRectangleOnScreen(rectangle, false);
6240    }
6241
6242    /**
6243     * Request that a rectangle of this view be visible on the screen,
6244     * scrolling if necessary just enough.
6245     *
6246     * <p>A View should call this if it maintains some notion of which part
6247     * of its content is interesting.  For example, a text editing view
6248     * should call this when its cursor moves.
6249     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6250     * It should not be affected by which part of the View is currently visible or its scroll
6251     * position.
6252     * <p>When <code>immediate</code> is set to true, scrolling will not be
6253     * animated.
6254     *
6255     * @param rectangle The rectangle in the View's content coordinate space
6256     * @param immediate True to forbid animated scrolling, false otherwise
6257     * @return Whether any parent scrolled.
6258     */
6259    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6260        if (mParent == null) {
6261            return false;
6262        }
6263
6264        View child = this;
6265
6266        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6267        position.set(rectangle);
6268
6269        ViewParent parent = mParent;
6270        boolean scrolled = false;
6271        while (parent != null) {
6272            rectangle.set((int) position.left, (int) position.top,
6273                    (int) position.right, (int) position.bottom);
6274
6275            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6276
6277            if (!(parent instanceof View)) {
6278                break;
6279            }
6280
6281            // move it from child's content coordinate space to parent's content coordinate space
6282            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6283
6284            child = (View) parent;
6285            parent = child.getParent();
6286        }
6287
6288        return scrolled;
6289    }
6290
6291    /**
6292     * Called when this view wants to give up focus. If focus is cleared
6293     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6294     * <p>
6295     * <strong>Note:</strong> When a View clears focus the framework is trying
6296     * to give focus to the first focusable View from the top. Hence, if this
6297     * View is the first from the top that can take focus, then all callbacks
6298     * related to clearing focus will be invoked after which the framework will
6299     * give focus to this view.
6300     * </p>
6301     */
6302    public void clearFocus() {
6303        if (DBG) {
6304            System.out.println(this + " clearFocus()");
6305        }
6306
6307        clearFocusInternal(null, true, true);
6308    }
6309
6310    /**
6311     * Clears focus from the view, optionally propagating the change up through
6312     * the parent hierarchy and requesting that the root view place new focus.
6313     *
6314     * @param propagate whether to propagate the change up through the parent
6315     *            hierarchy
6316     * @param refocus when propagate is true, specifies whether to request the
6317     *            root view place new focus
6318     */
6319    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6320        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6321            mPrivateFlags &= ~PFLAG_FOCUSED;
6322
6323            if (propagate && mParent != null) {
6324                mParent.clearChildFocus(this);
6325            }
6326
6327            onFocusChanged(false, 0, null);
6328            refreshDrawableState();
6329
6330            if (propagate && (!refocus || !rootViewRequestFocus())) {
6331                notifyGlobalFocusCleared(this);
6332            }
6333        }
6334    }
6335
6336    void notifyGlobalFocusCleared(View oldFocus) {
6337        if (oldFocus != null && mAttachInfo != null) {
6338            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6339        }
6340    }
6341
6342    boolean rootViewRequestFocus() {
6343        final View root = getRootView();
6344        return root != null && root.requestFocus();
6345    }
6346
6347    /**
6348     * Called internally by the view system when a new view is getting focus.
6349     * This is what clears the old focus.
6350     * <p>
6351     * <b>NOTE:</b> The parent view's focused child must be updated manually
6352     * after calling this method. Otherwise, the view hierarchy may be left in
6353     * an inconstent state.
6354     */
6355    void unFocus(View focused) {
6356        if (DBG) {
6357            System.out.println(this + " unFocus()");
6358        }
6359
6360        clearFocusInternal(focused, false, false);
6361    }
6362
6363    /**
6364     * Returns true if this view has focus itself, or is the ancestor of the
6365     * view that has focus.
6366     *
6367     * @return True if this view has or contains focus, false otherwise.
6368     */
6369    @ViewDebug.ExportedProperty(category = "focus")
6370    public boolean hasFocus() {
6371        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6372    }
6373
6374    /**
6375     * Returns true if this view is focusable or if it contains a reachable View
6376     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6377     * is a View whose parents do not block descendants focus.
6378     *
6379     * Only {@link #VISIBLE} views are considered focusable.
6380     *
6381     * @return True if the view is focusable or if the view contains a focusable
6382     *         View, false otherwise.
6383     *
6384     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6385     * @see ViewGroup#getTouchscreenBlocksFocus()
6386     */
6387    public boolean hasFocusable() {
6388        if (!isFocusableInTouchMode()) {
6389            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6390                final ViewGroup g = (ViewGroup) p;
6391                if (g.shouldBlockFocusForTouchscreen()) {
6392                    return false;
6393                }
6394            }
6395        }
6396        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6397    }
6398
6399    /**
6400     * Called by the view system when the focus state of this view changes.
6401     * When the focus change event is caused by directional navigation, direction
6402     * and previouslyFocusedRect provide insight into where the focus is coming from.
6403     * When overriding, be sure to call up through to the super class so that
6404     * the standard focus handling will occur.
6405     *
6406     * @param gainFocus True if the View has focus; false otherwise.
6407     * @param direction The direction focus has moved when requestFocus()
6408     *                  is called to give this view focus. Values are
6409     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6410     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6411     *                  It may not always apply, in which case use the default.
6412     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6413     *        system, of the previously focused view.  If applicable, this will be
6414     *        passed in as finer grained information about where the focus is coming
6415     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6416     */
6417    @CallSuper
6418    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6419            @Nullable Rect previouslyFocusedRect) {
6420        if (gainFocus) {
6421            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6422        } else {
6423            notifyViewAccessibilityStateChangedIfNeeded(
6424                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6425        }
6426
6427        InputMethodManager imm = InputMethodManager.peekInstance();
6428        if (!gainFocus) {
6429            if (isPressed()) {
6430                setPressed(false);
6431            }
6432            if (imm != null && mAttachInfo != null
6433                    && mAttachInfo.mHasWindowFocus) {
6434                imm.focusOut(this);
6435            }
6436            onFocusLost();
6437        } else if (imm != null && mAttachInfo != null
6438                && mAttachInfo.mHasWindowFocus) {
6439            imm.focusIn(this);
6440        }
6441
6442        invalidate(true);
6443        ListenerInfo li = mListenerInfo;
6444        if (li != null && li.mOnFocusChangeListener != null) {
6445            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6446        }
6447
6448        if (mAttachInfo != null) {
6449            mAttachInfo.mKeyDispatchState.reset(this);
6450        }
6451    }
6452
6453    /**
6454     * Sends an accessibility event of the given type. If accessibility is
6455     * not enabled this method has no effect. The default implementation calls
6456     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6457     * to populate information about the event source (this View), then calls
6458     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6459     * populate the text content of the event source including its descendants,
6460     * and last calls
6461     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6462     * on its parent to request sending of the event to interested parties.
6463     * <p>
6464     * If an {@link AccessibilityDelegate} has been specified via calling
6465     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6466     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6467     * responsible for handling this call.
6468     * </p>
6469     *
6470     * @param eventType The type of the event to send, as defined by several types from
6471     * {@link android.view.accessibility.AccessibilityEvent}, such as
6472     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6473     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6474     *
6475     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6476     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6477     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6478     * @see AccessibilityDelegate
6479     */
6480    public void sendAccessibilityEvent(int eventType) {
6481        if (mAccessibilityDelegate != null) {
6482            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6483        } else {
6484            sendAccessibilityEventInternal(eventType);
6485        }
6486    }
6487
6488    /**
6489     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6490     * {@link AccessibilityEvent} to make an announcement which is related to some
6491     * sort of a context change for which none of the events representing UI transitions
6492     * is a good fit. For example, announcing a new page in a book. If accessibility
6493     * is not enabled this method does nothing.
6494     *
6495     * @param text The announcement text.
6496     */
6497    public void announceForAccessibility(CharSequence text) {
6498        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6499            AccessibilityEvent event = AccessibilityEvent.obtain(
6500                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6501            onInitializeAccessibilityEvent(event);
6502            event.getText().add(text);
6503            event.setContentDescription(null);
6504            mParent.requestSendAccessibilityEvent(this, event);
6505        }
6506    }
6507
6508    /**
6509     * @see #sendAccessibilityEvent(int)
6510     *
6511     * Note: Called from the default {@link AccessibilityDelegate}.
6512     *
6513     * @hide
6514     */
6515    public void sendAccessibilityEventInternal(int eventType) {
6516        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6517            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6518        }
6519    }
6520
6521    /**
6522     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6523     * takes as an argument an empty {@link AccessibilityEvent} and does not
6524     * perform a check whether accessibility is enabled.
6525     * <p>
6526     * If an {@link AccessibilityDelegate} has been specified via calling
6527     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6528     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6529     * is responsible for handling this call.
6530     * </p>
6531     *
6532     * @param event The event to send.
6533     *
6534     * @see #sendAccessibilityEvent(int)
6535     */
6536    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6537        if (mAccessibilityDelegate != null) {
6538            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6539        } else {
6540            sendAccessibilityEventUncheckedInternal(event);
6541        }
6542    }
6543
6544    /**
6545     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6546     *
6547     * Note: Called from the default {@link AccessibilityDelegate}.
6548     *
6549     * @hide
6550     */
6551    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6552        if (!isShown()) {
6553            return;
6554        }
6555        onInitializeAccessibilityEvent(event);
6556        // Only a subset of accessibility events populates text content.
6557        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6558            dispatchPopulateAccessibilityEvent(event);
6559        }
6560        // In the beginning we called #isShown(), so we know that getParent() is not null.
6561        getParent().requestSendAccessibilityEvent(this, event);
6562    }
6563
6564    /**
6565     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6566     * to its children for adding their text content to the event. Note that the
6567     * event text is populated in a separate dispatch path since we add to the
6568     * event not only the text of the source but also the text of all its descendants.
6569     * A typical implementation will call
6570     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6571     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6572     * on each child. Override this method if custom population of the event text
6573     * content is required.
6574     * <p>
6575     * If an {@link AccessibilityDelegate} has been specified via calling
6576     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6577     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6578     * is responsible for handling this call.
6579     * </p>
6580     * <p>
6581     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6582     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6583     * </p>
6584     *
6585     * @param event The event.
6586     *
6587     * @return True if the event population was completed.
6588     */
6589    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6590        if (mAccessibilityDelegate != null) {
6591            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6592        } else {
6593            return dispatchPopulateAccessibilityEventInternal(event);
6594        }
6595    }
6596
6597    /**
6598     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6599     *
6600     * Note: Called from the default {@link AccessibilityDelegate}.
6601     *
6602     * @hide
6603     */
6604    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6605        onPopulateAccessibilityEvent(event);
6606        return false;
6607    }
6608
6609    /**
6610     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6611     * giving a chance to this View to populate the accessibility event with its
6612     * text content. While this method is free to modify event
6613     * attributes other than text content, doing so should normally be performed in
6614     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6615     * <p>
6616     * Example: Adding formatted date string to an accessibility event in addition
6617     *          to the text added by the super implementation:
6618     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6619     *     super.onPopulateAccessibilityEvent(event);
6620     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6621     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6622     *         mCurrentDate.getTimeInMillis(), flags);
6623     *     event.getText().add(selectedDateUtterance);
6624     * }</pre>
6625     * <p>
6626     * If an {@link AccessibilityDelegate} has been specified via calling
6627     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6628     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6629     * is responsible for handling this call.
6630     * </p>
6631     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6632     * information to the event, in case the default implementation has basic information to add.
6633     * </p>
6634     *
6635     * @param event The accessibility event which to populate.
6636     *
6637     * @see #sendAccessibilityEvent(int)
6638     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6639     */
6640    @CallSuper
6641    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6642        if (mAccessibilityDelegate != null) {
6643            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6644        } else {
6645            onPopulateAccessibilityEventInternal(event);
6646        }
6647    }
6648
6649    /**
6650     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6651     *
6652     * Note: Called from the default {@link AccessibilityDelegate}.
6653     *
6654     * @hide
6655     */
6656    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6657    }
6658
6659    /**
6660     * Initializes an {@link AccessibilityEvent} with information about
6661     * this View which is the event source. In other words, the source of
6662     * an accessibility event is the view whose state change triggered firing
6663     * the event.
6664     * <p>
6665     * Example: Setting the password property of an event in addition
6666     *          to properties set by the super implementation:
6667     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6668     *     super.onInitializeAccessibilityEvent(event);
6669     *     event.setPassword(true);
6670     * }</pre>
6671     * <p>
6672     * If an {@link AccessibilityDelegate} has been specified via calling
6673     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6674     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6675     * is responsible for handling this call.
6676     * </p>
6677     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6678     * information to the event, in case the default implementation has basic information to add.
6679     * </p>
6680     * @param event The event to initialize.
6681     *
6682     * @see #sendAccessibilityEvent(int)
6683     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6684     */
6685    @CallSuper
6686    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6687        if (mAccessibilityDelegate != null) {
6688            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6689        } else {
6690            onInitializeAccessibilityEventInternal(event);
6691        }
6692    }
6693
6694    /**
6695     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6696     *
6697     * Note: Called from the default {@link AccessibilityDelegate}.
6698     *
6699     * @hide
6700     */
6701    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6702        event.setSource(this);
6703        event.setClassName(getAccessibilityClassName());
6704        event.setPackageName(getContext().getPackageName());
6705        event.setEnabled(isEnabled());
6706        event.setContentDescription(mContentDescription);
6707
6708        switch (event.getEventType()) {
6709            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6710                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6711                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6712                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6713                event.setItemCount(focusablesTempList.size());
6714                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6715                if (mAttachInfo != null) {
6716                    focusablesTempList.clear();
6717                }
6718            } break;
6719            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6720                CharSequence text = getIterableTextForAccessibility();
6721                if (text != null && text.length() > 0) {
6722                    event.setFromIndex(getAccessibilitySelectionStart());
6723                    event.setToIndex(getAccessibilitySelectionEnd());
6724                    event.setItemCount(text.length());
6725                }
6726            } break;
6727        }
6728    }
6729
6730    /**
6731     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6732     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6733     * This method is responsible for obtaining an accessibility node info from a
6734     * pool of reusable instances and calling
6735     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6736     * initialize the former.
6737     * <p>
6738     * Note: The client is responsible for recycling the obtained instance by calling
6739     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6740     * </p>
6741     *
6742     * @return A populated {@link AccessibilityNodeInfo}.
6743     *
6744     * @see AccessibilityNodeInfo
6745     */
6746    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6747        if (mAccessibilityDelegate != null) {
6748            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6749        } else {
6750            return createAccessibilityNodeInfoInternal();
6751        }
6752    }
6753
6754    /**
6755     * @see #createAccessibilityNodeInfo()
6756     *
6757     * @hide
6758     */
6759    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6760        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6761        if (provider != null) {
6762            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6763        } else {
6764            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6765            onInitializeAccessibilityNodeInfo(info);
6766            return info;
6767        }
6768    }
6769
6770    /**
6771     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6772     * The base implementation sets:
6773     * <ul>
6774     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6775     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6776     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6777     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6778     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6779     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6780     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6781     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6782     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6783     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6784     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6785     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6786     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6787     * </ul>
6788     * <p>
6789     * Subclasses should override this method, call the super implementation,
6790     * and set additional attributes.
6791     * </p>
6792     * <p>
6793     * If an {@link AccessibilityDelegate} has been specified via calling
6794     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6795     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6796     * is responsible for handling this call.
6797     * </p>
6798     *
6799     * @param info The instance to initialize.
6800     */
6801    @CallSuper
6802    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6803        if (mAccessibilityDelegate != null) {
6804            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6805        } else {
6806            onInitializeAccessibilityNodeInfoInternal(info);
6807        }
6808    }
6809
6810    /**
6811     * Gets the location of this view in screen coordinates.
6812     *
6813     * @param outRect The output location
6814     * @hide
6815     */
6816    public void getBoundsOnScreen(Rect outRect) {
6817        getBoundsOnScreen(outRect, false);
6818    }
6819
6820    /**
6821     * Gets the location of this view in screen coordinates.
6822     *
6823     * @param outRect The output location
6824     * @param clipToParent Whether to clip child bounds to the parent ones.
6825     * @hide
6826     */
6827    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6828        if (mAttachInfo == null) {
6829            return;
6830        }
6831
6832        RectF position = mAttachInfo.mTmpTransformRect;
6833        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6834
6835        if (!hasIdentityMatrix()) {
6836            getMatrix().mapRect(position);
6837        }
6838
6839        position.offset(mLeft, mTop);
6840
6841        ViewParent parent = mParent;
6842        while (parent instanceof View) {
6843            View parentView = (View) parent;
6844
6845            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6846
6847            if (clipToParent) {
6848                position.left = Math.max(position.left, 0);
6849                position.top = Math.max(position.top, 0);
6850                position.right = Math.min(position.right, parentView.getWidth());
6851                position.bottom = Math.min(position.bottom, parentView.getHeight());
6852            }
6853
6854            if (!parentView.hasIdentityMatrix()) {
6855                parentView.getMatrix().mapRect(position);
6856            }
6857
6858            position.offset(parentView.mLeft, parentView.mTop);
6859
6860            parent = parentView.mParent;
6861        }
6862
6863        if (parent instanceof ViewRootImpl) {
6864            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6865            position.offset(0, -viewRootImpl.mCurScrollY);
6866        }
6867
6868        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6869
6870        outRect.set(Math.round(position.left), Math.round(position.top),
6871                Math.round(position.right), Math.round(position.bottom));
6872    }
6873
6874    /**
6875     * Return the class name of this object to be used for accessibility purposes.
6876     * Subclasses should only override this if they are implementing something that
6877     * should be seen as a completely new class of view when used by accessibility,
6878     * unrelated to the class it is deriving from.  This is used to fill in
6879     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6880     */
6881    public CharSequence getAccessibilityClassName() {
6882        return View.class.getName();
6883    }
6884
6885    /**
6886     * Called when assist structure is being retrieved from a view as part of
6887     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6888     * @param structure Fill in with structured view data.  The default implementation
6889     * fills in all data that can be inferred from the view itself.
6890     */
6891    public void onProvideStructure(ViewStructure structure) {
6892        onProvideStructureForAssistOrAutoFill(structure, 0);
6893    }
6894
6895    /**
6896     * Called when assist structure is being retrieved from a view as part of an auto-fill request.
6897     *
6898     * <p>The structure must be filled according to the request type, which is set in the
6899     * {@code flags} parameter - see the documentation on each flag for more details.
6900     *
6901     * @param structure Fill in with structured view data.  The default implementation
6902     * fills in all data that can be inferred from the view itself.
6903     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
6904     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
6905     */
6906    public void onProvideAutoFillStructure(ViewStructure structure, int flags) {
6907        onProvideStructureForAssistOrAutoFill(structure, flags);
6908    }
6909
6910    private void onProvideStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
6911        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
6912        // this method should take a boolean with the type of request.
6913        boolean forAutoFill = (flags
6914                & (View.AUTO_FILL_FLAG_TYPE_FILL
6915                        | View.AUTO_FILL_FLAG_TYPE_SAVE)) != 0;
6916        final int id = mID;
6917        if (id != NO_ID && !isViewIdGenerated(id)) {
6918            String pkg, type, entry;
6919            try {
6920                final Resources res = getResources();
6921                entry = res.getResourceEntryName(id);
6922                type = res.getResourceTypeName(id);
6923                pkg = res.getResourcePackageName(id);
6924            } catch (Resources.NotFoundException e) {
6925                entry = type = pkg = null;
6926            }
6927            structure.setId(id, pkg, type, entry);
6928        } else {
6929            structure.setId(id, null, null, null);
6930        }
6931
6932        if (forAutoFill) {
6933            // The auto-fill id needs to be unique, but its value doesn't matter, so it's better to
6934            // reuse the accessibility id to save space.
6935            structure.setAutoFillId(getAccessibilityViewId());
6936
6937            structure.setAutoFillType(getAutoFillType());
6938        }
6939
6940        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6941        if (!hasIdentityMatrix()) {
6942            structure.setTransformation(getMatrix());
6943        }
6944        structure.setElevation(getZ());
6945        structure.setVisibility(getVisibility());
6946        structure.setEnabled(isEnabled());
6947        if (isClickable()) {
6948            structure.setClickable(true);
6949        }
6950        if (isFocusable()) {
6951            structure.setFocusable(true);
6952        }
6953        if (isFocused()) {
6954            structure.setFocused(true);
6955        }
6956        if (isAccessibilityFocused()) {
6957            structure.setAccessibilityFocused(true);
6958        }
6959        if (isSelected()) {
6960            structure.setSelected(true);
6961        }
6962        if (isActivated()) {
6963            structure.setActivated(true);
6964        }
6965        if (isLongClickable()) {
6966            structure.setLongClickable(true);
6967        }
6968        if (this instanceof Checkable) {
6969            structure.setCheckable(true);
6970            if (((Checkable)this).isChecked()) {
6971                structure.setChecked(true);
6972            }
6973        }
6974        if (isContextClickable()) {
6975            structure.setContextClickable(true);
6976        }
6977        structure.setClassName(getAccessibilityClassName().toString());
6978        structure.setContentDescription(getContentDescription());
6979    }
6980
6981    /**
6982     * Called when assist structure is being retrieved from a view as part of
6983     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6984     * generate additional virtual structure under this view.  The defaullt implementation
6985     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6986     * view's virtual accessibility nodes, if any.  You can override this for a more
6987     * optimal implementation providing this data.
6988     */
6989    public void onProvideVirtualStructure(ViewStructure structure) {
6990        onProvideVirtualStructureForAssistOrAutoFill(structure, 0);
6991    }
6992
6993    /**
6994     * Called when assist structure is being retrieved from a view as part of an auto-fill request
6995     * to generate additional virtual structure under this view.
6996     *
6997     * <p>The defaullt implementation uses {@link #getAccessibilityNodeProvider()} to try to
6998     * generate this from the view's virtual accessibility nodes, if any. You can override this
6999     * for a more optimal implementation providing this data.
7000     *
7001     * <p>The structure must be filled according to the request type, which is set in the
7002     * {@code flags} parameter - see the documentation on each flag for more details.
7003     *
7004     * @param structure Fill in with structured view data.
7005     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7006     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
7007     */
7008    public void onProvideAutoFillVirtualStructure(ViewStructure structure, int flags) {
7009        onProvideVirtualStructureForAssistOrAutoFill(structure, flags);
7010    }
7011
7012    private void onProvideVirtualStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
7013        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7014        // this method should take a boolean with the type of request.
7015        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7016        if (provider != null) {
7017            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
7018            structure.setChildCount(1);
7019            ViewStructure root = structure.newChild(0);
7020            populateVirtualStructure(root, provider, info, flags);
7021            info.recycle();
7022        }
7023    }
7024
7025    /**
7026     * Gets the {@link VirtualViewDelegate} responsible for auto-filling the virtual children of
7027     * this view.
7028     *
7029     * <p>By default returns {@code null} but should be overridden when view provides a virtual
7030     * hierachy on {@link OnProvideAssistDataListener} that takes flags used by the AutoFill
7031     * Framework (such as {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7032     * {@link #AUTO_FILL_FLAG_TYPE_SAVE}).
7033     */
7034    @Nullable
7035    public VirtualViewDelegate getAutoFillVirtualViewDelegate(
7036            @SuppressWarnings("unused") VirtualViewDelegate.Callback callback) {
7037        return null;
7038    }
7039
7040    /**
7041     * Automatically fills the content of this view with the {@code value}.
7042     *
7043     * <p>By default does nothing, but views should override it (and {@link #getAutoFillType()} to
7044     * support the AutoFill Framework.
7045     *
7046     * <p>Typically, it is implemented by:
7047     *
7048     * <ol>
7049     * <li>Call the proper getter method on {@link AutoFillValue} to fetch the actual value.
7050     * <li>Pass the actual value to the equivalent setter in the view.
7051     * <ol>
7052     *
7053     * <p>For example, a text-field view would call:
7054     *
7055     * <pre class="prettyprint">
7056     * CharSequence text = value.getTextValue();
7057     * if (text != null) {
7058     *     setText(text);
7059     * }
7060     * </pre>
7061     */
7062    public void autoFill(@SuppressWarnings("unused") AutoFillValue value) {
7063    }
7064
7065    /**
7066     * Describes the auto-fill type that should be used on callas to
7067     * {@link #autoFill(AutoFillValue)} and
7068     * {@link VirtualViewDelegate#autoFill(int, AutoFillValue)}.
7069     *
7070     * <p>By default returns {@code null}, but views should override it (and
7071     * {@link #autoFill(AutoFillValue)} to support the AutoFill Framework.
7072     */
7073    @Nullable
7074    public AutoFillType getAutoFillType() {
7075        return null;
7076    }
7077
7078    private void populateVirtualStructure(ViewStructure structure,
7079            AccessibilityNodeProvider provider, AccessibilityNodeInfo info, int flags) {
7080        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7081        // this method should take a boolean with the type of request.
7082
7083        final boolean sanitized = (flags & View.AUTO_FILL_FLAG_TYPE_FILL) != 0;
7084
7085        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
7086                null, null, null);
7087        Rect rect = structure.getTempRect();
7088        info.getBoundsInParent(rect);
7089        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
7090        structure.setVisibility(VISIBLE);
7091        structure.setEnabled(info.isEnabled());
7092        if (info.isClickable()) {
7093            structure.setClickable(true);
7094        }
7095        if (info.isFocusable()) {
7096            structure.setFocusable(true);
7097        }
7098        if (info.isFocused()) {
7099            structure.setFocused(true);
7100        }
7101        if (info.isAccessibilityFocused()) {
7102            structure.setAccessibilityFocused(true);
7103        }
7104        if (info.isSelected()) {
7105            structure.setSelected(true);
7106        }
7107        if (info.isLongClickable()) {
7108            structure.setLongClickable(true);
7109        }
7110        if (info.isCheckable()) {
7111            structure.setCheckable(true);
7112            if (info.isChecked()) {
7113                structure.setChecked(true);
7114            }
7115        }
7116        if (info.isContextClickable()) {
7117            structure.setContextClickable(true);
7118        }
7119        CharSequence cname = info.getClassName();
7120        structure.setClassName(cname != null ? cname.toString() : null);
7121        structure.setContentDescription(info.getContentDescription());
7122        if (!sanitized && (info.getText() != null || info.getError() != null)) {
7123            // TODO(b/33197203) (b/33269702): when sanitized, try to use the Accessibility API to
7124            // just set sanitized values (like text coming from resource files), rather than not
7125            // setting it at all.
7126            structure.setText(info.getText(), info.getTextSelectionStart(),
7127                    info.getTextSelectionEnd());
7128        }
7129        final int NCHILDREN = info.getChildCount();
7130        if (NCHILDREN > 0) {
7131            structure.setChildCount(NCHILDREN);
7132            for (int i=0; i<NCHILDREN; i++) {
7133                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
7134                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
7135                ViewStructure child = structure.newChild(i);
7136                populateVirtualStructure(child, provider, cinfo, flags);
7137                cinfo.recycle();
7138            }
7139        }
7140    }
7141
7142    /**
7143     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
7144     * implementation calls {@link #onProvideStructure} and
7145     * {@link #onProvideVirtualStructure}.
7146     */
7147    public void dispatchProvideStructure(ViewStructure structure) {
7148        dispatchProvideStructureForAssistOrAutoFill(structure, 0);
7149    }
7150
7151    /**
7152     * Dispatch creation of {@link ViewStructure} down the hierarchy.
7153     *
7154     * <p>The structure must be filled according to the request type, which is set in the
7155     * {@code flags} parameter - see the documentation on each flag for more details.
7156     *
7157     * <p>The default implementation calls {@link #onProvideAutoFillStructure(ViewStructure, int)}
7158     * and {@link #onProvideAutoFillVirtualStructure(ViewStructure, int)}.
7159     *
7160     * @param structure Fill in with structured view data.
7161     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7162     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
7163     */
7164    public void dispatchProvideAutoFillStructure(ViewStructure structure, int flags) {
7165        dispatchProvideStructureForAssistOrAutoFill(structure, flags);
7166    }
7167
7168    private void dispatchProvideStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
7169        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7170        // this method should take a boolean with the type of request.
7171        boolean forAutoFill = (flags
7172                & (View.AUTO_FILL_FLAG_TYPE_FILL
7173                        | View.AUTO_FILL_FLAG_TYPE_SAVE)) != 0;
7174
7175        boolean blocked = forAutoFill ? isAutoFillBlocked() : isAssistBlocked();
7176        if (!blocked) {
7177            if (forAutoFill) {
7178                onProvideAutoFillStructure(structure, flags);
7179                onProvideAutoFillVirtualStructure(structure, flags);
7180            } else {
7181                onProvideStructure(structure);
7182                onProvideVirtualStructure(structure);
7183            }
7184        } else {
7185            structure.setClassName(getAccessibilityClassName().toString());
7186            structure.setAssistBlocked(true);
7187        }
7188    }
7189
7190    /**
7191     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
7192     *
7193     * Note: Called from the default {@link AccessibilityDelegate}.
7194     *
7195     * @hide
7196     */
7197    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
7198        if (mAttachInfo == null) {
7199            return;
7200        }
7201
7202        Rect bounds = mAttachInfo.mTmpInvalRect;
7203
7204        getDrawingRect(bounds);
7205        info.setBoundsInParent(bounds);
7206
7207        getBoundsOnScreen(bounds, true);
7208        info.setBoundsInScreen(bounds);
7209
7210        ViewParent parent = getParentForAccessibility();
7211        if (parent instanceof View) {
7212            info.setParent((View) parent);
7213        }
7214
7215        if (mID != View.NO_ID) {
7216            View rootView = getRootView();
7217            if (rootView == null) {
7218                rootView = this;
7219            }
7220
7221            View label = rootView.findLabelForView(this, mID);
7222            if (label != null) {
7223                info.setLabeledBy(label);
7224            }
7225
7226            if ((mAttachInfo.mAccessibilityFetchFlags
7227                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
7228                    && Resources.resourceHasPackage(mID)) {
7229                try {
7230                    String viewId = getResources().getResourceName(mID);
7231                    info.setViewIdResourceName(viewId);
7232                } catch (Resources.NotFoundException nfe) {
7233                    /* ignore */
7234                }
7235            }
7236        }
7237
7238        if (mLabelForId != View.NO_ID) {
7239            View rootView = getRootView();
7240            if (rootView == null) {
7241                rootView = this;
7242            }
7243            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
7244            if (labeled != null) {
7245                info.setLabelFor(labeled);
7246            }
7247        }
7248
7249        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
7250            View rootView = getRootView();
7251            if (rootView == null) {
7252                rootView = this;
7253            }
7254            View next = rootView.findViewInsideOutShouldExist(this,
7255                    mAccessibilityTraversalBeforeId);
7256            if (next != null && next.includeForAccessibility()) {
7257                info.setTraversalBefore(next);
7258            }
7259        }
7260
7261        if (mAccessibilityTraversalAfterId != View.NO_ID) {
7262            View rootView = getRootView();
7263            if (rootView == null) {
7264                rootView = this;
7265            }
7266            View next = rootView.findViewInsideOutShouldExist(this,
7267                    mAccessibilityTraversalAfterId);
7268            if (next != null && next.includeForAccessibility()) {
7269                info.setTraversalAfter(next);
7270            }
7271        }
7272
7273        info.setVisibleToUser(isVisibleToUser());
7274
7275        info.setImportantForAccessibility(isImportantForAccessibility());
7276        info.setPackageName(mContext.getPackageName());
7277        info.setClassName(getAccessibilityClassName());
7278        info.setContentDescription(getContentDescription());
7279
7280        info.setEnabled(isEnabled());
7281        info.setClickable(isClickable());
7282        info.setFocusable(isFocusable());
7283        info.setFocused(isFocused());
7284        info.setAccessibilityFocused(isAccessibilityFocused());
7285        info.setSelected(isSelected());
7286        info.setLongClickable(isLongClickable());
7287        info.setContextClickable(isContextClickable());
7288        info.setLiveRegion(getAccessibilityLiveRegion());
7289
7290        // TODO: These make sense only if we are in an AdapterView but all
7291        // views can be selected. Maybe from accessibility perspective
7292        // we should report as selectable view in an AdapterView.
7293        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
7294        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
7295
7296        if (isFocusable()) {
7297            if (isFocused()) {
7298                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
7299            } else {
7300                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
7301            }
7302        }
7303
7304        if (!isAccessibilityFocused()) {
7305            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
7306        } else {
7307            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
7308        }
7309
7310        if (isClickable() && isEnabled()) {
7311            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
7312        }
7313
7314        if (isLongClickable() && isEnabled()) {
7315            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
7316        }
7317
7318        if (isContextClickable() && isEnabled()) {
7319            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
7320        }
7321
7322        CharSequence text = getIterableTextForAccessibility();
7323        if (text != null && text.length() > 0) {
7324            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
7325
7326            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
7327            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
7328            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
7329            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
7330                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
7331                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
7332        }
7333
7334        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
7335        populateAccessibilityNodeInfoDrawingOrderInParent(info);
7336    }
7337
7338    /**
7339     * Determine the order in which this view will be drawn relative to its siblings for a11y
7340     *
7341     * @param info The info whose drawing order should be populated
7342     */
7343    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
7344        /*
7345         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7346         * drawing order may not be well-defined, and some Views with custom drawing order may
7347         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7348         */
7349        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7350            info.setDrawingOrder(0);
7351            return;
7352        }
7353        int drawingOrderInParent = 1;
7354        // Iterate up the hierarchy if parents are not important for a11y
7355        View viewAtDrawingLevel = this;
7356        final ViewParent parent = getParentForAccessibility();
7357        while (viewAtDrawingLevel != parent) {
7358            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7359            if (!(currentParent instanceof ViewGroup)) {
7360                // Should only happen for the Decor
7361                drawingOrderInParent = 0;
7362                break;
7363            } else {
7364                final ViewGroup parentGroup = (ViewGroup) currentParent;
7365                final int childCount = parentGroup.getChildCount();
7366                if (childCount > 1) {
7367                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7368                    if (preorderedList != null) {
7369                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7370                        for (int i = 0; i < childDrawIndex; i++) {
7371                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7372                        }
7373                    } else {
7374                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7375                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7376                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7377                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7378                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
7379                        if (childDrawIndex != 0) {
7380                            for (int i = 0; i < numChildrenToIterate; i++) {
7381                                final int otherDrawIndex = (customOrder ?
7382                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
7383                                if (otherDrawIndex < childDrawIndex) {
7384                                    drawingOrderInParent +=
7385                                            numViewsForAccessibility(parentGroup.getChildAt(i));
7386                                }
7387                            }
7388                        }
7389                    }
7390                }
7391            }
7392            viewAtDrawingLevel = (View) currentParent;
7393        }
7394        info.setDrawingOrder(drawingOrderInParent);
7395    }
7396
7397    private static int numViewsForAccessibility(View view) {
7398        if (view != null) {
7399            if (view.includeForAccessibility()) {
7400                return 1;
7401            } else if (view instanceof ViewGroup) {
7402                return ((ViewGroup) view).getNumChildrenForAccessibility();
7403            }
7404        }
7405        return 0;
7406    }
7407
7408    private View findLabelForView(View view, int labeledId) {
7409        if (mMatchLabelForPredicate == null) {
7410            mMatchLabelForPredicate = new MatchLabelForPredicate();
7411        }
7412        mMatchLabelForPredicate.mLabeledId = labeledId;
7413        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7414    }
7415
7416    /**
7417     * Computes whether this view is visible to the user. Such a view is
7418     * attached, visible, all its predecessors are visible, it is not clipped
7419     * entirely by its predecessors, and has an alpha greater than zero.
7420     *
7421     * @return Whether the view is visible on the screen.
7422     *
7423     * @hide
7424     */
7425    protected boolean isVisibleToUser() {
7426        return isVisibleToUser(null);
7427    }
7428
7429    /**
7430     * Computes whether the given portion of this view is visible to the user.
7431     * Such a view is attached, visible, all its predecessors are visible,
7432     * has an alpha greater than zero, and the specified portion is not
7433     * clipped entirely by its predecessors.
7434     *
7435     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7436     *                    <code>null</code>, and the entire view will be tested in this case.
7437     *                    When <code>true</code> is returned by the function, the actual visible
7438     *                    region will be stored in this parameter; that is, if boundInView is fully
7439     *                    contained within the view, no modification will be made, otherwise regions
7440     *                    outside of the visible area of the view will be clipped.
7441     *
7442     * @return Whether the specified portion of the view is visible on the screen.
7443     *
7444     * @hide
7445     */
7446    protected boolean isVisibleToUser(Rect boundInView) {
7447        if (mAttachInfo != null) {
7448            // Attached to invisible window means this view is not visible.
7449            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7450                return false;
7451            }
7452            // An invisible predecessor or one with alpha zero means
7453            // that this view is not visible to the user.
7454            Object current = this;
7455            while (current instanceof View) {
7456                View view = (View) current;
7457                // We have attach info so this view is attached and there is no
7458                // need to check whether we reach to ViewRootImpl on the way up.
7459                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7460                        view.getVisibility() != VISIBLE) {
7461                    return false;
7462                }
7463                current = view.mParent;
7464            }
7465            // Check if the view is entirely covered by its predecessors.
7466            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7467            Point offset = mAttachInfo.mPoint;
7468            if (!getGlobalVisibleRect(visibleRect, offset)) {
7469                return false;
7470            }
7471            // Check if the visible portion intersects the rectangle of interest.
7472            if (boundInView != null) {
7473                visibleRect.offset(-offset.x, -offset.y);
7474                return boundInView.intersect(visibleRect);
7475            }
7476            return true;
7477        }
7478        return false;
7479    }
7480
7481    /**
7482     * Returns the delegate for implementing accessibility support via
7483     * composition. For more details see {@link AccessibilityDelegate}.
7484     *
7485     * @return The delegate, or null if none set.
7486     *
7487     * @hide
7488     */
7489    public AccessibilityDelegate getAccessibilityDelegate() {
7490        return mAccessibilityDelegate;
7491    }
7492
7493    /**
7494     * Sets a delegate for implementing accessibility support via composition
7495     * (as opposed to inheritance). For more details, see
7496     * {@link AccessibilityDelegate}.
7497     * <p>
7498     * <strong>Note:</strong> On platform versions prior to
7499     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7500     * views in the {@code android.widget.*} package are called <i>before</i>
7501     * host methods. This prevents certain properties such as class name from
7502     * being modified by overriding
7503     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7504     * as any changes will be overwritten by the host class.
7505     * <p>
7506     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7507     * methods are called <i>after</i> host methods, which all properties to be
7508     * modified without being overwritten by the host class.
7509     *
7510     * @param delegate the object to which accessibility method calls should be
7511     *                 delegated
7512     * @see AccessibilityDelegate
7513     */
7514    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7515        mAccessibilityDelegate = delegate;
7516    }
7517
7518    /**
7519     * Gets the provider for managing a virtual view hierarchy rooted at this View
7520     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7521     * that explore the window content.
7522     * <p>
7523     * If this method returns an instance, this instance is responsible for managing
7524     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7525     * View including the one representing the View itself. Similarly the returned
7526     * instance is responsible for performing accessibility actions on any virtual
7527     * view or the root view itself.
7528     * </p>
7529     * <p>
7530     * If an {@link AccessibilityDelegate} has been specified via calling
7531     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7532     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7533     * is responsible for handling this call.
7534     * </p>
7535     *
7536     * @return The provider.
7537     *
7538     * @see AccessibilityNodeProvider
7539     */
7540    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7541        if (mAccessibilityDelegate != null) {
7542            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7543        } else {
7544            return null;
7545        }
7546    }
7547
7548    /**
7549     * Gets the unique identifier of this view on the screen for accessibility purposes.
7550     *
7551     * @return The view accessibility id.
7552     *
7553     * @hide
7554     */
7555    public int getAccessibilityViewId() {
7556        if (mAccessibilityViewId == NO_ID) {
7557            mAccessibilityViewId = sNextAccessibilityViewId++;
7558        }
7559        return mAccessibilityViewId;
7560    }
7561
7562    /**
7563     * Gets the unique identifier of the window in which this View reseides.
7564     *
7565     * @return The window accessibility id.
7566     *
7567     * @hide
7568     */
7569    public int getAccessibilityWindowId() {
7570        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7571                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7572    }
7573
7574    /**
7575     * Returns the {@link View}'s content description.
7576     * <p>
7577     * <strong>Note:</strong> Do not override this method, as it will have no
7578     * effect on the content description presented to accessibility services.
7579     * You must call {@link #setContentDescription(CharSequence)} to modify the
7580     * content description.
7581     *
7582     * @return the content description
7583     * @see #setContentDescription(CharSequence)
7584     * @attr ref android.R.styleable#View_contentDescription
7585     */
7586    @ViewDebug.ExportedProperty(category = "accessibility")
7587    public CharSequence getContentDescription() {
7588        return mContentDescription;
7589    }
7590
7591    /**
7592     * Sets the {@link View}'s content description.
7593     * <p>
7594     * A content description briefly describes the view and is primarily used
7595     * for accessibility support to determine how a view should be presented to
7596     * the user. In the case of a view with no textual representation, such as
7597     * {@link android.widget.ImageButton}, a useful content description
7598     * explains what the view does. For example, an image button with a phone
7599     * icon that is used to place a call may use "Call" as its content
7600     * description. An image of a floppy disk that is used to save a file may
7601     * use "Save".
7602     *
7603     * @param contentDescription The content description.
7604     * @see #getContentDescription()
7605     * @attr ref android.R.styleable#View_contentDescription
7606     */
7607    @RemotableViewMethod
7608    public void setContentDescription(CharSequence contentDescription) {
7609        if (mContentDescription == null) {
7610            if (contentDescription == null) {
7611                return;
7612            }
7613        } else if (mContentDescription.equals(contentDescription)) {
7614            return;
7615        }
7616        mContentDescription = contentDescription;
7617        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7618        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7619            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7620            notifySubtreeAccessibilityStateChangedIfNeeded();
7621        } else {
7622            notifyViewAccessibilityStateChangedIfNeeded(
7623                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7624        }
7625    }
7626
7627    /**
7628     * Sets the id of a view before which this one is visited in accessibility traversal.
7629     * A screen-reader must visit the content of this view before the content of the one
7630     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7631     * will traverse the entire content of B before traversing the entire content of A,
7632     * regardles of what traversal strategy it is using.
7633     * <p>
7634     * Views that do not have specified before/after relationships are traversed in order
7635     * determined by the screen-reader.
7636     * </p>
7637     * <p>
7638     * Setting that this view is before a view that is not important for accessibility
7639     * or if this view is not important for accessibility will have no effect as the
7640     * screen-reader is not aware of unimportant views.
7641     * </p>
7642     *
7643     * @param beforeId The id of a view this one precedes in accessibility traversal.
7644     *
7645     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7646     *
7647     * @see #setImportantForAccessibility(int)
7648     */
7649    @RemotableViewMethod
7650    public void setAccessibilityTraversalBefore(int beforeId) {
7651        if (mAccessibilityTraversalBeforeId == beforeId) {
7652            return;
7653        }
7654        mAccessibilityTraversalBeforeId = beforeId;
7655        notifyViewAccessibilityStateChangedIfNeeded(
7656                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7657    }
7658
7659    /**
7660     * Gets the id of a view before which this one is visited in accessibility traversal.
7661     *
7662     * @return The id of a view this one precedes in accessibility traversal if
7663     *         specified, otherwise {@link #NO_ID}.
7664     *
7665     * @see #setAccessibilityTraversalBefore(int)
7666     */
7667    public int getAccessibilityTraversalBefore() {
7668        return mAccessibilityTraversalBeforeId;
7669    }
7670
7671    /**
7672     * Sets the id of a view after which this one is visited in accessibility traversal.
7673     * A screen-reader must visit the content of the other view before the content of this
7674     * one. For example, if view B is set to be after view A, then a screen-reader
7675     * will traverse the entire content of A before traversing the entire content of B,
7676     * regardles of what traversal strategy it is using.
7677     * <p>
7678     * Views that do not have specified before/after relationships are traversed in order
7679     * determined by the screen-reader.
7680     * </p>
7681     * <p>
7682     * Setting that this view is after a view that is not important for accessibility
7683     * or if this view is not important for accessibility will have no effect as the
7684     * screen-reader is not aware of unimportant views.
7685     * </p>
7686     *
7687     * @param afterId The id of a view this one succedees in accessibility traversal.
7688     *
7689     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7690     *
7691     * @see #setImportantForAccessibility(int)
7692     */
7693    @RemotableViewMethod
7694    public void setAccessibilityTraversalAfter(int afterId) {
7695        if (mAccessibilityTraversalAfterId == afterId) {
7696            return;
7697        }
7698        mAccessibilityTraversalAfterId = afterId;
7699        notifyViewAccessibilityStateChangedIfNeeded(
7700                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7701    }
7702
7703    /**
7704     * Gets the id of a view after which this one is visited in accessibility traversal.
7705     *
7706     * @return The id of a view this one succeedes in accessibility traversal if
7707     *         specified, otherwise {@link #NO_ID}.
7708     *
7709     * @see #setAccessibilityTraversalAfter(int)
7710     */
7711    public int getAccessibilityTraversalAfter() {
7712        return mAccessibilityTraversalAfterId;
7713    }
7714
7715    /**
7716     * Gets the id of a view for which this view serves as a label for
7717     * accessibility purposes.
7718     *
7719     * @return The labeled view id.
7720     */
7721    @ViewDebug.ExportedProperty(category = "accessibility")
7722    public int getLabelFor() {
7723        return mLabelForId;
7724    }
7725
7726    /**
7727     * Sets the id of a view for which this view serves as a label for
7728     * accessibility purposes.
7729     *
7730     * @param id The labeled view id.
7731     */
7732    @RemotableViewMethod
7733    public void setLabelFor(@IdRes int id) {
7734        if (mLabelForId == id) {
7735            return;
7736        }
7737        mLabelForId = id;
7738        if (mLabelForId != View.NO_ID
7739                && mID == View.NO_ID) {
7740            mID = generateViewId();
7741        }
7742        notifyViewAccessibilityStateChangedIfNeeded(
7743                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7744    }
7745
7746    /**
7747     * Invoked whenever this view loses focus, either by losing window focus or by losing
7748     * focus within its window. This method can be used to clear any state tied to the
7749     * focus. For instance, if a button is held pressed with the trackball and the window
7750     * loses focus, this method can be used to cancel the press.
7751     *
7752     * Subclasses of View overriding this method should always call super.onFocusLost().
7753     *
7754     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7755     * @see #onWindowFocusChanged(boolean)
7756     *
7757     * @hide pending API council approval
7758     */
7759    @CallSuper
7760    protected void onFocusLost() {
7761        resetPressedState();
7762    }
7763
7764    private void resetPressedState() {
7765        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7766            return;
7767        }
7768
7769        if (isPressed()) {
7770            setPressed(false);
7771
7772            if (!mHasPerformedLongPress) {
7773                removeLongPressCallback();
7774            }
7775        }
7776    }
7777
7778    /**
7779     * Returns true if this view has focus
7780     *
7781     * @return True if this view has focus, false otherwise.
7782     */
7783    @ViewDebug.ExportedProperty(category = "focus")
7784    public boolean isFocused() {
7785        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7786    }
7787
7788    /**
7789     * Find the view in the hierarchy rooted at this view that currently has
7790     * focus.
7791     *
7792     * @return The view that currently has focus, or null if no focused view can
7793     *         be found.
7794     */
7795    public View findFocus() {
7796        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7797    }
7798
7799    /**
7800     * Indicates whether this view is one of the set of scrollable containers in
7801     * its window.
7802     *
7803     * @return whether this view is one of the set of scrollable containers in
7804     * its window
7805     *
7806     * @attr ref android.R.styleable#View_isScrollContainer
7807     */
7808    public boolean isScrollContainer() {
7809        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7810    }
7811
7812    /**
7813     * Change whether this view is one of the set of scrollable containers in
7814     * its window.  This will be used to determine whether the window can
7815     * resize or must pan when a soft input area is open -- scrollable
7816     * containers allow the window to use resize mode since the container
7817     * will appropriately shrink.
7818     *
7819     * @attr ref android.R.styleable#View_isScrollContainer
7820     */
7821    public void setScrollContainer(boolean isScrollContainer) {
7822        if (isScrollContainer) {
7823            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7824                mAttachInfo.mScrollContainers.add(this);
7825                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7826            }
7827            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7828        } else {
7829            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7830                mAttachInfo.mScrollContainers.remove(this);
7831            }
7832            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7833        }
7834    }
7835
7836    /**
7837     * Returns the quality of the drawing cache.
7838     *
7839     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7840     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7841     *
7842     * @see #setDrawingCacheQuality(int)
7843     * @see #setDrawingCacheEnabled(boolean)
7844     * @see #isDrawingCacheEnabled()
7845     *
7846     * @attr ref android.R.styleable#View_drawingCacheQuality
7847     */
7848    @DrawingCacheQuality
7849    public int getDrawingCacheQuality() {
7850        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7851    }
7852
7853    /**
7854     * Set the drawing cache quality of this view. This value is used only when the
7855     * drawing cache is enabled
7856     *
7857     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7858     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7859     *
7860     * @see #getDrawingCacheQuality()
7861     * @see #setDrawingCacheEnabled(boolean)
7862     * @see #isDrawingCacheEnabled()
7863     *
7864     * @attr ref android.R.styleable#View_drawingCacheQuality
7865     */
7866    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7867        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7868    }
7869
7870    /**
7871     * Returns whether the screen should remain on, corresponding to the current
7872     * value of {@link #KEEP_SCREEN_ON}.
7873     *
7874     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7875     *
7876     * @see #setKeepScreenOn(boolean)
7877     *
7878     * @attr ref android.R.styleable#View_keepScreenOn
7879     */
7880    public boolean getKeepScreenOn() {
7881        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7882    }
7883
7884    /**
7885     * Controls whether the screen should remain on, modifying the
7886     * value of {@link #KEEP_SCREEN_ON}.
7887     *
7888     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7889     *
7890     * @see #getKeepScreenOn()
7891     *
7892     * @attr ref android.R.styleable#View_keepScreenOn
7893     */
7894    public void setKeepScreenOn(boolean keepScreenOn) {
7895        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7896    }
7897
7898    /**
7899     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7900     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7901     *
7902     * @attr ref android.R.styleable#View_nextFocusLeft
7903     */
7904    public int getNextFocusLeftId() {
7905        return mNextFocusLeftId;
7906    }
7907
7908    /**
7909     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7910     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7911     * decide automatically.
7912     *
7913     * @attr ref android.R.styleable#View_nextFocusLeft
7914     */
7915    public void setNextFocusLeftId(int nextFocusLeftId) {
7916        mNextFocusLeftId = nextFocusLeftId;
7917    }
7918
7919    /**
7920     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7921     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7922     *
7923     * @attr ref android.R.styleable#View_nextFocusRight
7924     */
7925    public int getNextFocusRightId() {
7926        return mNextFocusRightId;
7927    }
7928
7929    /**
7930     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7931     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7932     * decide automatically.
7933     *
7934     * @attr ref android.R.styleable#View_nextFocusRight
7935     */
7936    public void setNextFocusRightId(int nextFocusRightId) {
7937        mNextFocusRightId = nextFocusRightId;
7938    }
7939
7940    /**
7941     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7942     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7943     *
7944     * @attr ref android.R.styleable#View_nextFocusUp
7945     */
7946    public int getNextFocusUpId() {
7947        return mNextFocusUpId;
7948    }
7949
7950    /**
7951     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7952     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7953     * decide automatically.
7954     *
7955     * @attr ref android.R.styleable#View_nextFocusUp
7956     */
7957    public void setNextFocusUpId(int nextFocusUpId) {
7958        mNextFocusUpId = nextFocusUpId;
7959    }
7960
7961    /**
7962     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7963     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7964     *
7965     * @attr ref android.R.styleable#View_nextFocusDown
7966     */
7967    public int getNextFocusDownId() {
7968        return mNextFocusDownId;
7969    }
7970
7971    /**
7972     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7973     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7974     * decide automatically.
7975     *
7976     * @attr ref android.R.styleable#View_nextFocusDown
7977     */
7978    public void setNextFocusDownId(int nextFocusDownId) {
7979        mNextFocusDownId = nextFocusDownId;
7980    }
7981
7982    /**
7983     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7984     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7985     *
7986     * @attr ref android.R.styleable#View_nextFocusForward
7987     */
7988    public int getNextFocusForwardId() {
7989        return mNextFocusForwardId;
7990    }
7991
7992    /**
7993     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7994     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7995     * decide automatically.
7996     *
7997     * @attr ref android.R.styleable#View_nextFocusForward
7998     */
7999    public void setNextFocusForwardId(int nextFocusForwardId) {
8000        mNextFocusForwardId = nextFocusForwardId;
8001    }
8002
8003    /**
8004     * Gets the id of the root of the next keyboard navigation cluster.
8005     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
8006     * decide automatically.
8007     *
8008     * @attr ref android.R.styleable#View_nextClusterForward
8009     */
8010    public int getNextClusterForwardId() {
8011        return mNextClusterForwardId;
8012    }
8013
8014    /**
8015     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
8016     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
8017     * decide automatically.
8018     *
8019     * @attr ref android.R.styleable#View_nextClusterForward
8020     */
8021    public void setNextClusterForwardId(int nextClusterForwardId) {
8022        mNextClusterForwardId = nextClusterForwardId;
8023    }
8024
8025    /**
8026     * Returns the visibility of this view and all of its ancestors
8027     *
8028     * @return True if this view and all of its ancestors are {@link #VISIBLE}
8029     */
8030    public boolean isShown() {
8031        View current = this;
8032        //noinspection ConstantConditions
8033        do {
8034            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8035                return false;
8036            }
8037            ViewParent parent = current.mParent;
8038            if (parent == null) {
8039                return false; // We are not attached to the view root
8040            }
8041            if (!(parent instanceof View)) {
8042                return true;
8043            }
8044            current = (View) parent;
8045        } while (current != null);
8046
8047        return false;
8048    }
8049
8050    /**
8051     * Called by the view hierarchy when the content insets for a window have
8052     * changed, to allow it to adjust its content to fit within those windows.
8053     * The content insets tell you the space that the status bar, input method,
8054     * and other system windows infringe on the application's window.
8055     *
8056     * <p>You do not normally need to deal with this function, since the default
8057     * window decoration given to applications takes care of applying it to the
8058     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
8059     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
8060     * and your content can be placed under those system elements.  You can then
8061     * use this method within your view hierarchy if you have parts of your UI
8062     * which you would like to ensure are not being covered.
8063     *
8064     * <p>The default implementation of this method simply applies the content
8065     * insets to the view's padding, consuming that content (modifying the
8066     * insets to be 0), and returning true.  This behavior is off by default, but can
8067     * be enabled through {@link #setFitsSystemWindows(boolean)}.
8068     *
8069     * <p>This function's traversal down the hierarchy is depth-first.  The same content
8070     * insets object is propagated down the hierarchy, so any changes made to it will
8071     * be seen by all following views (including potentially ones above in
8072     * the hierarchy since this is a depth-first traversal).  The first view
8073     * that returns true will abort the entire traversal.
8074     *
8075     * <p>The default implementation works well for a situation where it is
8076     * used with a container that covers the entire window, allowing it to
8077     * apply the appropriate insets to its content on all edges.  If you need
8078     * a more complicated layout (such as two different views fitting system
8079     * windows, one on the top of the window, and one on the bottom),
8080     * you can override the method and handle the insets however you would like.
8081     * Note that the insets provided by the framework are always relative to the
8082     * far edges of the window, not accounting for the location of the called view
8083     * within that window.  (In fact when this method is called you do not yet know
8084     * where the layout will place the view, as it is done before layout happens.)
8085     *
8086     * <p>Note: unlike many View methods, there is no dispatch phase to this
8087     * call.  If you are overriding it in a ViewGroup and want to allow the
8088     * call to continue to your children, you must be sure to call the super
8089     * implementation.
8090     *
8091     * <p>Here is a sample layout that makes use of fitting system windows
8092     * to have controls for a video view placed inside of the window decorations
8093     * that it hides and shows.  This can be used with code like the second
8094     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
8095     *
8096     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
8097     *
8098     * @param insets Current content insets of the window.  Prior to
8099     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
8100     * the insets or else you and Android will be unhappy.
8101     *
8102     * @return {@code true} if this view applied the insets and it should not
8103     * continue propagating further down the hierarchy, {@code false} otherwise.
8104     * @see #getFitsSystemWindows()
8105     * @see #setFitsSystemWindows(boolean)
8106     * @see #setSystemUiVisibility(int)
8107     *
8108     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
8109     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
8110     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
8111     * to implement handling their own insets.
8112     */
8113    @Deprecated
8114    protected boolean fitSystemWindows(Rect insets) {
8115        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
8116            if (insets == null) {
8117                // Null insets by definition have already been consumed.
8118                // This call cannot apply insets since there are none to apply,
8119                // so return false.
8120                return false;
8121            }
8122            // If we're not in the process of dispatching the newer apply insets call,
8123            // that means we're not in the compatibility path. Dispatch into the newer
8124            // apply insets path and take things from there.
8125            try {
8126                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
8127                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
8128            } finally {
8129                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
8130            }
8131        } else {
8132            // We're being called from the newer apply insets path.
8133            // Perform the standard fallback behavior.
8134            return fitSystemWindowsInt(insets);
8135        }
8136    }
8137
8138    private boolean fitSystemWindowsInt(Rect insets) {
8139        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
8140            mUserPaddingStart = UNDEFINED_PADDING;
8141            mUserPaddingEnd = UNDEFINED_PADDING;
8142            Rect localInsets = sThreadLocal.get();
8143            if (localInsets == null) {
8144                localInsets = new Rect();
8145                sThreadLocal.set(localInsets);
8146            }
8147            boolean res = computeFitSystemWindows(insets, localInsets);
8148            mUserPaddingLeftInitial = localInsets.left;
8149            mUserPaddingRightInitial = localInsets.right;
8150            internalSetPadding(localInsets.left, localInsets.top,
8151                    localInsets.right, localInsets.bottom);
8152            return res;
8153        }
8154        return false;
8155    }
8156
8157    /**
8158     * Called when the view should apply {@link WindowInsets} according to its internal policy.
8159     *
8160     * <p>This method should be overridden by views that wish to apply a policy different from or
8161     * in addition to the default behavior. Clients that wish to force a view subtree
8162     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
8163     *
8164     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
8165     * it will be called during dispatch instead of this method. The listener may optionally
8166     * call this method from its own implementation if it wishes to apply the view's default
8167     * insets policy in addition to its own.</p>
8168     *
8169     * <p>Implementations of this method should either return the insets parameter unchanged
8170     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
8171     * that this view applied itself. This allows new inset types added in future platform
8172     * versions to pass through existing implementations unchanged without being erroneously
8173     * consumed.</p>
8174     *
8175     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
8176     * property is set then the view will consume the system window insets and apply them
8177     * as padding for the view.</p>
8178     *
8179     * @param insets Insets to apply
8180     * @return The supplied insets with any applied insets consumed
8181     */
8182    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
8183        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
8184            // We weren't called from within a direct call to fitSystemWindows,
8185            // call into it as a fallback in case we're in a class that overrides it
8186            // and has logic to perform.
8187            if (fitSystemWindows(insets.getSystemWindowInsets())) {
8188                return insets.consumeSystemWindowInsets();
8189            }
8190        } else {
8191            // We were called from within a direct call to fitSystemWindows.
8192            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
8193                return insets.consumeSystemWindowInsets();
8194            }
8195        }
8196        return insets;
8197    }
8198
8199    /**
8200     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
8201     * window insets to this view. The listener's
8202     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
8203     * method will be called instead of the view's
8204     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
8205     *
8206     * @param listener Listener to set
8207     *
8208     * @see #onApplyWindowInsets(WindowInsets)
8209     */
8210    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
8211        getListenerInfo().mOnApplyWindowInsetsListener = listener;
8212    }
8213
8214    /**
8215     * Request to apply the given window insets to this view or another view in its subtree.
8216     *
8217     * <p>This method should be called by clients wishing to apply insets corresponding to areas
8218     * obscured by window decorations or overlays. This can include the status and navigation bars,
8219     * action bars, input methods and more. New inset categories may be added in the future.
8220     * The method returns the insets provided minus any that were applied by this view or its
8221     * children.</p>
8222     *
8223     * <p>Clients wishing to provide custom behavior should override the
8224     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
8225     * {@link OnApplyWindowInsetsListener} via the
8226     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
8227     * method.</p>
8228     *
8229     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
8230     * </p>
8231     *
8232     * @param insets Insets to apply
8233     * @return The provided insets minus the insets that were consumed
8234     */
8235    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
8236        try {
8237            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
8238            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
8239                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
8240            } else {
8241                return onApplyWindowInsets(insets);
8242            }
8243        } finally {
8244            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
8245        }
8246    }
8247
8248    /**
8249     * Compute the view's coordinate within the surface.
8250     *
8251     * <p>Computes the coordinates of this view in its surface. The argument
8252     * must be an array of two integers. After the method returns, the array
8253     * contains the x and y location in that order.</p>
8254     * @hide
8255     * @param location an array of two integers in which to hold the coordinates
8256     */
8257    public void getLocationInSurface(@Size(2) int[] location) {
8258        getLocationInWindow(location);
8259        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
8260            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
8261            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
8262        }
8263    }
8264
8265    /**
8266     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
8267     * only available if the view is attached.
8268     *
8269     * @return WindowInsets from the top of the view hierarchy or null if View is detached
8270     */
8271    public WindowInsets getRootWindowInsets() {
8272        if (mAttachInfo != null) {
8273            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
8274        }
8275        return null;
8276    }
8277
8278    /**
8279     * @hide Compute the insets that should be consumed by this view and the ones
8280     * that should propagate to those under it.
8281     */
8282    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
8283        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8284                || mAttachInfo == null
8285                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
8286                        && !mAttachInfo.mOverscanRequested)) {
8287            outLocalInsets.set(inoutInsets);
8288            inoutInsets.set(0, 0, 0, 0);
8289            return true;
8290        } else {
8291            // The application wants to take care of fitting system window for
8292            // the content...  however we still need to take care of any overscan here.
8293            final Rect overscan = mAttachInfo.mOverscanInsets;
8294            outLocalInsets.set(overscan);
8295            inoutInsets.left -= overscan.left;
8296            inoutInsets.top -= overscan.top;
8297            inoutInsets.right -= overscan.right;
8298            inoutInsets.bottom -= overscan.bottom;
8299            return false;
8300        }
8301    }
8302
8303    /**
8304     * Compute insets that should be consumed by this view and the ones that should propagate
8305     * to those under it.
8306     *
8307     * @param in Insets currently being processed by this View, likely received as a parameter
8308     *           to {@link #onApplyWindowInsets(WindowInsets)}.
8309     * @param outLocalInsets A Rect that will receive the insets that should be consumed
8310     *                       by this view
8311     * @return Insets that should be passed along to views under this one
8312     */
8313    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
8314        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8315                || mAttachInfo == null
8316                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
8317            outLocalInsets.set(in.getSystemWindowInsets());
8318            return in.consumeSystemWindowInsets();
8319        } else {
8320            outLocalInsets.set(0, 0, 0, 0);
8321            return in;
8322        }
8323    }
8324
8325    /**
8326     * Sets whether or not this view should account for system screen decorations
8327     * such as the status bar and inset its content; that is, controlling whether
8328     * the default implementation of {@link #fitSystemWindows(Rect)} will be
8329     * executed.  See that method for more details.
8330     *
8331     * <p>Note that if you are providing your own implementation of
8332     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
8333     * flag to true -- your implementation will be overriding the default
8334     * implementation that checks this flag.
8335     *
8336     * @param fitSystemWindows If true, then the default implementation of
8337     * {@link #fitSystemWindows(Rect)} will be executed.
8338     *
8339     * @attr ref android.R.styleable#View_fitsSystemWindows
8340     * @see #getFitsSystemWindows()
8341     * @see #fitSystemWindows(Rect)
8342     * @see #setSystemUiVisibility(int)
8343     */
8344    public void setFitsSystemWindows(boolean fitSystemWindows) {
8345        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
8346    }
8347
8348    /**
8349     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
8350     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
8351     * will be executed.
8352     *
8353     * @return {@code true} if the default implementation of
8354     * {@link #fitSystemWindows(Rect)} will be executed.
8355     *
8356     * @attr ref android.R.styleable#View_fitsSystemWindows
8357     * @see #setFitsSystemWindows(boolean)
8358     * @see #fitSystemWindows(Rect)
8359     * @see #setSystemUiVisibility(int)
8360     */
8361    @ViewDebug.ExportedProperty
8362    public boolean getFitsSystemWindows() {
8363        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
8364    }
8365
8366    /** @hide */
8367    public boolean fitsSystemWindows() {
8368        return getFitsSystemWindows();
8369    }
8370
8371    /**
8372     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8373     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8374     */
8375    @Deprecated
8376    public void requestFitSystemWindows() {
8377        if (mParent != null) {
8378            mParent.requestFitSystemWindows();
8379        }
8380    }
8381
8382    /**
8383     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
8384     */
8385    public void requestApplyInsets() {
8386        requestFitSystemWindows();
8387    }
8388
8389    /**
8390     * For use by PhoneWindow to make its own system window fitting optional.
8391     * @hide
8392     */
8393    public void makeOptionalFitsSystemWindows() {
8394        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
8395    }
8396
8397    /**
8398     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
8399     * treat them as such.
8400     * @hide
8401     */
8402    public void getOutsets(Rect outOutsetRect) {
8403        if (mAttachInfo != null) {
8404            outOutsetRect.set(mAttachInfo.mOutsets);
8405        } else {
8406            outOutsetRect.setEmpty();
8407        }
8408    }
8409
8410    /**
8411     * Returns the visibility status for this view.
8412     *
8413     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8414     * @attr ref android.R.styleable#View_visibility
8415     */
8416    @ViewDebug.ExportedProperty(mapping = {
8417        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
8418        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
8419        @ViewDebug.IntToString(from = GONE,      to = "GONE")
8420    })
8421    @Visibility
8422    public int getVisibility() {
8423        return mViewFlags & VISIBILITY_MASK;
8424    }
8425
8426    /**
8427     * Set the visibility state of this view.
8428     *
8429     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8430     * @attr ref android.R.styleable#View_visibility
8431     */
8432    @RemotableViewMethod
8433    public void setVisibility(@Visibility int visibility) {
8434        setFlags(visibility, VISIBILITY_MASK);
8435    }
8436
8437    /**
8438     * Returns the enabled status for this view. The interpretation of the
8439     * enabled state varies by subclass.
8440     *
8441     * @return True if this view is enabled, false otherwise.
8442     */
8443    @ViewDebug.ExportedProperty
8444    public boolean isEnabled() {
8445        return (mViewFlags & ENABLED_MASK) == ENABLED;
8446    }
8447
8448    /**
8449     * Set the enabled state of this view. The interpretation of the enabled
8450     * state varies by subclass.
8451     *
8452     * @param enabled True if this view is enabled, false otherwise.
8453     */
8454    @RemotableViewMethod
8455    public void setEnabled(boolean enabled) {
8456        if (enabled == isEnabled()) return;
8457
8458        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8459
8460        /*
8461         * The View most likely has to change its appearance, so refresh
8462         * the drawable state.
8463         */
8464        refreshDrawableState();
8465
8466        // Invalidate too, since the default behavior for views is to be
8467        // be drawn at 50% alpha rather than to change the drawable.
8468        invalidate(true);
8469
8470        if (!enabled) {
8471            cancelPendingInputEvents();
8472        }
8473    }
8474
8475    /**
8476     * Set whether this view can receive the focus.
8477     * <p>
8478     * Setting this to false will also ensure that this view is not focusable
8479     * in touch mode.
8480     *
8481     * @param focusable If true, this view can receive the focus.
8482     *
8483     * @see #setFocusableInTouchMode(boolean)
8484     * @see #setFocusable(int)
8485     * @attr ref android.R.styleable#View_focusable
8486     */
8487    public void setFocusable(boolean focusable) {
8488        setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
8489    }
8490
8491    /**
8492     * Sets whether this view can receive focus.
8493     * <p>
8494     * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
8495     * automatically based on the view's interactivity. This is the default.
8496     * <p>
8497     * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
8498     * in touch mode.
8499     *
8500     * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
8501     *                  or {@link #FOCUSABLE_AUTO}.
8502     * @see #setFocusableInTouchMode(boolean)
8503     * @attr ref android.R.styleable#View_focusable
8504     */
8505    public void setFocusable(@Focusable int focusable) {
8506        if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
8507            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8508        }
8509        setFlags(focusable, FOCUSABLE_MASK);
8510    }
8511
8512    /**
8513     * Set whether this view can receive focus while in touch mode.
8514     *
8515     * Setting this to true will also ensure that this view is focusable.
8516     *
8517     * @param focusableInTouchMode If true, this view can receive the focus while
8518     *   in touch mode.
8519     *
8520     * @see #setFocusable(boolean)
8521     * @attr ref android.R.styleable#View_focusableInTouchMode
8522     */
8523    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8524        // Focusable in touch mode should always be set before the focusable flag
8525        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8526        // which, in touch mode, will not successfully request focus on this view
8527        // because the focusable in touch mode flag is not set
8528        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8529        if (focusableInTouchMode) {
8530            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8531        }
8532    }
8533
8534    /**
8535     * Set whether this view should have sound effects enabled for events such as
8536     * clicking and touching.
8537     *
8538     * <p>You may wish to disable sound effects for a view if you already play sounds,
8539     * for instance, a dial key that plays dtmf tones.
8540     *
8541     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8542     * @see #isSoundEffectsEnabled()
8543     * @see #playSoundEffect(int)
8544     * @attr ref android.R.styleable#View_soundEffectsEnabled
8545     */
8546    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8547        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8548    }
8549
8550    /**
8551     * @return whether this view should have sound effects enabled for events such as
8552     *     clicking and touching.
8553     *
8554     * @see #setSoundEffectsEnabled(boolean)
8555     * @see #playSoundEffect(int)
8556     * @attr ref android.R.styleable#View_soundEffectsEnabled
8557     */
8558    @ViewDebug.ExportedProperty
8559    public boolean isSoundEffectsEnabled() {
8560        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8561    }
8562
8563    /**
8564     * Set whether this view should have haptic feedback for events such as
8565     * long presses.
8566     *
8567     * <p>You may wish to disable haptic feedback if your view already controls
8568     * its own haptic feedback.
8569     *
8570     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8571     * @see #isHapticFeedbackEnabled()
8572     * @see #performHapticFeedback(int)
8573     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8574     */
8575    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8576        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8577    }
8578
8579    /**
8580     * @return whether this view should have haptic feedback enabled for events
8581     * long presses.
8582     *
8583     * @see #setHapticFeedbackEnabled(boolean)
8584     * @see #performHapticFeedback(int)
8585     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8586     */
8587    @ViewDebug.ExportedProperty
8588    public boolean isHapticFeedbackEnabled() {
8589        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8590    }
8591
8592    /**
8593     * Returns the layout direction for this view.
8594     *
8595     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8596     *   {@link #LAYOUT_DIRECTION_RTL},
8597     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8598     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8599     *
8600     * @attr ref android.R.styleable#View_layoutDirection
8601     *
8602     * @hide
8603     */
8604    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8605        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8606        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8607        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8608        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8609    })
8610    @LayoutDir
8611    public int getRawLayoutDirection() {
8612        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8613    }
8614
8615    /**
8616     * Set the layout direction for this view. This will propagate a reset of layout direction
8617     * resolution to the view's children and resolve layout direction for this view.
8618     *
8619     * @param layoutDirection the layout direction to set. Should be one of:
8620     *
8621     * {@link #LAYOUT_DIRECTION_LTR},
8622     * {@link #LAYOUT_DIRECTION_RTL},
8623     * {@link #LAYOUT_DIRECTION_INHERIT},
8624     * {@link #LAYOUT_DIRECTION_LOCALE}.
8625     *
8626     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8627     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8628     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8629     *
8630     * @attr ref android.R.styleable#View_layoutDirection
8631     */
8632    @RemotableViewMethod
8633    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8634        if (getRawLayoutDirection() != layoutDirection) {
8635            // Reset the current layout direction and the resolved one
8636            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8637            resetRtlProperties();
8638            // Set the new layout direction (filtered)
8639            mPrivateFlags2 |=
8640                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8641            // We need to resolve all RTL properties as they all depend on layout direction
8642            resolveRtlPropertiesIfNeeded();
8643            requestLayout();
8644            invalidate(true);
8645        }
8646    }
8647
8648    /**
8649     * Returns the resolved layout direction for this view.
8650     *
8651     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8652     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8653     *
8654     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8655     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8656     *
8657     * @attr ref android.R.styleable#View_layoutDirection
8658     */
8659    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8660        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8661        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8662    })
8663    @ResolvedLayoutDir
8664    public int getLayoutDirection() {
8665        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8666        if (targetSdkVersion < JELLY_BEAN_MR1) {
8667            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8668            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8669        }
8670        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8671                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8672    }
8673
8674    /**
8675     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8676     * layout attribute and/or the inherited value from the parent
8677     *
8678     * @return true if the layout is right-to-left.
8679     *
8680     * @hide
8681     */
8682    @ViewDebug.ExportedProperty(category = "layout")
8683    public boolean isLayoutRtl() {
8684        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8685    }
8686
8687    /**
8688     * Indicates whether the view is currently tracking transient state that the
8689     * app should not need to concern itself with saving and restoring, but that
8690     * the framework should take special note to preserve when possible.
8691     *
8692     * <p>A view with transient state cannot be trivially rebound from an external
8693     * data source, such as an adapter binding item views in a list. This may be
8694     * because the view is performing an animation, tracking user selection
8695     * of content, or similar.</p>
8696     *
8697     * @return true if the view has transient state
8698     */
8699    @ViewDebug.ExportedProperty(category = "layout")
8700    public boolean hasTransientState() {
8701        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8702    }
8703
8704    /**
8705     * Set whether this view is currently tracking transient state that the
8706     * framework should attempt to preserve when possible. This flag is reference counted,
8707     * so every call to setHasTransientState(true) should be paired with a later call
8708     * to setHasTransientState(false).
8709     *
8710     * <p>A view with transient state cannot be trivially rebound from an external
8711     * data source, such as an adapter binding item views in a list. This may be
8712     * because the view is performing an animation, tracking user selection
8713     * of content, or similar.</p>
8714     *
8715     * @param hasTransientState true if this view has transient state
8716     */
8717    public void setHasTransientState(boolean hasTransientState) {
8718        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8719                mTransientStateCount - 1;
8720        if (mTransientStateCount < 0) {
8721            mTransientStateCount = 0;
8722            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8723                    "unmatched pair of setHasTransientState calls");
8724        } else if ((hasTransientState && mTransientStateCount == 1) ||
8725                (!hasTransientState && mTransientStateCount == 0)) {
8726            // update flag if we've just incremented up from 0 or decremented down to 0
8727            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8728                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8729            if (mParent != null) {
8730                try {
8731                    mParent.childHasTransientStateChanged(this, hasTransientState);
8732                } catch (AbstractMethodError e) {
8733                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8734                            " does not fully implement ViewParent", e);
8735                }
8736            }
8737        }
8738    }
8739
8740    /**
8741     * Returns true if this view is currently attached to a window.
8742     */
8743    public boolean isAttachedToWindow() {
8744        return mAttachInfo != null;
8745    }
8746
8747    /**
8748     * Returns true if this view has been through at least one layout since it
8749     * was last attached to or detached from a window.
8750     */
8751    public boolean isLaidOut() {
8752        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8753    }
8754
8755    /**
8756     * If this view doesn't do any drawing on its own, set this flag to
8757     * allow further optimizations. By default, this flag is not set on
8758     * View, but could be set on some View subclasses such as ViewGroup.
8759     *
8760     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8761     * you should clear this flag.
8762     *
8763     * @param willNotDraw whether or not this View draw on its own
8764     */
8765    public void setWillNotDraw(boolean willNotDraw) {
8766        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8767    }
8768
8769    /**
8770     * Returns whether or not this View draws on its own.
8771     *
8772     * @return true if this view has nothing to draw, false otherwise
8773     */
8774    @ViewDebug.ExportedProperty(category = "drawing")
8775    public boolean willNotDraw() {
8776        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8777    }
8778
8779    /**
8780     * When a View's drawing cache is enabled, drawing is redirected to an
8781     * offscreen bitmap. Some views, like an ImageView, must be able to
8782     * bypass this mechanism if they already draw a single bitmap, to avoid
8783     * unnecessary usage of the memory.
8784     *
8785     * @param willNotCacheDrawing true if this view does not cache its
8786     *        drawing, false otherwise
8787     */
8788    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8789        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8790    }
8791
8792    /**
8793     * Returns whether or not this View can cache its drawing or not.
8794     *
8795     * @return true if this view does not cache its drawing, false otherwise
8796     */
8797    @ViewDebug.ExportedProperty(category = "drawing")
8798    public boolean willNotCacheDrawing() {
8799        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8800    }
8801
8802    /**
8803     * Indicates whether this view reacts to click events or not.
8804     *
8805     * @return true if the view is clickable, false otherwise
8806     *
8807     * @see #setClickable(boolean)
8808     * @attr ref android.R.styleable#View_clickable
8809     */
8810    @ViewDebug.ExportedProperty
8811    public boolean isClickable() {
8812        return (mViewFlags & CLICKABLE) == CLICKABLE;
8813    }
8814
8815    /**
8816     * Enables or disables click events for this view. When a view
8817     * is clickable it will change its state to "pressed" on every click.
8818     * Subclasses should set the view clickable to visually react to
8819     * user's clicks.
8820     *
8821     * @param clickable true to make the view clickable, false otherwise
8822     *
8823     * @see #isClickable()
8824     * @attr ref android.R.styleable#View_clickable
8825     */
8826    public void setClickable(boolean clickable) {
8827        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8828    }
8829
8830    /**
8831     * Indicates whether this view reacts to long click events or not.
8832     *
8833     * @return true if the view is long clickable, false otherwise
8834     *
8835     * @see #setLongClickable(boolean)
8836     * @attr ref android.R.styleable#View_longClickable
8837     */
8838    public boolean isLongClickable() {
8839        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8840    }
8841
8842    /**
8843     * Enables or disables long click events for this view. When a view is long
8844     * clickable it reacts to the user holding down the button for a longer
8845     * duration than a tap. This event can either launch the listener or a
8846     * context menu.
8847     *
8848     * @param longClickable true to make the view long clickable, false otherwise
8849     * @see #isLongClickable()
8850     * @attr ref android.R.styleable#View_longClickable
8851     */
8852    public void setLongClickable(boolean longClickable) {
8853        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8854    }
8855
8856    /**
8857     * Indicates whether this view reacts to context clicks or not.
8858     *
8859     * @return true if the view is context clickable, false otherwise
8860     * @see #setContextClickable(boolean)
8861     * @attr ref android.R.styleable#View_contextClickable
8862     */
8863    public boolean isContextClickable() {
8864        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8865    }
8866
8867    /**
8868     * Enables or disables context clicking for this view. This event can launch the listener.
8869     *
8870     * @param contextClickable true to make the view react to a context click, false otherwise
8871     * @see #isContextClickable()
8872     * @attr ref android.R.styleable#View_contextClickable
8873     */
8874    public void setContextClickable(boolean contextClickable) {
8875        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8876    }
8877
8878    /**
8879     * Sets the pressed state for this view and provides a touch coordinate for
8880     * animation hinting.
8881     *
8882     * @param pressed Pass true to set the View's internal state to "pressed",
8883     *            or false to reverts the View's internal state from a
8884     *            previously set "pressed" state.
8885     * @param x The x coordinate of the touch that caused the press
8886     * @param y The y coordinate of the touch that caused the press
8887     */
8888    private void setPressed(boolean pressed, float x, float y) {
8889        if (pressed) {
8890            drawableHotspotChanged(x, y);
8891        }
8892
8893        setPressed(pressed);
8894    }
8895
8896    /**
8897     * Sets the pressed state for this view.
8898     *
8899     * @see #isClickable()
8900     * @see #setClickable(boolean)
8901     *
8902     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8903     *        the View's internal state from a previously set "pressed" state.
8904     */
8905    public void setPressed(boolean pressed) {
8906        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8907
8908        if (pressed) {
8909            mPrivateFlags |= PFLAG_PRESSED;
8910        } else {
8911            mPrivateFlags &= ~PFLAG_PRESSED;
8912        }
8913
8914        if (needsRefresh) {
8915            refreshDrawableState();
8916        }
8917        dispatchSetPressed(pressed);
8918    }
8919
8920    /**
8921     * Dispatch setPressed to all of this View's children.
8922     *
8923     * @see #setPressed(boolean)
8924     *
8925     * @param pressed The new pressed state
8926     */
8927    protected void dispatchSetPressed(boolean pressed) {
8928    }
8929
8930    /**
8931     * Indicates whether the view is currently in pressed state. Unless
8932     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8933     * the pressed state.
8934     *
8935     * @see #setPressed(boolean)
8936     * @see #isClickable()
8937     * @see #setClickable(boolean)
8938     *
8939     * @return true if the view is currently pressed, false otherwise
8940     */
8941    @ViewDebug.ExportedProperty
8942    public boolean isPressed() {
8943        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8944    }
8945
8946    /**
8947     * @hide
8948     * Indicates whether this view will participate in data collection through
8949     * {@link ViewStructure}.  If true, it will not provide any data
8950     * for itself or its children.  If false, the normal data collection will be allowed.
8951     *
8952     * @return Returns false if assist data collection is not blocked, else true.
8953     *
8954     * @see #setAssistBlocked(boolean)
8955     * @attr ref android.R.styleable#View_assistBlocked
8956     */
8957    public boolean isAssistBlocked() {
8958        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8959    }
8960
8961    /**
8962     * @hide
8963     * Indicates whether this view will participate in data collection through
8964     * {@link ViewStructure} for auto-fill purposes.
8965     *
8966     * <p>If {@code true}, it will not provide any data for itself or its children.
8967     * <p>If {@code false}, the normal data collection will be allowed.
8968     *
8969     * @return Returns {@code false} if assist data collection for auto-fill is not blocked,
8970     * else {@code true}.
8971     *
8972     * TODO(b/33197203): update / remove javadoc tags below
8973     * @see #setAssistBlocked(boolean)
8974     * @attr ref android.R.styleable#View_assistBlocked
8975     */
8976    public boolean isAutoFillBlocked() {
8977        return false; // TODO(b/33197203): properly implement it
8978    }
8979
8980    /**
8981     * @hide
8982     * Controls whether assist data collection from this view and its children is enabled
8983     * (that is, whether {@link #onProvideStructure} and
8984     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8985     * allowing normal assist collection.  Setting this to false will disable assist collection.
8986     *
8987     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8988     * (the default) to allow it.
8989     *
8990     * @see #isAssistBlocked()
8991     * @see #onProvideStructure
8992     * @see #onProvideVirtualStructure
8993     * @attr ref android.R.styleable#View_assistBlocked
8994     */
8995    public void setAssistBlocked(boolean enabled) {
8996        if (enabled) {
8997            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8998        } else {
8999            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
9000        }
9001    }
9002
9003    /**
9004     * Indicates whether this view will save its state (that is,
9005     * whether its {@link #onSaveInstanceState} method will be called).
9006     *
9007     * @return Returns true if the view state saving is enabled, else false.
9008     *
9009     * @see #setSaveEnabled(boolean)
9010     * @attr ref android.R.styleable#View_saveEnabled
9011     */
9012    public boolean isSaveEnabled() {
9013        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
9014    }
9015
9016    /**
9017     * Controls whether the saving of this view's state is
9018     * enabled (that is, whether its {@link #onSaveInstanceState} method
9019     * will be called).  Note that even if freezing is enabled, the
9020     * view still must have an id assigned to it (via {@link #setId(int)})
9021     * for its state to be saved.  This flag can only disable the
9022     * saving of this view; any child views may still have their state saved.
9023     *
9024     * @param enabled Set to false to <em>disable</em> state saving, or true
9025     * (the default) to allow it.
9026     *
9027     * @see #isSaveEnabled()
9028     * @see #setId(int)
9029     * @see #onSaveInstanceState()
9030     * @attr ref android.R.styleable#View_saveEnabled
9031     */
9032    public void setSaveEnabled(boolean enabled) {
9033        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
9034    }
9035
9036    /**
9037     * Gets whether the framework should discard touches when the view's
9038     * window is obscured by another visible window.
9039     * Refer to the {@link View} security documentation for more details.
9040     *
9041     * @return True if touch filtering is enabled.
9042     *
9043     * @see #setFilterTouchesWhenObscured(boolean)
9044     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9045     */
9046    @ViewDebug.ExportedProperty
9047    public boolean getFilterTouchesWhenObscured() {
9048        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
9049    }
9050
9051    /**
9052     * Sets whether the framework should discard touches when the view's
9053     * window is obscured by another visible window.
9054     * Refer to the {@link View} security documentation for more details.
9055     *
9056     * @param enabled True if touch filtering should be enabled.
9057     *
9058     * @see #getFilterTouchesWhenObscured
9059     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9060     */
9061    public void setFilterTouchesWhenObscured(boolean enabled) {
9062        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
9063                FILTER_TOUCHES_WHEN_OBSCURED);
9064    }
9065
9066    /**
9067     * Indicates whether the entire hierarchy under this view will save its
9068     * state when a state saving traversal occurs from its parent.  The default
9069     * is true; if false, these views will not be saved unless
9070     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9071     *
9072     * @return Returns true if the view state saving from parent is enabled, else false.
9073     *
9074     * @see #setSaveFromParentEnabled(boolean)
9075     */
9076    public boolean isSaveFromParentEnabled() {
9077        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
9078    }
9079
9080    /**
9081     * Controls whether the entire hierarchy under this view will save its
9082     * state when a state saving traversal occurs from its parent.  The default
9083     * is true; if false, these views will not be saved unless
9084     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9085     *
9086     * @param enabled Set to false to <em>disable</em> state saving, or true
9087     * (the default) to allow it.
9088     *
9089     * @see #isSaveFromParentEnabled()
9090     * @see #setId(int)
9091     * @see #onSaveInstanceState()
9092     */
9093    public void setSaveFromParentEnabled(boolean enabled) {
9094        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
9095    }
9096
9097
9098    /**
9099     * Returns whether this View is currently able to take focus.
9100     *
9101     * @return True if this view can take focus, or false otherwise.
9102     */
9103    @ViewDebug.ExportedProperty(category = "focus")
9104    public final boolean isFocusable() {
9105        return FOCUSABLE == (mViewFlags & FOCUSABLE);
9106    }
9107
9108    /**
9109     * Returns the focusable setting for this view.
9110     *
9111     * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}.
9112     * @attr ref android.R.styleable#View_focusable
9113     */
9114    @ViewDebug.ExportedProperty(mapping = {
9115            @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"),
9116            @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"),
9117            @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO")
9118            })
9119    @Focusable
9120    public int getFocusable() {
9121        return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
9122    }
9123
9124    /**
9125     * When a view is focusable, it may not want to take focus when in touch mode.
9126     * For example, a button would like focus when the user is navigating via a D-pad
9127     * so that the user can click on it, but once the user starts touching the screen,
9128     * the button shouldn't take focus
9129     * @return Whether the view is focusable in touch mode.
9130     * @attr ref android.R.styleable#View_focusableInTouchMode
9131     */
9132    @ViewDebug.ExportedProperty
9133    public final boolean isFocusableInTouchMode() {
9134        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
9135    }
9136
9137    /**
9138     * Find the nearest view in the specified direction that can take focus.
9139     * This does not actually give focus to that view.
9140     *
9141     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9142     *
9143     * @return The nearest focusable in the specified direction, or null if none
9144     *         can be found.
9145     */
9146    public View focusSearch(@FocusRealDirection int direction) {
9147        if (mParent != null) {
9148            return mParent.focusSearch(this, direction);
9149        } else {
9150            return null;
9151        }
9152    }
9153
9154    /**
9155     * Returns whether this View is a root of a keyboard navigation cluster.
9156     *
9157     * @return True if this view is a root of a cluster, or false otherwise.
9158     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9159     */
9160    @ViewDebug.ExportedProperty(category = "keyboardNavigationCluster")
9161    public final boolean isKeyboardNavigationCluster() {
9162        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
9163    }
9164
9165    /**
9166     * Set whether this view is a root of a keyboard navigation cluster.
9167     *
9168     * @param isCluster If true, this view is a root of a cluster.
9169     *
9170     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9171     */
9172    public void setKeyboardNavigationCluster(boolean isCluster) {
9173        if (isCluster) {
9174            mPrivateFlags3 |= PFLAG3_CLUSTER;
9175        } else {
9176            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
9177        }
9178    }
9179
9180    /**
9181     * Returns whether this View should receive focus when the focus is restored for the view
9182     * hierarchy containing this view.
9183     * <p>
9184     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9185     * window or serves as a target of cluster navigation.
9186     *
9187     * @see #restoreDefaultFocus(int)
9188     *
9189     * @return {@code true} if this view is the default-focus view, {@code false} otherwise
9190     * @attr ref android.R.styleable#View_focusedByDefault
9191     */
9192    @ViewDebug.ExportedProperty(category = "focusedByDefault")
9193    public final boolean isFocusedByDefault() {
9194        return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
9195    }
9196
9197    /**
9198     * Sets whether this View should receive focus when the focus is restored for the view
9199     * hierarchy containing this view.
9200     * <p>
9201     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9202     * window or serves as a target of cluster navigation.
9203     *
9204     * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
9205     *                           {@code false} otherwise.
9206     *
9207     * @see #restoreDefaultFocus(int)
9208     *
9209     * @attr ref android.R.styleable#View_focusedByDefault
9210     */
9211    public void setFocusedByDefault(boolean isFocusedByDefault) {
9212        if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
9213            return;
9214        }
9215
9216        if (isFocusedByDefault) {
9217            mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
9218        } else {
9219            mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
9220        }
9221
9222        if (mParent instanceof ViewGroup) {
9223            if (isFocusedByDefault) {
9224                ((ViewGroup) mParent).setDefaultFocus(this);
9225            } else {
9226                ((ViewGroup) mParent).cleanDefaultFocus(this);
9227            }
9228        }
9229    }
9230
9231    /**
9232     * Returns whether the view hierarchy with this view as a root contain a default-focus view.
9233     *
9234     * @return {@code true} if this view has default focus, {@code false} otherwise
9235     */
9236    boolean hasDefaultFocus() {
9237        return isFocusedByDefault();
9238    }
9239
9240    /**
9241     * Find the nearest keyboard navigation cluster in the specified direction.
9242     * This does not actually give focus to that cluster.
9243     *
9244     * @param currentCluster The starting point of the search. Null means the current cluster is not
9245     *                       found yet
9246     * @param direction Direction to look
9247     *
9248     * @return The nearest keyboard navigation cluster in the specified direction, or null if none
9249     *         can be found
9250     */
9251    public View keyboardNavigationClusterSearch(View currentCluster, int direction) {
9252        if (isKeyboardNavigationCluster()) {
9253            currentCluster = this;
9254        }
9255        if (isRootNamespace()) {
9256            // Root namespace means we should consider ourselves the top of the
9257            // tree for group searching; otherwise we could be group searching
9258            // into other tabs.  see LocalActivityManager and TabHost for more info.
9259            return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
9260                    this, currentCluster, direction);
9261        } else if (mParent != null) {
9262            return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
9263        }
9264        return null;
9265    }
9266
9267    /**
9268     * This method is the last chance for the focused view and its ancestors to
9269     * respond to an arrow key. This is called when the focused view did not
9270     * consume the key internally, nor could the view system find a new view in
9271     * the requested direction to give focus to.
9272     *
9273     * @param focused The currently focused view.
9274     * @param direction The direction focus wants to move. One of FOCUS_UP,
9275     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
9276     * @return True if the this view consumed this unhandled move.
9277     */
9278    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
9279        return false;
9280    }
9281
9282    /**
9283     * If a user manually specified the next view id for a particular direction,
9284     * use the root to look up the view.
9285     * @param root The root view of the hierarchy containing this view.
9286     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
9287     * or FOCUS_BACKWARD.
9288     * @return The user specified next view, or null if there is none.
9289     */
9290    View findUserSetNextFocus(View root, @FocusDirection int direction) {
9291        switch (direction) {
9292            case FOCUS_LEFT:
9293                if (mNextFocusLeftId == View.NO_ID) return null;
9294                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
9295            case FOCUS_RIGHT:
9296                if (mNextFocusRightId == View.NO_ID) return null;
9297                return findViewInsideOutShouldExist(root, mNextFocusRightId);
9298            case FOCUS_UP:
9299                if (mNextFocusUpId == View.NO_ID) return null;
9300                return findViewInsideOutShouldExist(root, mNextFocusUpId);
9301            case FOCUS_DOWN:
9302                if (mNextFocusDownId == View.NO_ID) return null;
9303                return findViewInsideOutShouldExist(root, mNextFocusDownId);
9304            case FOCUS_FORWARD:
9305                if (mNextFocusForwardId == View.NO_ID) return null;
9306                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
9307            case FOCUS_BACKWARD: {
9308                if (mID == View.NO_ID) return null;
9309                final int id = mID;
9310                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
9311                    @Override
9312                    public boolean apply(View t) {
9313                        return t.mNextFocusForwardId == id;
9314                    }
9315                });
9316            }
9317        }
9318        return null;
9319    }
9320
9321    private View findViewInsideOutShouldExist(View root, int id) {
9322        if (mMatchIdPredicate == null) {
9323            mMatchIdPredicate = new MatchIdPredicate();
9324        }
9325        mMatchIdPredicate.mId = id;
9326        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
9327        if (result == null) {
9328            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
9329        }
9330        return result;
9331    }
9332
9333    /**
9334     * Find and return all focusable views that are descendants of this view,
9335     * possibly including this view if it is focusable itself.
9336     *
9337     * @param direction The direction of the focus
9338     * @return A list of focusable views
9339     */
9340    public ArrayList<View> getFocusables(@FocusDirection int direction) {
9341        ArrayList<View> result = new ArrayList<View>(24);
9342        addFocusables(result, direction);
9343        return result;
9344    }
9345
9346    /**
9347     * Add any focusable views that are descendants of this view (possibly
9348     * including this view if it is focusable itself) to views.  If we are in touch mode,
9349     * only add views that are also focusable in touch mode.
9350     *
9351     * @param views Focusable views found so far
9352     * @param direction The direction of the focus
9353     */
9354    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
9355        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
9356    }
9357
9358    /**
9359     * Adds any focusable views that are descendants of this view (possibly
9360     * including this view if it is focusable itself) to views. This method
9361     * adds all focusable views regardless if we are in touch mode or
9362     * only views focusable in touch mode if we are in touch mode or
9363     * only views that can take accessibility focus if accessibility is enabled
9364     * depending on the focusable mode parameter.
9365     *
9366     * @param views Focusable views found so far or null if all we are interested is
9367     *        the number of focusables.
9368     * @param direction The direction of the focus.
9369     * @param focusableMode The type of focusables to be added.
9370     *
9371     * @see #FOCUSABLES_ALL
9372     * @see #FOCUSABLES_TOUCH_MODE
9373     */
9374    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
9375            @FocusableMode int focusableMode) {
9376        if (views == null) {
9377            return;
9378        }
9379        if (!isFocusable()) {
9380            return;
9381        }
9382        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
9383                && !isFocusableInTouchMode()) {
9384            return;
9385        }
9386        views.add(this);
9387    }
9388
9389    /**
9390     * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
9391     * including this view if it is a cluster root itself) to views.
9392     *
9393     * @param views Keyboard navigation cluster roots found so far
9394     * @param direction Direction to look
9395     */
9396    public void addKeyboardNavigationClusters(
9397            @NonNull Collection<View> views,
9398            int direction) {
9399        if (!(isKeyboardNavigationCluster())) {
9400            return;
9401        }
9402        views.add(this);
9403    }
9404
9405    /**
9406     * Finds the Views that contain given text. The containment is case insensitive.
9407     * The search is performed by either the text that the View renders or the content
9408     * description that describes the view for accessibility purposes and the view does
9409     * not render or both. Clients can specify how the search is to be performed via
9410     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
9411     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
9412     *
9413     * @param outViews The output list of matching Views.
9414     * @param searched The text to match against.
9415     *
9416     * @see #FIND_VIEWS_WITH_TEXT
9417     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
9418     * @see #setContentDescription(CharSequence)
9419     */
9420    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
9421            @FindViewFlags int flags) {
9422        if (getAccessibilityNodeProvider() != null) {
9423            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
9424                outViews.add(this);
9425            }
9426        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
9427                && (searched != null && searched.length() > 0)
9428                && (mContentDescription != null && mContentDescription.length() > 0)) {
9429            String searchedLowerCase = searched.toString().toLowerCase();
9430            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
9431            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
9432                outViews.add(this);
9433            }
9434        }
9435    }
9436
9437    /**
9438     * Find and return all touchable views that are descendants of this view,
9439     * possibly including this view if it is touchable itself.
9440     *
9441     * @return A list of touchable views
9442     */
9443    public ArrayList<View> getTouchables() {
9444        ArrayList<View> result = new ArrayList<View>();
9445        addTouchables(result);
9446        return result;
9447    }
9448
9449    /**
9450     * Add any touchable views that are descendants of this view (possibly
9451     * including this view if it is touchable itself) to views.
9452     *
9453     * @param views Touchable views found so far
9454     */
9455    public void addTouchables(ArrayList<View> views) {
9456        final int viewFlags = mViewFlags;
9457
9458        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
9459                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
9460                && (viewFlags & ENABLED_MASK) == ENABLED) {
9461            views.add(this);
9462        }
9463    }
9464
9465    /**
9466     * Returns whether this View is accessibility focused.
9467     *
9468     * @return True if this View is accessibility focused.
9469     */
9470    public boolean isAccessibilityFocused() {
9471        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
9472    }
9473
9474    /**
9475     * Call this to try to give accessibility focus to this view.
9476     *
9477     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
9478     * returns false or the view is no visible or the view already has accessibility
9479     * focus.
9480     *
9481     * See also {@link #focusSearch(int)}, which is what you call to say that you
9482     * have focus, and you want your parent to look for the next one.
9483     *
9484     * @return Whether this view actually took accessibility focus.
9485     *
9486     * @hide
9487     */
9488    public boolean requestAccessibilityFocus() {
9489        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
9490        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
9491            return false;
9492        }
9493        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9494            return false;
9495        }
9496        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
9497            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
9498            ViewRootImpl viewRootImpl = getViewRootImpl();
9499            if (viewRootImpl != null) {
9500                viewRootImpl.setAccessibilityFocus(this, null);
9501            }
9502            invalidate();
9503            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
9504            return true;
9505        }
9506        return false;
9507    }
9508
9509    /**
9510     * Call this to try to clear accessibility focus of this view.
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     * @hide
9516     */
9517    public void clearAccessibilityFocus() {
9518        clearAccessibilityFocusNoCallbacks(0);
9519
9520        // Clear the global reference of accessibility focus if this view or
9521        // any of its descendants had accessibility focus. This will NOT send
9522        // an event or update internal state if focus is cleared from a
9523        // descendant view, which may leave views in inconsistent states.
9524        final ViewRootImpl viewRootImpl = getViewRootImpl();
9525        if (viewRootImpl != null) {
9526            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
9527            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9528                viewRootImpl.setAccessibilityFocus(null, null);
9529            }
9530        }
9531    }
9532
9533    private void sendAccessibilityHoverEvent(int eventType) {
9534        // Since we are not delivering to a client accessibility events from not
9535        // important views (unless the clinet request that) we need to fire the
9536        // event from the deepest view exposed to the client. As a consequence if
9537        // the user crosses a not exposed view the client will see enter and exit
9538        // of the exposed predecessor followed by and enter and exit of that same
9539        // predecessor when entering and exiting the not exposed descendant. This
9540        // is fine since the client has a clear idea which view is hovered at the
9541        // price of a couple more events being sent. This is a simple and
9542        // working solution.
9543        View source = this;
9544        while (true) {
9545            if (source.includeForAccessibility()) {
9546                source.sendAccessibilityEvent(eventType);
9547                return;
9548            }
9549            ViewParent parent = source.getParent();
9550            if (parent instanceof View) {
9551                source = (View) parent;
9552            } else {
9553                return;
9554            }
9555        }
9556    }
9557
9558    /**
9559     * Clears accessibility focus without calling any callback methods
9560     * normally invoked in {@link #clearAccessibilityFocus()}. This method
9561     * is used separately from that one for clearing accessibility focus when
9562     * giving this focus to another view.
9563     *
9564     * @param action The action, if any, that led to focus being cleared. Set to
9565     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
9566     * the window.
9567     */
9568    void clearAccessibilityFocusNoCallbacks(int action) {
9569        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
9570            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
9571            invalidate();
9572            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9573                AccessibilityEvent event = AccessibilityEvent.obtain(
9574                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
9575                event.setAction(action);
9576                if (mAccessibilityDelegate != null) {
9577                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
9578                } else {
9579                    sendAccessibilityEventUnchecked(event);
9580                }
9581            }
9582        }
9583    }
9584
9585    /**
9586     * Call this to try to give focus to a specific view or to one of its
9587     * descendants.
9588     *
9589     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9590     * false), or if it is focusable and it is not focusable in touch mode
9591     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9592     *
9593     * See also {@link #focusSearch(int)}, which is what you call to say that you
9594     * have focus, and you want your parent to look for the next one.
9595     *
9596     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
9597     * {@link #FOCUS_DOWN} and <code>null</code>.
9598     *
9599     * @return Whether this view or one of its descendants actually took focus.
9600     */
9601    public final boolean requestFocus() {
9602        return requestFocus(View.FOCUS_DOWN);
9603    }
9604
9605    /**
9606     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
9607     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
9608     * Nested keyboard navigation clusters are excluded from the hierarchy.
9609     *
9610     * @param direction The direction of the focus
9611     * @return Whether this view or one of its descendants actually took focus
9612     */
9613    public boolean restoreDefaultFocus(@FocusDirection int direction) {
9614        return requestFocus(direction);
9615    }
9616
9617    /**
9618     * Call this to try to give focus to a specific view or to one of its
9619     * descendants and give it a hint about what direction focus is heading.
9620     *
9621     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9622     * false), or if it is focusable and it is not focusable in touch mode
9623     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9624     *
9625     * See also {@link #focusSearch(int)}, which is what you call to say that you
9626     * have focus, and you want your parent to look for the next one.
9627     *
9628     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9629     * <code>null</code> set for the previously focused rectangle.
9630     *
9631     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9632     * @return Whether this view or one of its descendants actually took focus.
9633     */
9634    public final boolean requestFocus(int direction) {
9635        return requestFocus(direction, null);
9636    }
9637
9638    /**
9639     * Call this to try to give focus to a specific view or to one of its descendants
9640     * and give it hints about the direction and a specific rectangle that the focus
9641     * is coming from.  The rectangle can help give larger views a finer grained hint
9642     * about where focus is coming from, and therefore, where to show selection, or
9643     * forward focus change internally.
9644     *
9645     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9646     * false), or if it is focusable and it is not focusable in touch mode
9647     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9648     *
9649     * A View will not take focus if it is not visible.
9650     *
9651     * A View will not take focus if one of its parents has
9652     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9653     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9654     *
9655     * See also {@link #focusSearch(int)}, which is what you call to say that you
9656     * have focus, and you want your parent to look for the next one.
9657     *
9658     * You may wish to override this method if your custom {@link View} has an internal
9659     * {@link View} that it wishes to forward the request to.
9660     *
9661     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9662     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9663     *        to give a finer grained hint about where focus is coming from.  May be null
9664     *        if there is no hint.
9665     * @return Whether this view or one of its descendants actually took focus.
9666     */
9667    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9668        return requestFocusNoSearch(direction, previouslyFocusedRect);
9669    }
9670
9671    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9672        // need to be focusable
9673        if ((mViewFlags & FOCUSABLE) != FOCUSABLE
9674                || (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9675            return false;
9676        }
9677
9678        // need to be focusable in touch mode if in touch mode
9679        if (isInTouchMode() &&
9680            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9681               return false;
9682        }
9683
9684        // need to not have any parents blocking us
9685        if (hasAncestorThatBlocksDescendantFocus()) {
9686            return false;
9687        }
9688
9689        handleFocusGainInternal(direction, previouslyFocusedRect);
9690        return true;
9691    }
9692
9693    /**
9694     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9695     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9696     * touch mode to request focus when they are touched.
9697     *
9698     * @return Whether this view or one of its descendants actually took focus.
9699     *
9700     * @see #isInTouchMode()
9701     *
9702     */
9703    public final boolean requestFocusFromTouch() {
9704        // Leave touch mode if we need to
9705        if (isInTouchMode()) {
9706            ViewRootImpl viewRoot = getViewRootImpl();
9707            if (viewRoot != null) {
9708                viewRoot.ensureTouchMode(false);
9709            }
9710        }
9711        return requestFocus(View.FOCUS_DOWN);
9712    }
9713
9714    /**
9715     * @return Whether any ancestor of this view blocks descendant focus.
9716     */
9717    private boolean hasAncestorThatBlocksDescendantFocus() {
9718        final boolean focusableInTouchMode = isFocusableInTouchMode();
9719        ViewParent ancestor = mParent;
9720        while (ancestor instanceof ViewGroup) {
9721            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9722            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9723                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9724                return true;
9725            } else {
9726                ancestor = vgAncestor.getParent();
9727            }
9728        }
9729        return false;
9730    }
9731
9732    /**
9733     * Gets the mode for determining whether this View is important for accessibility.
9734     * A view is important for accessibility if it fires accessibility events and if it
9735     * is reported to accessibility services that query the screen.
9736     *
9737     * @return The mode for determining whether a view is important for accessibility, one
9738     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
9739     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
9740     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
9741     *
9742     * @attr ref android.R.styleable#View_importantForAccessibility
9743     *
9744     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9745     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9746     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9747     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9748     */
9749    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9750            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9751            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9752            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9753            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9754                    to = "noHideDescendants")
9755        })
9756    public int getImportantForAccessibility() {
9757        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9758                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9759    }
9760
9761    /**
9762     * Sets the live region mode for this view. This indicates to accessibility
9763     * services whether they should automatically notify the user about changes
9764     * to the view's content description or text, or to the content descriptions
9765     * or text of the view's children (where applicable).
9766     * <p>
9767     * For example, in a login screen with a TextView that displays an "incorrect
9768     * password" notification, that view should be marked as a live region with
9769     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9770     * <p>
9771     * To disable change notifications for this view, use
9772     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9773     * mode for most views.
9774     * <p>
9775     * To indicate that the user should be notified of changes, use
9776     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9777     * <p>
9778     * If the view's changes should interrupt ongoing speech and notify the user
9779     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9780     *
9781     * @param mode The live region mode for this view, one of:
9782     *        <ul>
9783     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9784     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9785     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9786     *        </ul>
9787     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9788     */
9789    public void setAccessibilityLiveRegion(int mode) {
9790        if (mode != getAccessibilityLiveRegion()) {
9791            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9792            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9793                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9794            notifyViewAccessibilityStateChangedIfNeeded(
9795                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9796        }
9797    }
9798
9799    /**
9800     * Gets the live region mode for this View.
9801     *
9802     * @return The live region mode for the view.
9803     *
9804     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9805     *
9806     * @see #setAccessibilityLiveRegion(int)
9807     */
9808    public int getAccessibilityLiveRegion() {
9809        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9810                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9811    }
9812
9813    /**
9814     * Sets how to determine whether this view is important for accessibility
9815     * which is if it fires accessibility events and if it is reported to
9816     * accessibility services that query the screen.
9817     *
9818     * @param mode How to determine whether this view is important for accessibility.
9819     *
9820     * @attr ref android.R.styleable#View_importantForAccessibility
9821     *
9822     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9823     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9824     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9825     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9826     */
9827    public void setImportantForAccessibility(int mode) {
9828        final int oldMode = getImportantForAccessibility();
9829        if (mode != oldMode) {
9830            final boolean hideDescendants =
9831                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9832
9833            // If this node or its descendants are no longer important, try to
9834            // clear accessibility focus.
9835            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9836                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9837                if (focusHost != null) {
9838                    focusHost.clearAccessibilityFocus();
9839                }
9840            }
9841
9842            // If we're moving between AUTO and another state, we might not need
9843            // to send a subtree changed notification. We'll store the computed
9844            // importance, since we'll need to check it later to make sure.
9845            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9846                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9847            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9848            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9849            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9850                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9851            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9852                notifySubtreeAccessibilityStateChangedIfNeeded();
9853            } else {
9854                notifyViewAccessibilityStateChangedIfNeeded(
9855                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9856            }
9857        }
9858    }
9859
9860    /**
9861     * Returns the view within this view's hierarchy that is hosting
9862     * accessibility focus.
9863     *
9864     * @param searchDescendants whether to search for focus in descendant views
9865     * @return the view hosting accessibility focus, or {@code null}
9866     */
9867    private View findAccessibilityFocusHost(boolean searchDescendants) {
9868        if (isAccessibilityFocusedViewOrHost()) {
9869            return this;
9870        }
9871
9872        if (searchDescendants) {
9873            final ViewRootImpl viewRoot = getViewRootImpl();
9874            if (viewRoot != null) {
9875                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9876                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9877                    return focusHost;
9878                }
9879            }
9880        }
9881
9882        return null;
9883    }
9884
9885    /**
9886     * Computes whether this view should be exposed for accessibility. In
9887     * general, views that are interactive or provide information are exposed
9888     * while views that serve only as containers are hidden.
9889     * <p>
9890     * If an ancestor of this view has importance
9891     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9892     * returns <code>false</code>.
9893     * <p>
9894     * Otherwise, the value is computed according to the view's
9895     * {@link #getImportantForAccessibility()} value:
9896     * <ol>
9897     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9898     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9899     * </code>
9900     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9901     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9902     * view satisfies any of the following:
9903     * <ul>
9904     * <li>Is actionable, e.g. {@link #isClickable()},
9905     * {@link #isLongClickable()}, or {@link #isFocusable()}
9906     * <li>Has an {@link AccessibilityDelegate}
9907     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9908     * {@link OnKeyListener}, etc.
9909     * <li>Is an accessibility live region, e.g.
9910     * {@link #getAccessibilityLiveRegion()} is not
9911     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9912     * </ul>
9913     * </ol>
9914     *
9915     * @return Whether the view is exposed for accessibility.
9916     * @see #setImportantForAccessibility(int)
9917     * @see #getImportantForAccessibility()
9918     */
9919    public boolean isImportantForAccessibility() {
9920        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9921                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9922        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9923                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9924            return false;
9925        }
9926
9927        // Check parent mode to ensure we're not hidden.
9928        ViewParent parent = mParent;
9929        while (parent instanceof View) {
9930            if (((View) parent).getImportantForAccessibility()
9931                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9932                return false;
9933            }
9934            parent = parent.getParent();
9935        }
9936
9937        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9938                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9939                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9940    }
9941
9942    /**
9943     * Gets the parent for accessibility purposes. Note that the parent for
9944     * accessibility is not necessary the immediate parent. It is the first
9945     * predecessor that is important for accessibility.
9946     *
9947     * @return The parent for accessibility purposes.
9948     */
9949    public ViewParent getParentForAccessibility() {
9950        if (mParent instanceof View) {
9951            View parentView = (View) mParent;
9952            if (parentView.includeForAccessibility()) {
9953                return mParent;
9954            } else {
9955                return mParent.getParentForAccessibility();
9956            }
9957        }
9958        return null;
9959    }
9960
9961    /**
9962     * Adds the children of this View relevant for accessibility to the given list
9963     * as output. Since some Views are not important for accessibility the added
9964     * child views are not necessarily direct children of this view, rather they are
9965     * the first level of descendants important for accessibility.
9966     *
9967     * @param outChildren The output list that will receive children for accessibility.
9968     */
9969    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9970
9971    }
9972
9973    /**
9974     * Whether to regard this view for accessibility. A view is regarded for
9975     * accessibility if it is important for accessibility or the querying
9976     * accessibility service has explicitly requested that view not
9977     * important for accessibility are regarded.
9978     *
9979     * @return Whether to regard the view for accessibility.
9980     *
9981     * @hide
9982     */
9983    public boolean includeForAccessibility() {
9984        if (mAttachInfo != null) {
9985            return (mAttachInfo.mAccessibilityFetchFlags
9986                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9987                    || isImportantForAccessibility();
9988        }
9989        return false;
9990    }
9991
9992    /**
9993     * Returns whether the View is considered actionable from
9994     * accessibility perspective. Such view are important for
9995     * accessibility.
9996     *
9997     * @return True if the view is actionable for accessibility.
9998     *
9999     * @hide
10000     */
10001    public boolean isActionableForAccessibility() {
10002        return (isClickable() || isLongClickable() || isFocusable());
10003    }
10004
10005    /**
10006     * Returns whether the View has registered callbacks which makes it
10007     * important for accessibility.
10008     *
10009     * @return True if the view is actionable for accessibility.
10010     */
10011    private boolean hasListenersForAccessibility() {
10012        ListenerInfo info = getListenerInfo();
10013        return mTouchDelegate != null || info.mOnKeyListener != null
10014                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
10015                || info.mOnHoverListener != null || info.mOnDragListener != null;
10016    }
10017
10018    /**
10019     * Notifies that the accessibility state of this view changed. The change
10020     * is local to this view and does not represent structural changes such
10021     * as children and parent. For example, the view became focusable. The
10022     * notification is at at most once every
10023     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10024     * to avoid unnecessary load to the system. Also once a view has a pending
10025     * notification this method is a NOP until the notification has been sent.
10026     *
10027     * @hide
10028     */
10029    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
10030        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10031            return;
10032        }
10033        if (mSendViewStateChangedAccessibilityEvent == null) {
10034            mSendViewStateChangedAccessibilityEvent =
10035                    new SendViewStateChangedAccessibilityEvent();
10036        }
10037        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
10038    }
10039
10040    /**
10041     * Notifies that the accessibility state of this view changed. The change
10042     * is *not* local to this view and does represent structural changes such
10043     * as children and parent. For example, the view size changed. The
10044     * notification is at at most once every
10045     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10046     * to avoid unnecessary load to the system. Also once a view has a pending
10047     * notification this method is a NOP until the notification has been sent.
10048     *
10049     * @hide
10050     */
10051    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
10052        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10053            return;
10054        }
10055        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
10056            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10057            if (mParent != null) {
10058                try {
10059                    mParent.notifySubtreeAccessibilityStateChanged(
10060                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
10061                } catch (AbstractMethodError e) {
10062                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10063                            " does not fully implement ViewParent", e);
10064                }
10065            }
10066        }
10067    }
10068
10069    /**
10070     * Change the visibility of the View without triggering any other changes. This is
10071     * important for transitions, where visibility changes should not adjust focus or
10072     * trigger a new layout. This is only used when the visibility has already been changed
10073     * and we need a transient value during an animation. When the animation completes,
10074     * the original visibility value is always restored.
10075     *
10076     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
10077     * @hide
10078     */
10079    public void setTransitionVisibility(@Visibility int visibility) {
10080        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
10081    }
10082
10083    /**
10084     * Reset the flag indicating the accessibility state of the subtree rooted
10085     * at this view changed.
10086     */
10087    void resetSubtreeAccessibilityStateChanged() {
10088        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10089    }
10090
10091    /**
10092     * Report an accessibility action to this view's parents for delegated processing.
10093     *
10094     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
10095     * call this method to delegate an accessibility action to a supporting parent. If the parent
10096     * returns true from its
10097     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
10098     * method this method will return true to signify that the action was consumed.</p>
10099     *
10100     * <p>This method is useful for implementing nested scrolling child views. If
10101     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
10102     * a custom view implementation may invoke this method to allow a parent to consume the
10103     * scroll first. If this method returns true the custom view should skip its own scrolling
10104     * behavior.</p>
10105     *
10106     * @param action Accessibility action to delegate
10107     * @param arguments Optional action arguments
10108     * @return true if the action was consumed by a parent
10109     */
10110    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
10111        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
10112            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
10113                return true;
10114            }
10115        }
10116        return false;
10117    }
10118
10119    /**
10120     * Performs the specified accessibility action on the view. For
10121     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
10122     * <p>
10123     * If an {@link AccessibilityDelegate} has been specified via calling
10124     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
10125     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
10126     * is responsible for handling this call.
10127     * </p>
10128     *
10129     * <p>The default implementation will delegate
10130     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
10131     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
10132     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
10133     *
10134     * @param action The action to perform.
10135     * @param arguments Optional action arguments.
10136     * @return Whether the action was performed.
10137     */
10138    public boolean performAccessibilityAction(int action, Bundle arguments) {
10139      if (mAccessibilityDelegate != null) {
10140          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
10141      } else {
10142          return performAccessibilityActionInternal(action, arguments);
10143      }
10144    }
10145
10146   /**
10147    * @see #performAccessibilityAction(int, Bundle)
10148    *
10149    * Note: Called from the default {@link AccessibilityDelegate}.
10150    *
10151    * @hide
10152    */
10153    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
10154        if (isNestedScrollingEnabled()
10155                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
10156                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
10157                || action == R.id.accessibilityActionScrollUp
10158                || action == R.id.accessibilityActionScrollLeft
10159                || action == R.id.accessibilityActionScrollDown
10160                || action == R.id.accessibilityActionScrollRight)) {
10161            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
10162                return true;
10163            }
10164        }
10165
10166        switch (action) {
10167            case AccessibilityNodeInfo.ACTION_CLICK: {
10168                if (isClickable()) {
10169                    performClick();
10170                    return true;
10171                }
10172            } break;
10173            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
10174                if (isLongClickable()) {
10175                    performLongClick();
10176                    return true;
10177                }
10178            } break;
10179            case AccessibilityNodeInfo.ACTION_FOCUS: {
10180                if (!hasFocus()) {
10181                    // Get out of touch mode since accessibility
10182                    // wants to move focus around.
10183                    getViewRootImpl().ensureTouchMode(false);
10184                    return requestFocus();
10185                }
10186            } break;
10187            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
10188                if (hasFocus()) {
10189                    clearFocus();
10190                    return !isFocused();
10191                }
10192            } break;
10193            case AccessibilityNodeInfo.ACTION_SELECT: {
10194                if (!isSelected()) {
10195                    setSelected(true);
10196                    return isSelected();
10197                }
10198            } break;
10199            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
10200                if (isSelected()) {
10201                    setSelected(false);
10202                    return !isSelected();
10203                }
10204            } break;
10205            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
10206                if (!isAccessibilityFocused()) {
10207                    return requestAccessibilityFocus();
10208                }
10209            } break;
10210            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
10211                if (isAccessibilityFocused()) {
10212                    clearAccessibilityFocus();
10213                    return true;
10214                }
10215            } break;
10216            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
10217                if (arguments != null) {
10218                    final int granularity = arguments.getInt(
10219                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10220                    final boolean extendSelection = arguments.getBoolean(
10221                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10222                    return traverseAtGranularity(granularity, true, extendSelection);
10223                }
10224            } break;
10225            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
10226                if (arguments != null) {
10227                    final int granularity = arguments.getInt(
10228                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10229                    final boolean extendSelection = arguments.getBoolean(
10230                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10231                    return traverseAtGranularity(granularity, false, extendSelection);
10232                }
10233            } break;
10234            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
10235                CharSequence text = getIterableTextForAccessibility();
10236                if (text == null) {
10237                    return false;
10238                }
10239                final int start = (arguments != null) ? arguments.getInt(
10240                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
10241                final int end = (arguments != null) ? arguments.getInt(
10242                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
10243                // Only cursor position can be specified (selection length == 0)
10244                if ((getAccessibilitySelectionStart() != start
10245                        || getAccessibilitySelectionEnd() != end)
10246                        && (start == end)) {
10247                    setAccessibilitySelection(start, end);
10248                    notifyViewAccessibilityStateChangedIfNeeded(
10249                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10250                    return true;
10251                }
10252            } break;
10253            case R.id.accessibilityActionShowOnScreen: {
10254                if (mAttachInfo != null) {
10255                    final Rect r = mAttachInfo.mTmpInvalRect;
10256                    getDrawingRect(r);
10257                    return requestRectangleOnScreen(r, true);
10258                }
10259            } break;
10260            case R.id.accessibilityActionContextClick: {
10261                if (isContextClickable()) {
10262                    performContextClick();
10263                    return true;
10264                }
10265            } break;
10266        }
10267        return false;
10268    }
10269
10270    private boolean traverseAtGranularity(int granularity, boolean forward,
10271            boolean extendSelection) {
10272        CharSequence text = getIterableTextForAccessibility();
10273        if (text == null || text.length() == 0) {
10274            return false;
10275        }
10276        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
10277        if (iterator == null) {
10278            return false;
10279        }
10280        int current = getAccessibilitySelectionEnd();
10281        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10282            current = forward ? 0 : text.length();
10283        }
10284        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
10285        if (range == null) {
10286            return false;
10287        }
10288        final int segmentStart = range[0];
10289        final int segmentEnd = range[1];
10290        int selectionStart;
10291        int selectionEnd;
10292        if (extendSelection && isAccessibilitySelectionExtendable()) {
10293            selectionStart = getAccessibilitySelectionStart();
10294            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10295                selectionStart = forward ? segmentStart : segmentEnd;
10296            }
10297            selectionEnd = forward ? segmentEnd : segmentStart;
10298        } else {
10299            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
10300        }
10301        setAccessibilitySelection(selectionStart, selectionEnd);
10302        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
10303                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
10304        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
10305        return true;
10306    }
10307
10308    /**
10309     * Gets the text reported for accessibility purposes.
10310     *
10311     * @return The accessibility text.
10312     *
10313     * @hide
10314     */
10315    public CharSequence getIterableTextForAccessibility() {
10316        return getContentDescription();
10317    }
10318
10319    /**
10320     * Gets whether accessibility selection can be extended.
10321     *
10322     * @return If selection is extensible.
10323     *
10324     * @hide
10325     */
10326    public boolean isAccessibilitySelectionExtendable() {
10327        return false;
10328    }
10329
10330    /**
10331     * @hide
10332     */
10333    public int getAccessibilitySelectionStart() {
10334        return mAccessibilityCursorPosition;
10335    }
10336
10337    /**
10338     * @hide
10339     */
10340    public int getAccessibilitySelectionEnd() {
10341        return getAccessibilitySelectionStart();
10342    }
10343
10344    /**
10345     * @hide
10346     */
10347    public void setAccessibilitySelection(int start, int end) {
10348        if (start ==  end && end == mAccessibilityCursorPosition) {
10349            return;
10350        }
10351        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
10352            mAccessibilityCursorPosition = start;
10353        } else {
10354            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
10355        }
10356        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
10357    }
10358
10359    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
10360            int fromIndex, int toIndex) {
10361        if (mParent == null) {
10362            return;
10363        }
10364        AccessibilityEvent event = AccessibilityEvent.obtain(
10365                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
10366        onInitializeAccessibilityEvent(event);
10367        onPopulateAccessibilityEvent(event);
10368        event.setFromIndex(fromIndex);
10369        event.setToIndex(toIndex);
10370        event.setAction(action);
10371        event.setMovementGranularity(granularity);
10372        mParent.requestSendAccessibilityEvent(this, event);
10373    }
10374
10375    /**
10376     * @hide
10377     */
10378    public TextSegmentIterator getIteratorForGranularity(int granularity) {
10379        switch (granularity) {
10380            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
10381                CharSequence text = getIterableTextForAccessibility();
10382                if (text != null && text.length() > 0) {
10383                    CharacterTextSegmentIterator iterator =
10384                        CharacterTextSegmentIterator.getInstance(
10385                                mContext.getResources().getConfiguration().locale);
10386                    iterator.initialize(text.toString());
10387                    return iterator;
10388                }
10389            } break;
10390            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
10391                CharSequence text = getIterableTextForAccessibility();
10392                if (text != null && text.length() > 0) {
10393                    WordTextSegmentIterator iterator =
10394                        WordTextSegmentIterator.getInstance(
10395                                mContext.getResources().getConfiguration().locale);
10396                    iterator.initialize(text.toString());
10397                    return iterator;
10398                }
10399            } break;
10400            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
10401                CharSequence text = getIterableTextForAccessibility();
10402                if (text != null && text.length() > 0) {
10403                    ParagraphTextSegmentIterator iterator =
10404                        ParagraphTextSegmentIterator.getInstance();
10405                    iterator.initialize(text.toString());
10406                    return iterator;
10407                }
10408            } break;
10409        }
10410        return null;
10411    }
10412
10413    /**
10414     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
10415     * and {@link #onFinishTemporaryDetach()}.
10416     *
10417     * <p>This method always returns {@code true} when called directly or indirectly from
10418     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
10419     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
10420     * <ul>
10421     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
10422     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
10423     * </ul>
10424     * </p>
10425     *
10426     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
10427     * and {@link #onFinishTemporaryDetach()}.
10428     */
10429    public final boolean isTemporarilyDetached() {
10430        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
10431    }
10432
10433    /**
10434     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
10435     * a container View.
10436     */
10437    @CallSuper
10438    public void dispatchStartTemporaryDetach() {
10439        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
10440        onStartTemporaryDetach();
10441    }
10442
10443    /**
10444     * This is called when a container is going to temporarily detach a child, with
10445     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
10446     * It will either be followed by {@link #onFinishTemporaryDetach()} or
10447     * {@link #onDetachedFromWindow()} when the container is done.
10448     */
10449    public void onStartTemporaryDetach() {
10450        removeUnsetPressCallback();
10451        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
10452    }
10453
10454    /**
10455     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
10456     * a container View.
10457     */
10458    @CallSuper
10459    public void dispatchFinishTemporaryDetach() {
10460        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
10461        onFinishTemporaryDetach();
10462        if (hasWindowFocus() && hasFocus()) {
10463            InputMethodManager.getInstance().focusIn(this);
10464        }
10465    }
10466
10467    /**
10468     * Called after {@link #onStartTemporaryDetach} when the container is done
10469     * changing the view.
10470     */
10471    public void onFinishTemporaryDetach() {
10472    }
10473
10474    /**
10475     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
10476     * for this view's window.  Returns null if the view is not currently attached
10477     * to the window.  Normally you will not need to use this directly, but
10478     * just use the standard high-level event callbacks like
10479     * {@link #onKeyDown(int, KeyEvent)}.
10480     */
10481    public KeyEvent.DispatcherState getKeyDispatcherState() {
10482        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
10483    }
10484
10485    /**
10486     * Dispatch a key event before it is processed by any input method
10487     * associated with the view hierarchy.  This can be used to intercept
10488     * key events in special situations before the IME consumes them; a
10489     * typical example would be handling the BACK key to update the application's
10490     * UI instead of allowing the IME to see it and close itself.
10491     *
10492     * @param event The key event to be dispatched.
10493     * @return True if the event was handled, false otherwise.
10494     */
10495    public boolean dispatchKeyEventPreIme(KeyEvent event) {
10496        return onKeyPreIme(event.getKeyCode(), event);
10497    }
10498
10499    /**
10500     * Dispatch a key event to the next view on the focus path. This path runs
10501     * from the top of the view tree down to the currently focused view. If this
10502     * view has focus, it will dispatch to itself. Otherwise it will dispatch
10503     * the next node down the focus path. This method also fires any key
10504     * listeners.
10505     *
10506     * @param event The key event to be dispatched.
10507     * @return True if the event was handled, false otherwise.
10508     */
10509    public boolean dispatchKeyEvent(KeyEvent event) {
10510        if (mInputEventConsistencyVerifier != null) {
10511            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
10512        }
10513
10514        // Give any attached key listener a first crack at the event.
10515        //noinspection SimplifiableIfStatement
10516        ListenerInfo li = mListenerInfo;
10517        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10518                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
10519            return true;
10520        }
10521
10522        if (event.dispatch(this, mAttachInfo != null
10523                ? mAttachInfo.mKeyDispatchState : null, this)) {
10524            return true;
10525        }
10526
10527        if (mInputEventConsistencyVerifier != null) {
10528            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10529        }
10530        return false;
10531    }
10532
10533    /**
10534     * Dispatches a key shortcut event.
10535     *
10536     * @param event The key event to be dispatched.
10537     * @return True if the event was handled by the view, false otherwise.
10538     */
10539    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
10540        return onKeyShortcut(event.getKeyCode(), event);
10541    }
10542
10543    /**
10544     * Pass the touch screen motion event down to the target view, or this
10545     * view if it is the target.
10546     *
10547     * @param event The motion event to be dispatched.
10548     * @return True if the event was handled by the view, false otherwise.
10549     */
10550    public boolean dispatchTouchEvent(MotionEvent event) {
10551        // If the event should be handled by accessibility focus first.
10552        if (event.isTargetAccessibilityFocus()) {
10553            // We don't have focus or no virtual descendant has it, do not handle the event.
10554            if (!isAccessibilityFocusedViewOrHost()) {
10555                return false;
10556            }
10557            // We have focus and got the event, then use normal event dispatch.
10558            event.setTargetAccessibilityFocus(false);
10559        }
10560
10561        boolean result = false;
10562
10563        if (mInputEventConsistencyVerifier != null) {
10564            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
10565        }
10566
10567        final int actionMasked = event.getActionMasked();
10568        if (actionMasked == MotionEvent.ACTION_DOWN) {
10569            // Defensive cleanup for new gesture
10570            stopNestedScroll();
10571        }
10572
10573        if (onFilterTouchEventForSecurity(event)) {
10574            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
10575                result = true;
10576            }
10577            //noinspection SimplifiableIfStatement
10578            ListenerInfo li = mListenerInfo;
10579            if (li != null && li.mOnTouchListener != null
10580                    && (mViewFlags & ENABLED_MASK) == ENABLED
10581                    && li.mOnTouchListener.onTouch(this, event)) {
10582                result = true;
10583            }
10584
10585            if (!result && onTouchEvent(event)) {
10586                result = true;
10587            }
10588        }
10589
10590        if (!result && mInputEventConsistencyVerifier != null) {
10591            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10592        }
10593
10594        // Clean up after nested scrolls if this is the end of a gesture;
10595        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
10596        // of the gesture.
10597        if (actionMasked == MotionEvent.ACTION_UP ||
10598                actionMasked == MotionEvent.ACTION_CANCEL ||
10599                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
10600            stopNestedScroll();
10601        }
10602
10603        return result;
10604    }
10605
10606    boolean isAccessibilityFocusedViewOrHost() {
10607        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
10608                .getAccessibilityFocusedHost() == this);
10609    }
10610
10611    /**
10612     * Filter the touch event to apply security policies.
10613     *
10614     * @param event The motion event to be filtered.
10615     * @return True if the event should be dispatched, false if the event should be dropped.
10616     *
10617     * @see #getFilterTouchesWhenObscured
10618     */
10619    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
10620        //noinspection RedundantIfStatement
10621        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
10622                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
10623            // Window is obscured, drop this touch.
10624            return false;
10625        }
10626        return true;
10627    }
10628
10629    /**
10630     * Pass a trackball motion event down to the focused view.
10631     *
10632     * @param event The motion event to be dispatched.
10633     * @return True if the event was handled by the view, false otherwise.
10634     */
10635    public boolean dispatchTrackballEvent(MotionEvent event) {
10636        if (mInputEventConsistencyVerifier != null) {
10637            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
10638        }
10639
10640        return onTrackballEvent(event);
10641    }
10642
10643    /**
10644     * Dispatch a generic motion event.
10645     * <p>
10646     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10647     * are delivered to the view under the pointer.  All other generic motion events are
10648     * delivered to the focused view.  Hover events are handled specially and are delivered
10649     * to {@link #onHoverEvent(MotionEvent)}.
10650     * </p>
10651     *
10652     * @param event The motion event to be dispatched.
10653     * @return True if the event was handled by the view, false otherwise.
10654     */
10655    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10656        if (mInputEventConsistencyVerifier != null) {
10657            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10658        }
10659
10660        final int source = event.getSource();
10661        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10662            final int action = event.getAction();
10663            if (action == MotionEvent.ACTION_HOVER_ENTER
10664                    || action == MotionEvent.ACTION_HOVER_MOVE
10665                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10666                if (dispatchHoverEvent(event)) {
10667                    return true;
10668                }
10669            } else if (dispatchGenericPointerEvent(event)) {
10670                return true;
10671            }
10672        } else if (dispatchGenericFocusedEvent(event)) {
10673            return true;
10674        }
10675
10676        if (dispatchGenericMotionEventInternal(event)) {
10677            return true;
10678        }
10679
10680        if (mInputEventConsistencyVerifier != null) {
10681            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10682        }
10683        return false;
10684    }
10685
10686    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10687        //noinspection SimplifiableIfStatement
10688        ListenerInfo li = mListenerInfo;
10689        if (li != null && li.mOnGenericMotionListener != null
10690                && (mViewFlags & ENABLED_MASK) == ENABLED
10691                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10692            return true;
10693        }
10694
10695        if (onGenericMotionEvent(event)) {
10696            return true;
10697        }
10698
10699        final int actionButton = event.getActionButton();
10700        switch (event.getActionMasked()) {
10701            case MotionEvent.ACTION_BUTTON_PRESS:
10702                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10703                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10704                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10705                    if (performContextClick(event.getX(), event.getY())) {
10706                        mInContextButtonPress = true;
10707                        setPressed(true, event.getX(), event.getY());
10708                        removeTapCallback();
10709                        removeLongPressCallback();
10710                        return true;
10711                    }
10712                }
10713                break;
10714
10715            case MotionEvent.ACTION_BUTTON_RELEASE:
10716                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10717                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10718                    mInContextButtonPress = false;
10719                    mIgnoreNextUpEvent = true;
10720                }
10721                break;
10722        }
10723
10724        if (mInputEventConsistencyVerifier != null) {
10725            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10726        }
10727        return false;
10728    }
10729
10730    /**
10731     * Dispatch a hover event.
10732     * <p>
10733     * Do not call this method directly.
10734     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10735     * </p>
10736     *
10737     * @param event The motion event to be dispatched.
10738     * @return True if the event was handled by the view, false otherwise.
10739     */
10740    protected boolean dispatchHoverEvent(MotionEvent event) {
10741        ListenerInfo li = mListenerInfo;
10742        //noinspection SimplifiableIfStatement
10743        if (li != null && li.mOnHoverListener != null
10744                && (mViewFlags & ENABLED_MASK) == ENABLED
10745                && li.mOnHoverListener.onHover(this, event)) {
10746            return true;
10747        }
10748
10749        return onHoverEvent(event);
10750    }
10751
10752    /**
10753     * Returns true if the view has a child to which it has recently sent
10754     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10755     * it does not have a hovered child, then it must be the innermost hovered view.
10756     * @hide
10757     */
10758    protected boolean hasHoveredChild() {
10759        return false;
10760    }
10761
10762    /**
10763     * Dispatch a generic motion event to the view under the first pointer.
10764     * <p>
10765     * Do not call this method directly.
10766     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10767     * </p>
10768     *
10769     * @param event The motion event to be dispatched.
10770     * @return True if the event was handled by the view, false otherwise.
10771     */
10772    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10773        return false;
10774    }
10775
10776    /**
10777     * Dispatch a generic motion event to the currently focused view.
10778     * <p>
10779     * Do not call this method directly.
10780     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10781     * </p>
10782     *
10783     * @param event The motion event to be dispatched.
10784     * @return True if the event was handled by the view, false otherwise.
10785     */
10786    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10787        return false;
10788    }
10789
10790    /**
10791     * Dispatch a pointer event.
10792     * <p>
10793     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10794     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10795     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10796     * and should not be expected to handle other pointing device features.
10797     * </p>
10798     *
10799     * @param event The motion event to be dispatched.
10800     * @return True if the event was handled by the view, false otherwise.
10801     * @hide
10802     */
10803    public final boolean dispatchPointerEvent(MotionEvent event) {
10804        if (event.isTouchEvent()) {
10805            return dispatchTouchEvent(event);
10806        } else {
10807            return dispatchGenericMotionEvent(event);
10808        }
10809    }
10810
10811    /**
10812     * Called when the window containing this view gains or loses window focus.
10813     * ViewGroups should override to route to their children.
10814     *
10815     * @param hasFocus True if the window containing this view now has focus,
10816     *        false otherwise.
10817     */
10818    public void dispatchWindowFocusChanged(boolean hasFocus) {
10819        onWindowFocusChanged(hasFocus);
10820    }
10821
10822    /**
10823     * Called when the window containing this view gains or loses focus.  Note
10824     * that this is separate from view focus: to receive key events, both
10825     * your view and its window must have focus.  If a window is displayed
10826     * on top of yours that takes input focus, then your own window will lose
10827     * focus but the view focus will remain unchanged.
10828     *
10829     * @param hasWindowFocus True if the window containing this view now has
10830     *        focus, false otherwise.
10831     */
10832    public void onWindowFocusChanged(boolean hasWindowFocus) {
10833        InputMethodManager imm = InputMethodManager.peekInstance();
10834        if (!hasWindowFocus) {
10835            if (isPressed()) {
10836                setPressed(false);
10837            }
10838            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
10839            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10840                imm.focusOut(this);
10841            }
10842            removeLongPressCallback();
10843            removeTapCallback();
10844            onFocusLost();
10845        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10846            imm.focusIn(this);
10847        }
10848        refreshDrawableState();
10849    }
10850
10851    /**
10852     * Returns true if this view is in a window that currently has window focus.
10853     * Note that this is not the same as the view itself having focus.
10854     *
10855     * @return True if this view is in a window that currently has window focus.
10856     */
10857    public boolean hasWindowFocus() {
10858        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10859    }
10860
10861    /**
10862     * Dispatch a view visibility change down the view hierarchy.
10863     * ViewGroups should override to route to their children.
10864     * @param changedView The view whose visibility changed. Could be 'this' or
10865     * an ancestor view.
10866     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10867     * {@link #INVISIBLE} or {@link #GONE}.
10868     */
10869    protected void dispatchVisibilityChanged(@NonNull View changedView,
10870            @Visibility int visibility) {
10871        onVisibilityChanged(changedView, visibility);
10872    }
10873
10874    /**
10875     * Called when the visibility of the view or an ancestor of the view has
10876     * changed.
10877     *
10878     * @param changedView The view whose visibility changed. May be
10879     *                    {@code this} or an ancestor view.
10880     * @param visibility The new visibility, one of {@link #VISIBLE},
10881     *                   {@link #INVISIBLE} or {@link #GONE}.
10882     */
10883    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10884    }
10885
10886    /**
10887     * Dispatch a hint about whether this view is displayed. For instance, when
10888     * a View moves out of the screen, it might receives a display hint indicating
10889     * the view is not displayed. Applications should not <em>rely</em> on this hint
10890     * as there is no guarantee that they will receive one.
10891     *
10892     * @param hint A hint about whether or not this view is displayed:
10893     * {@link #VISIBLE} or {@link #INVISIBLE}.
10894     */
10895    public void dispatchDisplayHint(@Visibility int hint) {
10896        onDisplayHint(hint);
10897    }
10898
10899    /**
10900     * Gives this view a hint about whether is displayed or not. For instance, when
10901     * a View moves out of the screen, it might receives a display hint indicating
10902     * the view is not displayed. Applications should not <em>rely</em> on this hint
10903     * as there is no guarantee that they will receive one.
10904     *
10905     * @param hint A hint about whether or not this view is displayed:
10906     * {@link #VISIBLE} or {@link #INVISIBLE}.
10907     */
10908    protected void onDisplayHint(@Visibility int hint) {
10909    }
10910
10911    /**
10912     * Dispatch a window visibility change down the view hierarchy.
10913     * ViewGroups should override to route to their children.
10914     *
10915     * @param visibility The new visibility of the window.
10916     *
10917     * @see #onWindowVisibilityChanged(int)
10918     */
10919    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10920        onWindowVisibilityChanged(visibility);
10921    }
10922
10923    /**
10924     * Called when the window containing has change its visibility
10925     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10926     * that this tells you whether or not your window is being made visible
10927     * to the window manager; this does <em>not</em> tell you whether or not
10928     * your window is obscured by other windows on the screen, even if it
10929     * is itself visible.
10930     *
10931     * @param visibility The new visibility of the window.
10932     */
10933    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10934        if (visibility == VISIBLE) {
10935            initialAwakenScrollBars();
10936        }
10937    }
10938
10939    /**
10940     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10941     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10942     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10943     *
10944     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10945     *                  ancestors or by window visibility
10946     * @return true if this view is visible to the user, not counting clipping or overlapping
10947     */
10948    boolean dispatchVisibilityAggregated(boolean isVisible) {
10949        final boolean thisVisible = getVisibility() == VISIBLE;
10950        // If we're not visible but something is telling us we are, ignore it.
10951        if (thisVisible || !isVisible) {
10952            onVisibilityAggregated(isVisible);
10953        }
10954        return thisVisible && isVisible;
10955    }
10956
10957    /**
10958     * Called when the user-visibility of this View is potentially affected by a change
10959     * to this view itself, an ancestor view or the window this view is attached to.
10960     *
10961     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10962     *                  and this view's window is also visible
10963     */
10964    @CallSuper
10965    public void onVisibilityAggregated(boolean isVisible) {
10966        if (isVisible && mAttachInfo != null) {
10967            initialAwakenScrollBars();
10968        }
10969
10970        final Drawable dr = mBackground;
10971        if (dr != null && isVisible != dr.isVisible()) {
10972            dr.setVisible(isVisible, false);
10973        }
10974        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10975        if (fg != null && isVisible != fg.isVisible()) {
10976            fg.setVisible(isVisible, false);
10977        }
10978    }
10979
10980    /**
10981     * Returns the current visibility of the window this view is attached to
10982     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10983     *
10984     * @return Returns the current visibility of the view's window.
10985     */
10986    @Visibility
10987    public int getWindowVisibility() {
10988        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10989    }
10990
10991    /**
10992     * Retrieve the overall visible display size in which the window this view is
10993     * attached to has been positioned in.  This takes into account screen
10994     * decorations above the window, for both cases where the window itself
10995     * is being position inside of them or the window is being placed under
10996     * then and covered insets are used for the window to position its content
10997     * inside.  In effect, this tells you the available area where content can
10998     * be placed and remain visible to users.
10999     *
11000     * <p>This function requires an IPC back to the window manager to retrieve
11001     * the requested information, so should not be used in performance critical
11002     * code like drawing.
11003     *
11004     * @param outRect Filled in with the visible display frame.  If the view
11005     * is not attached to a window, this is simply the raw display size.
11006     */
11007    public void getWindowVisibleDisplayFrame(Rect outRect) {
11008        if (mAttachInfo != null) {
11009            try {
11010                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11011            } catch (RemoteException e) {
11012                return;
11013            }
11014            // XXX This is really broken, and probably all needs to be done
11015            // in the window manager, and we need to know more about whether
11016            // we want the area behind or in front of the IME.
11017            final Rect insets = mAttachInfo.mVisibleInsets;
11018            outRect.left += insets.left;
11019            outRect.top += insets.top;
11020            outRect.right -= insets.right;
11021            outRect.bottom -= insets.bottom;
11022            return;
11023        }
11024        // The view is not attached to a display so we don't have a context.
11025        // Make a best guess about the display size.
11026        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11027        d.getRectSize(outRect);
11028    }
11029
11030    /**
11031     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
11032     * is currently in without any insets.
11033     *
11034     * @hide
11035     */
11036    public void getWindowDisplayFrame(Rect outRect) {
11037        if (mAttachInfo != null) {
11038            try {
11039                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11040            } catch (RemoteException e) {
11041                return;
11042            }
11043            return;
11044        }
11045        // The view is not attached to a display so we don't have a context.
11046        // Make a best guess about the display size.
11047        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11048        d.getRectSize(outRect);
11049    }
11050
11051    /**
11052     * Dispatch a notification about a resource configuration change down
11053     * the view hierarchy.
11054     * ViewGroups should override to route to their children.
11055     *
11056     * @param newConfig The new resource configuration.
11057     *
11058     * @see #onConfigurationChanged(android.content.res.Configuration)
11059     */
11060    public void dispatchConfigurationChanged(Configuration newConfig) {
11061        onConfigurationChanged(newConfig);
11062    }
11063
11064    /**
11065     * Called when the current configuration of the resources being used
11066     * by the application have changed.  You can use this to decide when
11067     * to reload resources that can changed based on orientation and other
11068     * configuration characteristics.  You only need to use this if you are
11069     * not relying on the normal {@link android.app.Activity} mechanism of
11070     * recreating the activity instance upon a configuration change.
11071     *
11072     * @param newConfig The new resource configuration.
11073     */
11074    protected void onConfigurationChanged(Configuration newConfig) {
11075    }
11076
11077    /**
11078     * Private function to aggregate all per-view attributes in to the view
11079     * root.
11080     */
11081    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11082        performCollectViewAttributes(attachInfo, visibility);
11083    }
11084
11085    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11086        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
11087            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
11088                attachInfo.mKeepScreenOn = true;
11089            }
11090            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
11091            ListenerInfo li = mListenerInfo;
11092            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
11093                attachInfo.mHasSystemUiListeners = true;
11094            }
11095        }
11096    }
11097
11098    void needGlobalAttributesUpdate(boolean force) {
11099        final AttachInfo ai = mAttachInfo;
11100        if (ai != null && !ai.mRecomputeGlobalAttributes) {
11101            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
11102                    || ai.mHasSystemUiListeners) {
11103                ai.mRecomputeGlobalAttributes = true;
11104            }
11105        }
11106    }
11107
11108    /**
11109     * Returns whether the device is currently in touch mode.  Touch mode is entered
11110     * once the user begins interacting with the device by touch, and affects various
11111     * things like whether focus is always visible to the user.
11112     *
11113     * @return Whether the device is in touch mode.
11114     */
11115    @ViewDebug.ExportedProperty
11116    public boolean isInTouchMode() {
11117        if (mAttachInfo != null) {
11118            return mAttachInfo.mInTouchMode;
11119        } else {
11120            return ViewRootImpl.isInTouchMode();
11121        }
11122    }
11123
11124    /**
11125     * Returns the context the view is running in, through which it can
11126     * access the current theme, resources, etc.
11127     *
11128     * @return The view's Context.
11129     */
11130    @ViewDebug.CapturedViewProperty
11131    public final Context getContext() {
11132        return mContext;
11133    }
11134
11135    /**
11136     * Handle a key event before it is processed by any input method
11137     * associated with the view hierarchy.  This can be used to intercept
11138     * key events in special situations before the IME consumes them; a
11139     * typical example would be handling the BACK key to update the application's
11140     * UI instead of allowing the IME to see it and close itself.
11141     *
11142     * @param keyCode The value in event.getKeyCode().
11143     * @param event Description of the key event.
11144     * @return If you handled the event, return true. If you want to allow the
11145     *         event to be handled by the next receiver, return false.
11146     */
11147    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
11148        return false;
11149    }
11150
11151    /**
11152     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
11153     * KeyEvent.Callback.onKeyDown()}: perform press of the view
11154     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
11155     * is released, if the view is enabled and clickable.
11156     * <p>
11157     * Key presses in software keyboards will generally NOT trigger this
11158     * listener, although some may elect to do so in some situations. Do not
11159     * rely on this to catch software key presses.
11160     *
11161     * @param keyCode a key code that represents the button pressed, from
11162     *                {@link android.view.KeyEvent}
11163     * @param event the KeyEvent object that defines the button action
11164     */
11165    public boolean onKeyDown(int keyCode, KeyEvent event) {
11166        if (KeyEvent.isConfirmKey(keyCode)) {
11167            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11168                return true;
11169            }
11170
11171            if (event.getRepeatCount() == 0) {
11172                // Long clickable items don't necessarily have to be clickable.
11173                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
11174                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
11175                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
11176                    // For the purposes of menu anchoring and drawable hotspots,
11177                    // key events are considered to be at the center of the view.
11178                    final float x = getWidth() / 2f;
11179                    final float y = getHeight() / 2f;
11180                    if (clickable) {
11181                        setPressed(true, x, y);
11182                    }
11183                    checkForLongClick(0, x, y);
11184                    return true;
11185                }
11186            }
11187        }
11188
11189        return false;
11190    }
11191
11192    /**
11193     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
11194     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
11195     * the event).
11196     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11197     * although some may elect to do so in some situations. Do not rely on this to
11198     * catch software key presses.
11199     */
11200    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
11201        return false;
11202    }
11203
11204    /**
11205     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
11206     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
11207     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
11208     * or {@link KeyEvent#KEYCODE_SPACE} is released.
11209     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11210     * although some may elect to do so in some situations. Do not rely on this to
11211     * catch software key presses.
11212     *
11213     * @param keyCode A key code that represents the button pressed, from
11214     *                {@link android.view.KeyEvent}.
11215     * @param event   The KeyEvent object that defines the button action.
11216     */
11217    public boolean onKeyUp(int keyCode, KeyEvent event) {
11218        if (KeyEvent.isConfirmKey(keyCode)) {
11219            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11220                return true;
11221            }
11222            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
11223                setPressed(false);
11224
11225                if (!mHasPerformedLongPress) {
11226                    // This is a tap, so remove the longpress check
11227                    removeLongPressCallback();
11228                    return performClick();
11229                }
11230            }
11231        }
11232        return false;
11233    }
11234
11235    /**
11236     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
11237     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
11238     * the event).
11239     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11240     * although some may elect to do so in some situations. Do not rely on this to
11241     * catch software key presses.
11242     *
11243     * @param keyCode     A key code that represents the button pressed, from
11244     *                    {@link android.view.KeyEvent}.
11245     * @param repeatCount The number of times the action was made.
11246     * @param event       The KeyEvent object that defines the button action.
11247     */
11248    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
11249        return false;
11250    }
11251
11252    /**
11253     * Called on the focused view when a key shortcut event is not handled.
11254     * Override this method to implement local key shortcuts for the View.
11255     * Key shortcuts can also be implemented by setting the
11256     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
11257     *
11258     * @param keyCode The value in event.getKeyCode().
11259     * @param event Description of the key event.
11260     * @return If you handled the event, return true. If you want to allow the
11261     *         event to be handled by the next receiver, return false.
11262     */
11263    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
11264        return false;
11265    }
11266
11267    /**
11268     * Check whether the called view is a text editor, in which case it
11269     * would make sense to automatically display a soft input window for
11270     * it.  Subclasses should override this if they implement
11271     * {@link #onCreateInputConnection(EditorInfo)} to return true if
11272     * a call on that method would return a non-null InputConnection, and
11273     * they are really a first-class editor that the user would normally
11274     * start typing on when the go into a window containing your view.
11275     *
11276     * <p>The default implementation always returns false.  This does
11277     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
11278     * will not be called or the user can not otherwise perform edits on your
11279     * view; it is just a hint to the system that this is not the primary
11280     * purpose of this view.
11281     *
11282     * @return Returns true if this view is a text editor, else false.
11283     */
11284    public boolean onCheckIsTextEditor() {
11285        return false;
11286    }
11287
11288    /**
11289     * Create a new InputConnection for an InputMethod to interact
11290     * with the view.  The default implementation returns null, since it doesn't
11291     * support input methods.  You can override this to implement such support.
11292     * This is only needed for views that take focus and text input.
11293     *
11294     * <p>When implementing this, you probably also want to implement
11295     * {@link #onCheckIsTextEditor()} to indicate you will return a
11296     * non-null InputConnection.</p>
11297     *
11298     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
11299     * object correctly and in its entirety, so that the connected IME can rely
11300     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
11301     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
11302     * must be filled in with the correct cursor position for IMEs to work correctly
11303     * with your application.</p>
11304     *
11305     * @param outAttrs Fill in with attribute information about the connection.
11306     */
11307    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
11308        return null;
11309    }
11310
11311    /**
11312     * Called by the {@link android.view.inputmethod.InputMethodManager}
11313     * when a view who is not the current
11314     * input connection target is trying to make a call on the manager.  The
11315     * default implementation returns false; you can override this to return
11316     * true for certain views if you are performing InputConnection proxying
11317     * to them.
11318     * @param view The View that is making the InputMethodManager call.
11319     * @return Return true to allow the call, false to reject.
11320     */
11321    public boolean checkInputConnectionProxy(View view) {
11322        return false;
11323    }
11324
11325    /**
11326     * Show the context menu for this view. It is not safe to hold on to the
11327     * menu after returning from this method.
11328     *
11329     * You should normally not overload this method. Overload
11330     * {@link #onCreateContextMenu(ContextMenu)} or define an
11331     * {@link OnCreateContextMenuListener} to add items to the context menu.
11332     *
11333     * @param menu The context menu to populate
11334     */
11335    public void createContextMenu(ContextMenu menu) {
11336        ContextMenuInfo menuInfo = getContextMenuInfo();
11337
11338        // Sets the current menu info so all items added to menu will have
11339        // my extra info set.
11340        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
11341
11342        onCreateContextMenu(menu);
11343        ListenerInfo li = mListenerInfo;
11344        if (li != null && li.mOnCreateContextMenuListener != null) {
11345            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
11346        }
11347
11348        // Clear the extra information so subsequent items that aren't mine don't
11349        // have my extra info.
11350        ((MenuBuilder)menu).setCurrentMenuInfo(null);
11351
11352        if (mParent != null) {
11353            mParent.createContextMenu(menu);
11354        }
11355    }
11356
11357    /**
11358     * Views should implement this if they have extra information to associate
11359     * with the context menu. The return result is supplied as a parameter to
11360     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
11361     * callback.
11362     *
11363     * @return Extra information about the item for which the context menu
11364     *         should be shown. This information will vary across different
11365     *         subclasses of View.
11366     */
11367    protected ContextMenuInfo getContextMenuInfo() {
11368        return null;
11369    }
11370
11371    /**
11372     * Views should implement this if the view itself is going to add items to
11373     * the context menu.
11374     *
11375     * @param menu the context menu to populate
11376     */
11377    protected void onCreateContextMenu(ContextMenu menu) {
11378    }
11379
11380    /**
11381     * Implement this method to handle trackball motion events.  The
11382     * <em>relative</em> movement of the trackball since the last event
11383     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
11384     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
11385     * that a movement of 1 corresponds to the user pressing one DPAD key (so
11386     * they will often be fractional values, representing the more fine-grained
11387     * movement information available from a trackball).
11388     *
11389     * @param event The motion event.
11390     * @return True if the event was handled, false otherwise.
11391     */
11392    public boolean onTrackballEvent(MotionEvent event) {
11393        return false;
11394    }
11395
11396    /**
11397     * Implement this method to handle generic motion events.
11398     * <p>
11399     * Generic motion events describe joystick movements, mouse hovers, track pad
11400     * touches, scroll wheel movements and other input events.  The
11401     * {@link MotionEvent#getSource() source} of the motion event specifies
11402     * the class of input that was received.  Implementations of this method
11403     * must examine the bits in the source before processing the event.
11404     * The following code example shows how this is done.
11405     * </p><p>
11406     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
11407     * are delivered to the view under the pointer.  All other generic motion events are
11408     * delivered to the focused view.
11409     * </p>
11410     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
11411     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
11412     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
11413     *             // process the joystick movement...
11414     *             return true;
11415     *         }
11416     *     }
11417     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
11418     *         switch (event.getAction()) {
11419     *             case MotionEvent.ACTION_HOVER_MOVE:
11420     *                 // process the mouse hover movement...
11421     *                 return true;
11422     *             case MotionEvent.ACTION_SCROLL:
11423     *                 // process the scroll wheel movement...
11424     *                 return true;
11425     *         }
11426     *     }
11427     *     return super.onGenericMotionEvent(event);
11428     * }</pre>
11429     *
11430     * @param event The generic motion event being processed.
11431     * @return True if the event was handled, false otherwise.
11432     */
11433    public boolean onGenericMotionEvent(MotionEvent event) {
11434        return false;
11435    }
11436
11437    /**
11438     * Implement this method to handle hover events.
11439     * <p>
11440     * This method is called whenever a pointer is hovering into, over, or out of the
11441     * bounds of a view and the view is not currently being touched.
11442     * Hover events are represented as pointer events with action
11443     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
11444     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
11445     * </p>
11446     * <ul>
11447     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
11448     * when the pointer enters the bounds of the view.</li>
11449     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
11450     * when the pointer has already entered the bounds of the view and has moved.</li>
11451     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
11452     * when the pointer has exited the bounds of the view or when the pointer is
11453     * about to go down due to a button click, tap, or similar user action that
11454     * causes the view to be touched.</li>
11455     * </ul>
11456     * <p>
11457     * The view should implement this method to return true to indicate that it is
11458     * handling the hover event, such as by changing its drawable state.
11459     * </p><p>
11460     * The default implementation calls {@link #setHovered} to update the hovered state
11461     * of the view when a hover enter or hover exit event is received, if the view
11462     * is enabled and is clickable.  The default implementation also sends hover
11463     * accessibility events.
11464     * </p>
11465     *
11466     * @param event The motion event that describes the hover.
11467     * @return True if the view handled the hover event.
11468     *
11469     * @see #isHovered
11470     * @see #setHovered
11471     * @see #onHoverChanged
11472     */
11473    public boolean onHoverEvent(MotionEvent event) {
11474        // The root view may receive hover (or touch) events that are outside the bounds of
11475        // the window.  This code ensures that we only send accessibility events for
11476        // hovers that are actually within the bounds of the root view.
11477        final int action = event.getActionMasked();
11478        if (!mSendingHoverAccessibilityEvents) {
11479            if ((action == MotionEvent.ACTION_HOVER_ENTER
11480                    || action == MotionEvent.ACTION_HOVER_MOVE)
11481                    && !hasHoveredChild()
11482                    && pointInView(event.getX(), event.getY())) {
11483                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
11484                mSendingHoverAccessibilityEvents = true;
11485            }
11486        } else {
11487            if (action == MotionEvent.ACTION_HOVER_EXIT
11488                    || (action == MotionEvent.ACTION_MOVE
11489                            && !pointInView(event.getX(), event.getY()))) {
11490                mSendingHoverAccessibilityEvents = false;
11491                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
11492            }
11493        }
11494
11495        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
11496                && event.isFromSource(InputDevice.SOURCE_MOUSE)
11497                && isOnScrollbar(event.getX(), event.getY())) {
11498            awakenScrollBars();
11499        }
11500        if (isHoverable()) {
11501            switch (action) {
11502                case MotionEvent.ACTION_HOVER_ENTER:
11503                    setHovered(true);
11504                    break;
11505                case MotionEvent.ACTION_HOVER_EXIT:
11506                    setHovered(false);
11507                    break;
11508            }
11509
11510            // Dispatch the event to onGenericMotionEvent before returning true.
11511            // This is to provide compatibility with existing applications that
11512            // handled HOVER_MOVE events in onGenericMotionEvent and that would
11513            // break because of the new default handling for hoverable views
11514            // in onHoverEvent.
11515            // Note that onGenericMotionEvent will be called by default when
11516            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
11517            dispatchGenericMotionEventInternal(event);
11518            // The event was already handled by calling setHovered(), so always
11519            // return true.
11520            return true;
11521        }
11522
11523        return false;
11524    }
11525
11526    /**
11527     * Returns true if the view should handle {@link #onHoverEvent}
11528     * by calling {@link #setHovered} to change its hovered state.
11529     *
11530     * @return True if the view is hoverable.
11531     */
11532    private boolean isHoverable() {
11533        final int viewFlags = mViewFlags;
11534        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11535            return false;
11536        }
11537
11538        return (viewFlags & CLICKABLE) == CLICKABLE
11539                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
11540                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11541    }
11542
11543    /**
11544     * Returns true if the view is currently hovered.
11545     *
11546     * @return True if the view is currently hovered.
11547     *
11548     * @see #setHovered
11549     * @see #onHoverChanged
11550     */
11551    @ViewDebug.ExportedProperty
11552    public boolean isHovered() {
11553        return (mPrivateFlags & PFLAG_HOVERED) != 0;
11554    }
11555
11556    /**
11557     * Sets whether the view is currently hovered.
11558     * <p>
11559     * Calling this method also changes the drawable state of the view.  This
11560     * enables the view to react to hover by using different drawable resources
11561     * to change its appearance.
11562     * </p><p>
11563     * The {@link #onHoverChanged} method is called when the hovered state changes.
11564     * </p>
11565     *
11566     * @param hovered True if the view is hovered.
11567     *
11568     * @see #isHovered
11569     * @see #onHoverChanged
11570     */
11571    public void setHovered(boolean hovered) {
11572        if (hovered) {
11573            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
11574                mPrivateFlags |= PFLAG_HOVERED;
11575                refreshDrawableState();
11576                onHoverChanged(true);
11577            }
11578        } else {
11579            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
11580                mPrivateFlags &= ~PFLAG_HOVERED;
11581                refreshDrawableState();
11582                onHoverChanged(false);
11583            }
11584        }
11585    }
11586
11587    /**
11588     * Implement this method to handle hover state changes.
11589     * <p>
11590     * This method is called whenever the hover state changes as a result of a
11591     * call to {@link #setHovered}.
11592     * </p>
11593     *
11594     * @param hovered The current hover state, as returned by {@link #isHovered}.
11595     *
11596     * @see #isHovered
11597     * @see #setHovered
11598     */
11599    public void onHoverChanged(boolean hovered) {
11600    }
11601
11602    /**
11603     * Handles scroll bar dragging by mouse input.
11604     *
11605     * @hide
11606     * @param event The motion event.
11607     *
11608     * @return true if the event was handled as a scroll bar dragging, false otherwise.
11609     */
11610    protected boolean handleScrollBarDragging(MotionEvent event) {
11611        if (mScrollCache == null) {
11612            return false;
11613        }
11614        final float x = event.getX();
11615        final float y = event.getY();
11616        final int action = event.getAction();
11617        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
11618                && action != MotionEvent.ACTION_DOWN)
11619                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
11620                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
11621            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11622            return false;
11623        }
11624
11625        switch (action) {
11626            case MotionEvent.ACTION_MOVE:
11627                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
11628                    return false;
11629                }
11630                if (mScrollCache.mScrollBarDraggingState
11631                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
11632                    final Rect bounds = mScrollCache.mScrollBarBounds;
11633                    getVerticalScrollBarBounds(bounds);
11634                    final int range = computeVerticalScrollRange();
11635                    final int offset = computeVerticalScrollOffset();
11636                    final int extent = computeVerticalScrollExtent();
11637
11638                    final int thumbLength = ScrollBarUtils.getThumbLength(
11639                            bounds.height(), bounds.width(), extent, range);
11640                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11641                            bounds.height(), thumbLength, extent, range, offset);
11642
11643                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
11644                    final float maxThumbOffset = bounds.height() - thumbLength;
11645                    final float newThumbOffset =
11646                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11647                    final int height = getHeight();
11648                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11649                            && height > 0 && extent > 0) {
11650                        final int newY = Math.round((range - extent)
11651                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11652                        if (newY != getScrollY()) {
11653                            mScrollCache.mScrollBarDraggingPos = y;
11654                            setScrollY(newY);
11655                        }
11656                    }
11657                    return true;
11658                }
11659                if (mScrollCache.mScrollBarDraggingState
11660                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11661                    final Rect bounds = mScrollCache.mScrollBarBounds;
11662                    getHorizontalScrollBarBounds(bounds);
11663                    final int range = computeHorizontalScrollRange();
11664                    final int offset = computeHorizontalScrollOffset();
11665                    final int extent = computeHorizontalScrollExtent();
11666
11667                    final int thumbLength = ScrollBarUtils.getThumbLength(
11668                            bounds.width(), bounds.height(), extent, range);
11669                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11670                            bounds.width(), thumbLength, extent, range, offset);
11671
11672                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11673                    final float maxThumbOffset = bounds.width() - thumbLength;
11674                    final float newThumbOffset =
11675                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11676                    final int width = getWidth();
11677                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11678                            && width > 0 && extent > 0) {
11679                        final int newX = Math.round((range - extent)
11680                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11681                        if (newX != getScrollX()) {
11682                            mScrollCache.mScrollBarDraggingPos = x;
11683                            setScrollX(newX);
11684                        }
11685                    }
11686                    return true;
11687                }
11688            case MotionEvent.ACTION_DOWN:
11689                if (mScrollCache.state == ScrollabilityCache.OFF) {
11690                    return false;
11691                }
11692                if (isOnVerticalScrollbarThumb(x, y)) {
11693                    mScrollCache.mScrollBarDraggingState =
11694                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11695                    mScrollCache.mScrollBarDraggingPos = y;
11696                    return true;
11697                }
11698                if (isOnHorizontalScrollbarThumb(x, y)) {
11699                    mScrollCache.mScrollBarDraggingState =
11700                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11701                    mScrollCache.mScrollBarDraggingPos = x;
11702                    return true;
11703                }
11704        }
11705        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11706        return false;
11707    }
11708
11709    /**
11710     * Implement this method to handle touch screen motion events.
11711     * <p>
11712     * If this method is used to detect click actions, it is recommended that
11713     * the actions be performed by implementing and calling
11714     * {@link #performClick()}. This will ensure consistent system behavior,
11715     * including:
11716     * <ul>
11717     * <li>obeying click sound preferences
11718     * <li>dispatching OnClickListener calls
11719     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11720     * accessibility features are enabled
11721     * </ul>
11722     *
11723     * @param event The motion event.
11724     * @return True if the event was handled, false otherwise.
11725     */
11726    public boolean onTouchEvent(MotionEvent event) {
11727        final float x = event.getX();
11728        final float y = event.getY();
11729        final int viewFlags = mViewFlags;
11730        final int action = event.getAction();
11731
11732        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
11733                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11734                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11735
11736        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11737            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11738                setPressed(false);
11739            }
11740            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11741            // A disabled view that is clickable still consumes the touch
11742            // events, it just doesn't respond to them.
11743            return clickable;
11744        }
11745        if (mTouchDelegate != null) {
11746            if (mTouchDelegate.onTouchEvent(event)) {
11747                return true;
11748            }
11749        }
11750
11751        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
11752            switch (action) {
11753                case MotionEvent.ACTION_UP:
11754                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11755                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
11756                        handleTooltipUp();
11757                    }
11758                    if (!clickable) {
11759                        removeTapCallback();
11760                        removeLongPressCallback();
11761                        mInContextButtonPress = false;
11762                        mHasPerformedLongPress = false;
11763                        mIgnoreNextUpEvent = false;
11764                        break;
11765                    }
11766                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11767                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11768                        // take focus if we don't have it already and we should in
11769                        // touch mode.
11770                        boolean focusTaken = false;
11771                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11772                            focusTaken = requestFocus();
11773                        }
11774
11775                        if (prepressed) {
11776                            // The button is being released before we actually
11777                            // showed it as pressed.  Make it show the pressed
11778                            // state now (before scheduling the click) to ensure
11779                            // the user sees it.
11780                            setPressed(true, x, y);
11781                        }
11782
11783                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11784                            // This is a tap, so remove the longpress check
11785                            removeLongPressCallback();
11786
11787                            // Only perform take click actions if we were in the pressed state
11788                            if (!focusTaken) {
11789                                // Use a Runnable and post this rather than calling
11790                                // performClick directly. This lets other visual state
11791                                // of the view update before click actions start.
11792                                if (mPerformClick == null) {
11793                                    mPerformClick = new PerformClick();
11794                                }
11795                                if (!post(mPerformClick)) {
11796                                    performClick();
11797                                }
11798                            }
11799                        }
11800
11801                        if (mUnsetPressedState == null) {
11802                            mUnsetPressedState = new UnsetPressedState();
11803                        }
11804
11805                        if (prepressed) {
11806                            postDelayed(mUnsetPressedState,
11807                                    ViewConfiguration.getPressedStateDuration());
11808                        } else if (!post(mUnsetPressedState)) {
11809                            // If the post failed, unpress right now
11810                            mUnsetPressedState.run();
11811                        }
11812
11813                        removeTapCallback();
11814                    }
11815                    mIgnoreNextUpEvent = false;
11816                    break;
11817
11818                case MotionEvent.ACTION_DOWN:
11819                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
11820                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
11821                    }
11822                    mHasPerformedLongPress = false;
11823
11824                    if (!clickable) {
11825                        checkForLongClick(0, x, y);
11826                        break;
11827                    }
11828
11829                    if (performButtonActionOnTouchDown(event)) {
11830                        break;
11831                    }
11832
11833                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11834                    boolean isInScrollingContainer = isInScrollingContainer();
11835
11836                    // For views inside a scrolling container, delay the pressed feedback for
11837                    // a short period in case this is a scroll.
11838                    if (isInScrollingContainer) {
11839                        mPrivateFlags |= PFLAG_PREPRESSED;
11840                        if (mPendingCheckForTap == null) {
11841                            mPendingCheckForTap = new CheckForTap();
11842                        }
11843                        mPendingCheckForTap.x = event.getX();
11844                        mPendingCheckForTap.y = event.getY();
11845                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11846                    } else {
11847                        // Not inside a scrolling container, so show the feedback right away
11848                        setPressed(true, x, y);
11849                        checkForLongClick(0, x, y);
11850                    }
11851                    break;
11852
11853                case MotionEvent.ACTION_CANCEL:
11854                    if (clickable) {
11855                        setPressed(false);
11856                    }
11857                    removeTapCallback();
11858                    removeLongPressCallback();
11859                    mInContextButtonPress = false;
11860                    mHasPerformedLongPress = false;
11861                    mIgnoreNextUpEvent = false;
11862                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11863                    break;
11864
11865                case MotionEvent.ACTION_MOVE:
11866                    if (clickable) {
11867                        drawableHotspotChanged(x, y);
11868                    }
11869
11870                    // Be lenient about moving outside of buttons
11871                    if (!pointInView(x, y, mTouchSlop)) {
11872                        // Outside button
11873                        // Remove any future long press/tap checks
11874                        removeTapCallback();
11875                        removeLongPressCallback();
11876                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11877                            setPressed(false);
11878                        }
11879                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11880                    }
11881                    break;
11882            }
11883
11884            return true;
11885        }
11886
11887        return false;
11888    }
11889
11890    /**
11891     * @hide
11892     */
11893    public boolean isInScrollingContainer() {
11894        ViewParent p = getParent();
11895        while (p != null && p instanceof ViewGroup) {
11896            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11897                return true;
11898            }
11899            p = p.getParent();
11900        }
11901        return false;
11902    }
11903
11904    /**
11905     * Remove the longpress detection timer.
11906     */
11907    private void removeLongPressCallback() {
11908        if (mPendingCheckForLongPress != null) {
11909            removeCallbacks(mPendingCheckForLongPress);
11910        }
11911    }
11912
11913    /**
11914     * Remove the pending click action
11915     */
11916    private void removePerformClickCallback() {
11917        if (mPerformClick != null) {
11918            removeCallbacks(mPerformClick);
11919        }
11920    }
11921
11922    /**
11923     * Remove the prepress detection timer.
11924     */
11925    private void removeUnsetPressCallback() {
11926        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11927            setPressed(false);
11928            removeCallbacks(mUnsetPressedState);
11929        }
11930    }
11931
11932    /**
11933     * Remove the tap detection timer.
11934     */
11935    private void removeTapCallback() {
11936        if (mPendingCheckForTap != null) {
11937            mPrivateFlags &= ~PFLAG_PREPRESSED;
11938            removeCallbacks(mPendingCheckForTap);
11939        }
11940    }
11941
11942    /**
11943     * Cancels a pending long press.  Your subclass can use this if you
11944     * want the context menu to come up if the user presses and holds
11945     * at the same place, but you don't want it to come up if they press
11946     * and then move around enough to cause scrolling.
11947     */
11948    public void cancelLongPress() {
11949        removeLongPressCallback();
11950
11951        /*
11952         * The prepressed state handled by the tap callback is a display
11953         * construct, but the tap callback will post a long press callback
11954         * less its own timeout. Remove it here.
11955         */
11956        removeTapCallback();
11957    }
11958
11959    /**
11960     * Remove the pending callback for sending a
11961     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11962     */
11963    private void removeSendViewScrolledAccessibilityEventCallback() {
11964        if (mSendViewScrolledAccessibilityEvent != null) {
11965            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11966            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11967        }
11968    }
11969
11970    /**
11971     * Sets the TouchDelegate for this View.
11972     */
11973    public void setTouchDelegate(TouchDelegate delegate) {
11974        mTouchDelegate = delegate;
11975    }
11976
11977    /**
11978     * Gets the TouchDelegate for this View.
11979     */
11980    public TouchDelegate getTouchDelegate() {
11981        return mTouchDelegate;
11982    }
11983
11984    /**
11985     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11986     *
11987     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11988     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11989     * available. This method should only be called for touch events.
11990     *
11991     * <p class="note">This api is not intended for most applications. Buffered dispatch
11992     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11993     * streams will not improve your input latency. Side effects include: increased latency,
11994     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11995     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11996     * you.</p>
11997     */
11998    public final void requestUnbufferedDispatch(MotionEvent event) {
11999        final int action = event.getAction();
12000        if (mAttachInfo == null
12001                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
12002                || !event.isTouchEvent()) {
12003            return;
12004        }
12005        mAttachInfo.mUnbufferedDispatchRequested = true;
12006    }
12007
12008    /**
12009     * Set flags controlling behavior of this view.
12010     *
12011     * @param flags Constant indicating the value which should be set
12012     * @param mask Constant indicating the bit range that should be changed
12013     */
12014    void setFlags(int flags, int mask) {
12015        final boolean accessibilityEnabled =
12016                AccessibilityManager.getInstance(mContext).isEnabled();
12017        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
12018
12019        int old = mViewFlags;
12020        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
12021
12022        int changed = mViewFlags ^ old;
12023        if (changed == 0) {
12024            return;
12025        }
12026        int privateFlags = mPrivateFlags;
12027
12028        // If focusable is auto, update the FOCUSABLE bit.
12029        if (((mViewFlags & FOCUSABLE_AUTO) != 0)
12030                && (changed & (FOCUSABLE_MASK | CLICKABLE | FOCUSABLE_IN_TOUCH_MODE)) != 0) {
12031            int newFocus = NOT_FOCUSABLE;
12032            if ((mViewFlags & (CLICKABLE | FOCUSABLE_IN_TOUCH_MODE)) != 0) {
12033                newFocus = FOCUSABLE;
12034            } else {
12035                mViewFlags = (mViewFlags & ~FOCUSABLE_IN_TOUCH_MODE);
12036            }
12037            mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
12038            int focusChanged = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
12039            changed = (changed & ~FOCUSABLE) | focusChanged;
12040        }
12041
12042        /* Check if the FOCUSABLE bit has changed */
12043        if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
12044            if (((old & FOCUSABLE) == FOCUSABLE)
12045                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
12046                /* Give up focus if we are no longer focusable */
12047                clearFocus();
12048            } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
12049                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
12050                /*
12051                 * Tell the view system that we are now available to take focus
12052                 * if no one else already has it.
12053                 */
12054                if (mParent != null) mParent.focusableViewAvailable(this);
12055            }
12056        }
12057
12058        final int newVisibility = flags & VISIBILITY_MASK;
12059        if (newVisibility == VISIBLE) {
12060            if ((changed & VISIBILITY_MASK) != 0) {
12061                /*
12062                 * If this view is becoming visible, invalidate it in case it changed while
12063                 * it was not visible. Marking it drawn ensures that the invalidation will
12064                 * go through.
12065                 */
12066                mPrivateFlags |= PFLAG_DRAWN;
12067                invalidate(true);
12068
12069                needGlobalAttributesUpdate(true);
12070
12071                // a view becoming visible is worth notifying the parent
12072                // about in case nothing has focus.  even if this specific view
12073                // isn't focusable, it may contain something that is, so let
12074                // the root view try to give this focus if nothing else does.
12075                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
12076                    mParent.focusableViewAvailable(this);
12077                }
12078            }
12079        }
12080
12081        /* Check if the GONE bit has changed */
12082        if ((changed & GONE) != 0) {
12083            needGlobalAttributesUpdate(false);
12084            requestLayout();
12085
12086            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
12087                if (hasFocus()) clearFocus();
12088                clearAccessibilityFocus();
12089                destroyDrawingCache();
12090                if (mParent instanceof View) {
12091                    // GONE views noop invalidation, so invalidate the parent
12092                    ((View) mParent).invalidate(true);
12093                }
12094                // Mark the view drawn to ensure that it gets invalidated properly the next
12095                // time it is visible and gets invalidated
12096                mPrivateFlags |= PFLAG_DRAWN;
12097            }
12098            if (mAttachInfo != null) {
12099                mAttachInfo.mViewVisibilityChanged = true;
12100            }
12101        }
12102
12103        /* Check if the VISIBLE bit has changed */
12104        if ((changed & INVISIBLE) != 0) {
12105            needGlobalAttributesUpdate(false);
12106            /*
12107             * If this view is becoming invisible, set the DRAWN flag so that
12108             * the next invalidate() will not be skipped.
12109             */
12110            mPrivateFlags |= PFLAG_DRAWN;
12111
12112            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
12113                // root view becoming invisible shouldn't clear focus and accessibility focus
12114                if (getRootView() != this) {
12115                    if (hasFocus()) clearFocus();
12116                    clearAccessibilityFocus();
12117                }
12118            }
12119            if (mAttachInfo != null) {
12120                mAttachInfo.mViewVisibilityChanged = true;
12121            }
12122        }
12123
12124        if ((changed & VISIBILITY_MASK) != 0) {
12125            // If the view is invisible, cleanup its display list to free up resources
12126            if (newVisibility != VISIBLE && mAttachInfo != null) {
12127                cleanupDraw();
12128            }
12129
12130            if (mParent instanceof ViewGroup) {
12131                ((ViewGroup) mParent).onChildVisibilityChanged(this,
12132                        (changed & VISIBILITY_MASK), newVisibility);
12133                ((View) mParent).invalidate(true);
12134            } else if (mParent != null) {
12135                mParent.invalidateChild(this, null);
12136            }
12137
12138            if (mAttachInfo != null) {
12139                dispatchVisibilityChanged(this, newVisibility);
12140
12141                // Aggregated visibility changes are dispatched to attached views
12142                // in visible windows where the parent is currently shown/drawn
12143                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
12144                // discounting clipping or overlapping. This makes it a good place
12145                // to change animation states.
12146                if (mParent != null && getWindowVisibility() == VISIBLE &&
12147                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
12148                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
12149                }
12150                notifySubtreeAccessibilityStateChangedIfNeeded();
12151            }
12152        }
12153
12154        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
12155            destroyDrawingCache();
12156        }
12157
12158        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
12159            destroyDrawingCache();
12160            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12161            invalidateParentCaches();
12162        }
12163
12164        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
12165            destroyDrawingCache();
12166            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12167        }
12168
12169        if ((changed & DRAW_MASK) != 0) {
12170            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
12171                if (mBackground != null
12172                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
12173                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12174                } else {
12175                    mPrivateFlags |= PFLAG_SKIP_DRAW;
12176                }
12177            } else {
12178                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12179            }
12180            requestLayout();
12181            invalidate(true);
12182        }
12183
12184        if ((changed & KEEP_SCREEN_ON) != 0) {
12185            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12186                mParent.recomputeViewAttributes(this);
12187            }
12188        }
12189
12190        if (accessibilityEnabled) {
12191            if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
12192                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
12193                    || (changed & CONTEXT_CLICKABLE) != 0) {
12194                if (oldIncludeForAccessibility != includeForAccessibility()) {
12195                    notifySubtreeAccessibilityStateChangedIfNeeded();
12196                } else {
12197                    notifyViewAccessibilityStateChangedIfNeeded(
12198                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12199                }
12200            } else if ((changed & ENABLED_MASK) != 0) {
12201                notifyViewAccessibilityStateChangedIfNeeded(
12202                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12203            }
12204        }
12205    }
12206
12207    /**
12208     * Change the view's z order in the tree, so it's on top of other sibling
12209     * views. This ordering change may affect layout, if the parent container
12210     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
12211     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
12212     * method should be followed by calls to {@link #requestLayout()} and
12213     * {@link View#invalidate()} on the view's parent to force the parent to redraw
12214     * with the new child ordering.
12215     *
12216     * @see ViewGroup#bringChildToFront(View)
12217     */
12218    public void bringToFront() {
12219        if (mParent != null) {
12220            mParent.bringChildToFront(this);
12221        }
12222    }
12223
12224    /**
12225     * This is called in response to an internal scroll in this view (i.e., the
12226     * view scrolled its own contents). This is typically as a result of
12227     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
12228     * called.
12229     *
12230     * @param l Current horizontal scroll origin.
12231     * @param t Current vertical scroll origin.
12232     * @param oldl Previous horizontal scroll origin.
12233     * @param oldt Previous vertical scroll origin.
12234     */
12235    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
12236        notifySubtreeAccessibilityStateChangedIfNeeded();
12237
12238        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
12239            postSendViewScrolledAccessibilityEventCallback();
12240        }
12241
12242        mBackgroundSizeChanged = true;
12243        if (mForegroundInfo != null) {
12244            mForegroundInfo.mBoundsChanged = true;
12245        }
12246
12247        final AttachInfo ai = mAttachInfo;
12248        if (ai != null) {
12249            ai.mViewScrollChanged = true;
12250        }
12251
12252        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
12253            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
12254        }
12255    }
12256
12257    /**
12258     * Interface definition for a callback to be invoked when the scroll
12259     * X or Y positions of a view change.
12260     * <p>
12261     * <b>Note:</b> Some views handle scrolling independently from View and may
12262     * have their own separate listeners for scroll-type events. For example,
12263     * {@link android.widget.ListView ListView} allows clients to register an
12264     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
12265     * to listen for changes in list scroll position.
12266     *
12267     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
12268     */
12269    public interface OnScrollChangeListener {
12270        /**
12271         * Called when the scroll position of a view changes.
12272         *
12273         * @param v The view whose scroll position has changed.
12274         * @param scrollX Current horizontal scroll origin.
12275         * @param scrollY Current vertical scroll origin.
12276         * @param oldScrollX Previous horizontal scroll origin.
12277         * @param oldScrollY Previous vertical scroll origin.
12278         */
12279        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
12280    }
12281
12282    /**
12283     * Interface definition for a callback to be invoked when the layout bounds of a view
12284     * changes due to layout processing.
12285     */
12286    public interface OnLayoutChangeListener {
12287        /**
12288         * Called when the layout bounds of a view changes due to layout processing.
12289         *
12290         * @param v The view whose bounds have changed.
12291         * @param left The new value of the view's left property.
12292         * @param top The new value of the view's top property.
12293         * @param right The new value of the view's right property.
12294         * @param bottom The new value of the view's bottom property.
12295         * @param oldLeft The previous value of the view's left property.
12296         * @param oldTop The previous value of the view's top property.
12297         * @param oldRight The previous value of the view's right property.
12298         * @param oldBottom The previous value of the view's bottom property.
12299         */
12300        void onLayoutChange(View v, int left, int top, int right, int bottom,
12301            int oldLeft, int oldTop, int oldRight, int oldBottom);
12302    }
12303
12304    /**
12305     * This is called during layout when the size of this view has changed. If
12306     * you were just added to the view hierarchy, you're called with the old
12307     * values of 0.
12308     *
12309     * @param w Current width of this view.
12310     * @param h Current height of this view.
12311     * @param oldw Old width of this view.
12312     * @param oldh Old height of this view.
12313     */
12314    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
12315    }
12316
12317    /**
12318     * Called by draw to draw the child views. This may be overridden
12319     * by derived classes to gain control just before its children are drawn
12320     * (but after its own view has been drawn).
12321     * @param canvas the canvas on which to draw the view
12322     */
12323    protected void dispatchDraw(Canvas canvas) {
12324
12325    }
12326
12327    /**
12328     * Gets the parent of this view. Note that the parent is a
12329     * ViewParent and not necessarily a View.
12330     *
12331     * @return Parent of this view.
12332     */
12333    public final ViewParent getParent() {
12334        return mParent;
12335    }
12336
12337    /**
12338     * Set the horizontal scrolled position of your view. This will cause a call to
12339     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12340     * invalidated.
12341     * @param value the x position to scroll to
12342     */
12343    public void setScrollX(int value) {
12344        scrollTo(value, mScrollY);
12345    }
12346
12347    /**
12348     * Set the vertical scrolled position of your view. This will cause a call to
12349     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12350     * invalidated.
12351     * @param value the y position to scroll to
12352     */
12353    public void setScrollY(int value) {
12354        scrollTo(mScrollX, value);
12355    }
12356
12357    /**
12358     * Return the scrolled left position of this view. This is the left edge of
12359     * the displayed part of your view. You do not need to draw any pixels
12360     * farther left, since those are outside of the frame of your view on
12361     * screen.
12362     *
12363     * @return The left edge of the displayed part of your view, in pixels.
12364     */
12365    public final int getScrollX() {
12366        return mScrollX;
12367    }
12368
12369    /**
12370     * Return the scrolled top position of this view. This is the top edge of
12371     * the displayed part of your view. You do not need to draw any pixels above
12372     * it, since those are outside of the frame of your view on screen.
12373     *
12374     * @return The top edge of the displayed part of your view, in pixels.
12375     */
12376    public final int getScrollY() {
12377        return mScrollY;
12378    }
12379
12380    /**
12381     * Return the width of the your view.
12382     *
12383     * @return The width of your view, in pixels.
12384     */
12385    @ViewDebug.ExportedProperty(category = "layout")
12386    public final int getWidth() {
12387        return mRight - mLeft;
12388    }
12389
12390    /**
12391     * Return the height of your view.
12392     *
12393     * @return The height of your view, in pixels.
12394     */
12395    @ViewDebug.ExportedProperty(category = "layout")
12396    public final int getHeight() {
12397        return mBottom - mTop;
12398    }
12399
12400    /**
12401     * Return the visible drawing bounds of your view. Fills in the output
12402     * rectangle with the values from getScrollX(), getScrollY(),
12403     * getWidth(), and getHeight(). These bounds do not account for any
12404     * transformation properties currently set on the view, such as
12405     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
12406     *
12407     * @param outRect The (scrolled) drawing bounds of the view.
12408     */
12409    public void getDrawingRect(Rect outRect) {
12410        outRect.left = mScrollX;
12411        outRect.top = mScrollY;
12412        outRect.right = mScrollX + (mRight - mLeft);
12413        outRect.bottom = mScrollY + (mBottom - mTop);
12414    }
12415
12416    /**
12417     * Like {@link #getMeasuredWidthAndState()}, but only returns the
12418     * raw width component (that is the result is masked by
12419     * {@link #MEASURED_SIZE_MASK}).
12420     *
12421     * @return The raw measured width of this view.
12422     */
12423    public final int getMeasuredWidth() {
12424        return mMeasuredWidth & MEASURED_SIZE_MASK;
12425    }
12426
12427    /**
12428     * Return the full width measurement information for this view as computed
12429     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12430     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12431     * This should be used during measurement and layout calculations only. Use
12432     * {@link #getWidth()} to see how wide a view is after layout.
12433     *
12434     * @return The measured width of this view as a bit mask.
12435     */
12436    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12437            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12438                    name = "MEASURED_STATE_TOO_SMALL"),
12439    })
12440    public final int getMeasuredWidthAndState() {
12441        return mMeasuredWidth;
12442    }
12443
12444    /**
12445     * Like {@link #getMeasuredHeightAndState()}, but only returns the
12446     * raw height component (that is the result is masked by
12447     * {@link #MEASURED_SIZE_MASK}).
12448     *
12449     * @return The raw measured height of this view.
12450     */
12451    public final int getMeasuredHeight() {
12452        return mMeasuredHeight & MEASURED_SIZE_MASK;
12453    }
12454
12455    /**
12456     * Return the full height measurement information for this view as computed
12457     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12458     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12459     * This should be used during measurement and layout calculations only. Use
12460     * {@link #getHeight()} to see how wide a view is after layout.
12461     *
12462     * @return The measured height of this view as a bit mask.
12463     */
12464    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12465            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12466                    name = "MEASURED_STATE_TOO_SMALL"),
12467    })
12468    public final int getMeasuredHeightAndState() {
12469        return mMeasuredHeight;
12470    }
12471
12472    /**
12473     * Return only the state bits of {@link #getMeasuredWidthAndState()}
12474     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
12475     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
12476     * and the height component is at the shifted bits
12477     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
12478     */
12479    public final int getMeasuredState() {
12480        return (mMeasuredWidth&MEASURED_STATE_MASK)
12481                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
12482                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
12483    }
12484
12485    /**
12486     * The transform matrix of this view, which is calculated based on the current
12487     * rotation, scale, and pivot properties.
12488     *
12489     * @see #getRotation()
12490     * @see #getScaleX()
12491     * @see #getScaleY()
12492     * @see #getPivotX()
12493     * @see #getPivotY()
12494     * @return The current transform matrix for the view
12495     */
12496    public Matrix getMatrix() {
12497        ensureTransformationInfo();
12498        final Matrix matrix = mTransformationInfo.mMatrix;
12499        mRenderNode.getMatrix(matrix);
12500        return matrix;
12501    }
12502
12503    /**
12504     * Returns true if the transform matrix is the identity matrix.
12505     * Recomputes the matrix if necessary.
12506     *
12507     * @return True if the transform matrix is the identity matrix, false otherwise.
12508     */
12509    final boolean hasIdentityMatrix() {
12510        return mRenderNode.hasIdentityMatrix();
12511    }
12512
12513    void ensureTransformationInfo() {
12514        if (mTransformationInfo == null) {
12515            mTransformationInfo = new TransformationInfo();
12516        }
12517    }
12518
12519    /**
12520     * Utility method to retrieve the inverse of the current mMatrix property.
12521     * We cache the matrix to avoid recalculating it when transform properties
12522     * have not changed.
12523     *
12524     * @return The inverse of the current matrix of this view.
12525     * @hide
12526     */
12527    public final Matrix getInverseMatrix() {
12528        ensureTransformationInfo();
12529        if (mTransformationInfo.mInverseMatrix == null) {
12530            mTransformationInfo.mInverseMatrix = new Matrix();
12531        }
12532        final Matrix matrix = mTransformationInfo.mInverseMatrix;
12533        mRenderNode.getInverseMatrix(matrix);
12534        return matrix;
12535    }
12536
12537    /**
12538     * Gets the distance along the Z axis from the camera to this view.
12539     *
12540     * @see #setCameraDistance(float)
12541     *
12542     * @return The distance along the Z axis.
12543     */
12544    public float getCameraDistance() {
12545        final float dpi = mResources.getDisplayMetrics().densityDpi;
12546        return -(mRenderNode.getCameraDistance() * dpi);
12547    }
12548
12549    /**
12550     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
12551     * views are drawn) from the camera to this view. The camera's distance
12552     * affects 3D transformations, for instance rotations around the X and Y
12553     * axis. If the rotationX or rotationY properties are changed and this view is
12554     * large (more than half the size of the screen), it is recommended to always
12555     * use a camera distance that's greater than the height (X axis rotation) or
12556     * the width (Y axis rotation) of this view.</p>
12557     *
12558     * <p>The distance of the camera from the view plane can have an affect on the
12559     * perspective distortion of the view when it is rotated around the x or y axis.
12560     * For example, a large distance will result in a large viewing angle, and there
12561     * will not be much perspective distortion of the view as it rotates. A short
12562     * distance may cause much more perspective distortion upon rotation, and can
12563     * also result in some drawing artifacts if the rotated view ends up partially
12564     * behind the camera (which is why the recommendation is to use a distance at
12565     * least as far as the size of the view, if the view is to be rotated.)</p>
12566     *
12567     * <p>The distance is expressed in "depth pixels." The default distance depends
12568     * on the screen density. For instance, on a medium density display, the
12569     * default distance is 1280. On a high density display, the default distance
12570     * is 1920.</p>
12571     *
12572     * <p>If you want to specify a distance that leads to visually consistent
12573     * results across various densities, use the following formula:</p>
12574     * <pre>
12575     * float scale = context.getResources().getDisplayMetrics().density;
12576     * view.setCameraDistance(distance * scale);
12577     * </pre>
12578     *
12579     * <p>The density scale factor of a high density display is 1.5,
12580     * and 1920 = 1280 * 1.5.</p>
12581     *
12582     * @param distance The distance in "depth pixels", if negative the opposite
12583     *        value is used
12584     *
12585     * @see #setRotationX(float)
12586     * @see #setRotationY(float)
12587     */
12588    public void setCameraDistance(float distance) {
12589        final float dpi = mResources.getDisplayMetrics().densityDpi;
12590
12591        invalidateViewProperty(true, false);
12592        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
12593        invalidateViewProperty(false, false);
12594
12595        invalidateParentIfNeededAndWasQuickRejected();
12596    }
12597
12598    /**
12599     * The degrees that the view is rotated around the pivot point.
12600     *
12601     * @see #setRotation(float)
12602     * @see #getPivotX()
12603     * @see #getPivotY()
12604     *
12605     * @return The degrees of rotation.
12606     */
12607    @ViewDebug.ExportedProperty(category = "drawing")
12608    public float getRotation() {
12609        return mRenderNode.getRotation();
12610    }
12611
12612    /**
12613     * Sets the degrees that the view is rotated around the pivot point. Increasing values
12614     * result in clockwise rotation.
12615     *
12616     * @param rotation The degrees of rotation.
12617     *
12618     * @see #getRotation()
12619     * @see #getPivotX()
12620     * @see #getPivotY()
12621     * @see #setRotationX(float)
12622     * @see #setRotationY(float)
12623     *
12624     * @attr ref android.R.styleable#View_rotation
12625     */
12626    public void setRotation(float rotation) {
12627        if (rotation != getRotation()) {
12628            // Double-invalidation is necessary to capture view's old and new areas
12629            invalidateViewProperty(true, false);
12630            mRenderNode.setRotation(rotation);
12631            invalidateViewProperty(false, true);
12632
12633            invalidateParentIfNeededAndWasQuickRejected();
12634            notifySubtreeAccessibilityStateChangedIfNeeded();
12635        }
12636    }
12637
12638    /**
12639     * The degrees that the view is rotated around the vertical axis through the pivot point.
12640     *
12641     * @see #getPivotX()
12642     * @see #getPivotY()
12643     * @see #setRotationY(float)
12644     *
12645     * @return The degrees of Y rotation.
12646     */
12647    @ViewDebug.ExportedProperty(category = "drawing")
12648    public float getRotationY() {
12649        return mRenderNode.getRotationY();
12650    }
12651
12652    /**
12653     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
12654     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
12655     * down the y axis.
12656     *
12657     * When rotating large views, it is recommended to adjust the camera distance
12658     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12659     *
12660     * @param rotationY The degrees of Y rotation.
12661     *
12662     * @see #getRotationY()
12663     * @see #getPivotX()
12664     * @see #getPivotY()
12665     * @see #setRotation(float)
12666     * @see #setRotationX(float)
12667     * @see #setCameraDistance(float)
12668     *
12669     * @attr ref android.R.styleable#View_rotationY
12670     */
12671    public void setRotationY(float rotationY) {
12672        if (rotationY != getRotationY()) {
12673            invalidateViewProperty(true, false);
12674            mRenderNode.setRotationY(rotationY);
12675            invalidateViewProperty(false, true);
12676
12677            invalidateParentIfNeededAndWasQuickRejected();
12678            notifySubtreeAccessibilityStateChangedIfNeeded();
12679        }
12680    }
12681
12682    /**
12683     * The degrees that the view is rotated around the horizontal axis through the pivot point.
12684     *
12685     * @see #getPivotX()
12686     * @see #getPivotY()
12687     * @see #setRotationX(float)
12688     *
12689     * @return The degrees of X rotation.
12690     */
12691    @ViewDebug.ExportedProperty(category = "drawing")
12692    public float getRotationX() {
12693        return mRenderNode.getRotationX();
12694    }
12695
12696    /**
12697     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12698     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12699     * x axis.
12700     *
12701     * When rotating large views, it is recommended to adjust the camera distance
12702     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12703     *
12704     * @param rotationX The degrees of X rotation.
12705     *
12706     * @see #getRotationX()
12707     * @see #getPivotX()
12708     * @see #getPivotY()
12709     * @see #setRotation(float)
12710     * @see #setRotationY(float)
12711     * @see #setCameraDistance(float)
12712     *
12713     * @attr ref android.R.styleable#View_rotationX
12714     */
12715    public void setRotationX(float rotationX) {
12716        if (rotationX != getRotationX()) {
12717            invalidateViewProperty(true, false);
12718            mRenderNode.setRotationX(rotationX);
12719            invalidateViewProperty(false, true);
12720
12721            invalidateParentIfNeededAndWasQuickRejected();
12722            notifySubtreeAccessibilityStateChangedIfNeeded();
12723        }
12724    }
12725
12726    /**
12727     * The amount that the view is scaled in x around the pivot point, as a proportion of
12728     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12729     *
12730     * <p>By default, this is 1.0f.
12731     *
12732     * @see #getPivotX()
12733     * @see #getPivotY()
12734     * @return The scaling factor.
12735     */
12736    @ViewDebug.ExportedProperty(category = "drawing")
12737    public float getScaleX() {
12738        return mRenderNode.getScaleX();
12739    }
12740
12741    /**
12742     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12743     * the view's unscaled width. A value of 1 means that no scaling is applied.
12744     *
12745     * @param scaleX The scaling factor.
12746     * @see #getPivotX()
12747     * @see #getPivotY()
12748     *
12749     * @attr ref android.R.styleable#View_scaleX
12750     */
12751    public void setScaleX(float scaleX) {
12752        if (scaleX != getScaleX()) {
12753            invalidateViewProperty(true, false);
12754            mRenderNode.setScaleX(scaleX);
12755            invalidateViewProperty(false, true);
12756
12757            invalidateParentIfNeededAndWasQuickRejected();
12758            notifySubtreeAccessibilityStateChangedIfNeeded();
12759        }
12760    }
12761
12762    /**
12763     * The amount that the view is scaled in y around the pivot point, as a proportion of
12764     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12765     *
12766     * <p>By default, this is 1.0f.
12767     *
12768     * @see #getPivotX()
12769     * @see #getPivotY()
12770     * @return The scaling factor.
12771     */
12772    @ViewDebug.ExportedProperty(category = "drawing")
12773    public float getScaleY() {
12774        return mRenderNode.getScaleY();
12775    }
12776
12777    /**
12778     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12779     * the view's unscaled width. A value of 1 means that no scaling is applied.
12780     *
12781     * @param scaleY The scaling factor.
12782     * @see #getPivotX()
12783     * @see #getPivotY()
12784     *
12785     * @attr ref android.R.styleable#View_scaleY
12786     */
12787    public void setScaleY(float scaleY) {
12788        if (scaleY != getScaleY()) {
12789            invalidateViewProperty(true, false);
12790            mRenderNode.setScaleY(scaleY);
12791            invalidateViewProperty(false, true);
12792
12793            invalidateParentIfNeededAndWasQuickRejected();
12794            notifySubtreeAccessibilityStateChangedIfNeeded();
12795        }
12796    }
12797
12798    /**
12799     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12800     * and {@link #setScaleX(float) scaled}.
12801     *
12802     * @see #getRotation()
12803     * @see #getScaleX()
12804     * @see #getScaleY()
12805     * @see #getPivotY()
12806     * @return The x location of the pivot point.
12807     *
12808     * @attr ref android.R.styleable#View_transformPivotX
12809     */
12810    @ViewDebug.ExportedProperty(category = "drawing")
12811    public float getPivotX() {
12812        return mRenderNode.getPivotX();
12813    }
12814
12815    /**
12816     * Sets the x location of the point around which the view is
12817     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12818     * By default, the pivot point is centered on the object.
12819     * Setting this property disables this behavior and causes the view to use only the
12820     * explicitly set pivotX and pivotY values.
12821     *
12822     * @param pivotX The x location of the pivot point.
12823     * @see #getRotation()
12824     * @see #getScaleX()
12825     * @see #getScaleY()
12826     * @see #getPivotY()
12827     *
12828     * @attr ref android.R.styleable#View_transformPivotX
12829     */
12830    public void setPivotX(float pivotX) {
12831        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12832            invalidateViewProperty(true, false);
12833            mRenderNode.setPivotX(pivotX);
12834            invalidateViewProperty(false, true);
12835
12836            invalidateParentIfNeededAndWasQuickRejected();
12837        }
12838    }
12839
12840    /**
12841     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12842     * and {@link #setScaleY(float) scaled}.
12843     *
12844     * @see #getRotation()
12845     * @see #getScaleX()
12846     * @see #getScaleY()
12847     * @see #getPivotY()
12848     * @return The y location of the pivot point.
12849     *
12850     * @attr ref android.R.styleable#View_transformPivotY
12851     */
12852    @ViewDebug.ExportedProperty(category = "drawing")
12853    public float getPivotY() {
12854        return mRenderNode.getPivotY();
12855    }
12856
12857    /**
12858     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12859     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12860     * Setting this property disables this behavior and causes the view to use only the
12861     * explicitly set pivotX and pivotY values.
12862     *
12863     * @param pivotY The y location of the pivot point.
12864     * @see #getRotation()
12865     * @see #getScaleX()
12866     * @see #getScaleY()
12867     * @see #getPivotY()
12868     *
12869     * @attr ref android.R.styleable#View_transformPivotY
12870     */
12871    public void setPivotY(float pivotY) {
12872        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12873            invalidateViewProperty(true, false);
12874            mRenderNode.setPivotY(pivotY);
12875            invalidateViewProperty(false, true);
12876
12877            invalidateParentIfNeededAndWasQuickRejected();
12878        }
12879    }
12880
12881    /**
12882     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12883     * completely transparent and 1 means the view is completely opaque.
12884     *
12885     * <p>By default this is 1.0f.
12886     * @return The opacity of the view.
12887     */
12888    @ViewDebug.ExportedProperty(category = "drawing")
12889    public float getAlpha() {
12890        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12891    }
12892
12893    /**
12894     * Sets the behavior for overlapping rendering for this view (see {@link
12895     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12896     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12897     * providing the value which is then used internally. That is, when {@link
12898     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12899     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12900     * instead.
12901     *
12902     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12903     * instead of that returned by {@link #hasOverlappingRendering()}.
12904     *
12905     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12906     */
12907    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12908        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12909        if (hasOverlappingRendering) {
12910            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12911        } else {
12912            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12913        }
12914    }
12915
12916    /**
12917     * Returns the value for overlapping rendering that is used internally. This is either
12918     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12919     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12920     *
12921     * @return The value for overlapping rendering being used internally.
12922     */
12923    public final boolean getHasOverlappingRendering() {
12924        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12925                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12926                hasOverlappingRendering();
12927    }
12928
12929    /**
12930     * Returns whether this View has content which overlaps.
12931     *
12932     * <p>This function, intended to be overridden by specific View types, is an optimization when
12933     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12934     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12935     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12936     * directly. An example of overlapping rendering is a TextView with a background image, such as
12937     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12938     * ImageView with only the foreground image. The default implementation returns true; subclasses
12939     * should override if they have cases which can be optimized.</p>
12940     *
12941     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12942     * necessitates that a View return true if it uses the methods internally without passing the
12943     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12944     *
12945     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12946     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12947     *
12948     * @return true if the content in this view might overlap, false otherwise.
12949     */
12950    @ViewDebug.ExportedProperty(category = "drawing")
12951    public boolean hasOverlappingRendering() {
12952        return true;
12953    }
12954
12955    /**
12956     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12957     * completely transparent and 1 means the view is completely opaque.
12958     *
12959     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12960     * can have significant performance implications, especially for large views. It is best to use
12961     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12962     *
12963     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12964     * strongly recommended for performance reasons to either override
12965     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12966     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12967     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12968     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12969     * of rendering cost, even for simple or small views. Starting with
12970     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12971     * applied to the view at the rendering level.</p>
12972     *
12973     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12974     * responsible for applying the opacity itself.</p>
12975     *
12976     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12977     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12978     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12979     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12980     *
12981     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12982     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12983     * {@link #hasOverlappingRendering}.</p>
12984     *
12985     * @param alpha The opacity of the view.
12986     *
12987     * @see #hasOverlappingRendering()
12988     * @see #setLayerType(int, android.graphics.Paint)
12989     *
12990     * @attr ref android.R.styleable#View_alpha
12991     */
12992    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12993        ensureTransformationInfo();
12994        if (mTransformationInfo.mAlpha != alpha) {
12995            // Report visibility changes, which can affect children, to accessibility
12996            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
12997                notifySubtreeAccessibilityStateChangedIfNeeded();
12998            }
12999            mTransformationInfo.mAlpha = alpha;
13000            if (onSetAlpha((int) (alpha * 255))) {
13001                mPrivateFlags |= PFLAG_ALPHA_SET;
13002                // subclass is handling alpha - don't optimize rendering cache invalidation
13003                invalidateParentCaches();
13004                invalidate(true);
13005            } else {
13006                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13007                invalidateViewProperty(true, false);
13008                mRenderNode.setAlpha(getFinalAlpha());
13009            }
13010        }
13011    }
13012
13013    /**
13014     * Faster version of setAlpha() which performs the same steps except there are
13015     * no calls to invalidate(). The caller of this function should perform proper invalidation
13016     * on the parent and this object. The return value indicates whether the subclass handles
13017     * alpha (the return value for onSetAlpha()).
13018     *
13019     * @param alpha The new value for the alpha property
13020     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
13021     *         the new value for the alpha property is different from the old value
13022     */
13023    boolean setAlphaNoInvalidation(float alpha) {
13024        ensureTransformationInfo();
13025        if (mTransformationInfo.mAlpha != alpha) {
13026            mTransformationInfo.mAlpha = alpha;
13027            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
13028            if (subclassHandlesAlpha) {
13029                mPrivateFlags |= PFLAG_ALPHA_SET;
13030                return true;
13031            } else {
13032                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13033                mRenderNode.setAlpha(getFinalAlpha());
13034            }
13035        }
13036        return false;
13037    }
13038
13039    /**
13040     * This property is hidden and intended only for use by the Fade transition, which
13041     * animates it to produce a visual translucency that does not side-effect (or get
13042     * affected by) the real alpha property. This value is composited with the other
13043     * alpha value (and the AlphaAnimation value, when that is present) to produce
13044     * a final visual translucency result, which is what is passed into the DisplayList.
13045     *
13046     * @hide
13047     */
13048    public void setTransitionAlpha(float alpha) {
13049        ensureTransformationInfo();
13050        if (mTransformationInfo.mTransitionAlpha != alpha) {
13051            mTransformationInfo.mTransitionAlpha = alpha;
13052            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13053            invalidateViewProperty(true, false);
13054            mRenderNode.setAlpha(getFinalAlpha());
13055        }
13056    }
13057
13058    /**
13059     * Calculates the visual alpha of this view, which is a combination of the actual
13060     * alpha value and the transitionAlpha value (if set).
13061     */
13062    private float getFinalAlpha() {
13063        if (mTransformationInfo != null) {
13064            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
13065        }
13066        return 1;
13067    }
13068
13069    /**
13070     * This property is hidden and intended only for use by the Fade transition, which
13071     * animates it to produce a visual translucency that does not side-effect (or get
13072     * affected by) the real alpha property. This value is composited with the other
13073     * alpha value (and the AlphaAnimation value, when that is present) to produce
13074     * a final visual translucency result, which is what is passed into the DisplayList.
13075     *
13076     * @hide
13077     */
13078    @ViewDebug.ExportedProperty(category = "drawing")
13079    public float getTransitionAlpha() {
13080        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
13081    }
13082
13083    /**
13084     * Top position of this view relative to its parent.
13085     *
13086     * @return The top of this view, in pixels.
13087     */
13088    @ViewDebug.CapturedViewProperty
13089    public final int getTop() {
13090        return mTop;
13091    }
13092
13093    /**
13094     * Sets the top position of this view relative to its parent. This method is meant to be called
13095     * by the layout system and should not generally be called otherwise, because the property
13096     * may be changed at any time by the layout.
13097     *
13098     * @param top The top of this view, in pixels.
13099     */
13100    public final void setTop(int top) {
13101        if (top != mTop) {
13102            final boolean matrixIsIdentity = hasIdentityMatrix();
13103            if (matrixIsIdentity) {
13104                if (mAttachInfo != null) {
13105                    int minTop;
13106                    int yLoc;
13107                    if (top < mTop) {
13108                        minTop = top;
13109                        yLoc = top - mTop;
13110                    } else {
13111                        minTop = mTop;
13112                        yLoc = 0;
13113                    }
13114                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
13115                }
13116            } else {
13117                // Double-invalidation is necessary to capture view's old and new areas
13118                invalidate(true);
13119            }
13120
13121            int width = mRight - mLeft;
13122            int oldHeight = mBottom - mTop;
13123
13124            mTop = top;
13125            mRenderNode.setTop(mTop);
13126
13127            sizeChange(width, mBottom - mTop, width, oldHeight);
13128
13129            if (!matrixIsIdentity) {
13130                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13131                invalidate(true);
13132            }
13133            mBackgroundSizeChanged = true;
13134            if (mForegroundInfo != null) {
13135                mForegroundInfo.mBoundsChanged = true;
13136            }
13137            invalidateParentIfNeeded();
13138            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13139                // View was rejected last time it was drawn by its parent; this may have changed
13140                invalidateParentIfNeeded();
13141            }
13142        }
13143    }
13144
13145    /**
13146     * Bottom position of this view relative to its parent.
13147     *
13148     * @return The bottom of this view, in pixels.
13149     */
13150    @ViewDebug.CapturedViewProperty
13151    public final int getBottom() {
13152        return mBottom;
13153    }
13154
13155    /**
13156     * True if this view has changed since the last time being drawn.
13157     *
13158     * @return The dirty state of this view.
13159     */
13160    public boolean isDirty() {
13161        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
13162    }
13163
13164    /**
13165     * Sets the bottom position of this view relative to its parent. This method is meant to be
13166     * called by the layout system and should not generally be called otherwise, because the
13167     * property may be changed at any time by the layout.
13168     *
13169     * @param bottom The bottom of this view, in pixels.
13170     */
13171    public final void setBottom(int bottom) {
13172        if (bottom != mBottom) {
13173            final boolean matrixIsIdentity = hasIdentityMatrix();
13174            if (matrixIsIdentity) {
13175                if (mAttachInfo != null) {
13176                    int maxBottom;
13177                    if (bottom < mBottom) {
13178                        maxBottom = mBottom;
13179                    } else {
13180                        maxBottom = bottom;
13181                    }
13182                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
13183                }
13184            } else {
13185                // Double-invalidation is necessary to capture view's old and new areas
13186                invalidate(true);
13187            }
13188
13189            int width = mRight - mLeft;
13190            int oldHeight = mBottom - mTop;
13191
13192            mBottom = bottom;
13193            mRenderNode.setBottom(mBottom);
13194
13195            sizeChange(width, mBottom - mTop, width, oldHeight);
13196
13197            if (!matrixIsIdentity) {
13198                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13199                invalidate(true);
13200            }
13201            mBackgroundSizeChanged = true;
13202            if (mForegroundInfo != null) {
13203                mForegroundInfo.mBoundsChanged = true;
13204            }
13205            invalidateParentIfNeeded();
13206            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13207                // View was rejected last time it was drawn by its parent; this may have changed
13208                invalidateParentIfNeeded();
13209            }
13210        }
13211    }
13212
13213    /**
13214     * Left position of this view relative to its parent.
13215     *
13216     * @return The left edge of this view, in pixels.
13217     */
13218    @ViewDebug.CapturedViewProperty
13219    public final int getLeft() {
13220        return mLeft;
13221    }
13222
13223    /**
13224     * Sets the left position of this view relative to its parent. This method is meant to be called
13225     * by the layout system and should not generally be called otherwise, because the property
13226     * may be changed at any time by the layout.
13227     *
13228     * @param left The left of this view, in pixels.
13229     */
13230    public final void setLeft(int left) {
13231        if (left != mLeft) {
13232            final boolean matrixIsIdentity = hasIdentityMatrix();
13233            if (matrixIsIdentity) {
13234                if (mAttachInfo != null) {
13235                    int minLeft;
13236                    int xLoc;
13237                    if (left < mLeft) {
13238                        minLeft = left;
13239                        xLoc = left - mLeft;
13240                    } else {
13241                        minLeft = mLeft;
13242                        xLoc = 0;
13243                    }
13244                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
13245                }
13246            } else {
13247                // Double-invalidation is necessary to capture view's old and new areas
13248                invalidate(true);
13249            }
13250
13251            int oldWidth = mRight - mLeft;
13252            int height = mBottom - mTop;
13253
13254            mLeft = left;
13255            mRenderNode.setLeft(left);
13256
13257            sizeChange(mRight - mLeft, height, oldWidth, height);
13258
13259            if (!matrixIsIdentity) {
13260                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13261                invalidate(true);
13262            }
13263            mBackgroundSizeChanged = true;
13264            if (mForegroundInfo != null) {
13265                mForegroundInfo.mBoundsChanged = true;
13266            }
13267            invalidateParentIfNeeded();
13268            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13269                // View was rejected last time it was drawn by its parent; this may have changed
13270                invalidateParentIfNeeded();
13271            }
13272        }
13273    }
13274
13275    /**
13276     * Right position of this view relative to its parent.
13277     *
13278     * @return The right edge of this view, in pixels.
13279     */
13280    @ViewDebug.CapturedViewProperty
13281    public final int getRight() {
13282        return mRight;
13283    }
13284
13285    /**
13286     * Sets the right position of this view relative to its parent. This method is meant to be called
13287     * by the layout system and should not generally be called otherwise, because the property
13288     * may be changed at any time by the layout.
13289     *
13290     * @param right The right of this view, in pixels.
13291     */
13292    public final void setRight(int right) {
13293        if (right != mRight) {
13294            final boolean matrixIsIdentity = hasIdentityMatrix();
13295            if (matrixIsIdentity) {
13296                if (mAttachInfo != null) {
13297                    int maxRight;
13298                    if (right < mRight) {
13299                        maxRight = mRight;
13300                    } else {
13301                        maxRight = right;
13302                    }
13303                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
13304                }
13305            } else {
13306                // Double-invalidation is necessary to capture view's old and new areas
13307                invalidate(true);
13308            }
13309
13310            int oldWidth = mRight - mLeft;
13311            int height = mBottom - mTop;
13312
13313            mRight = right;
13314            mRenderNode.setRight(mRight);
13315
13316            sizeChange(mRight - mLeft, height, oldWidth, height);
13317
13318            if (!matrixIsIdentity) {
13319                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13320                invalidate(true);
13321            }
13322            mBackgroundSizeChanged = true;
13323            if (mForegroundInfo != null) {
13324                mForegroundInfo.mBoundsChanged = true;
13325            }
13326            invalidateParentIfNeeded();
13327            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13328                // View was rejected last time it was drawn by its parent; this may have changed
13329                invalidateParentIfNeeded();
13330            }
13331        }
13332    }
13333
13334    /**
13335     * The visual x position of this view, in pixels. This is equivalent to the
13336     * {@link #setTranslationX(float) translationX} property plus the current
13337     * {@link #getLeft() left} property.
13338     *
13339     * @return The visual x position of this view, in pixels.
13340     */
13341    @ViewDebug.ExportedProperty(category = "drawing")
13342    public float getX() {
13343        return mLeft + getTranslationX();
13344    }
13345
13346    /**
13347     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
13348     * {@link #setTranslationX(float) translationX} property to be the difference between
13349     * the x value passed in and the current {@link #getLeft() left} property.
13350     *
13351     * @param x The visual x position of this view, in pixels.
13352     */
13353    public void setX(float x) {
13354        setTranslationX(x - mLeft);
13355    }
13356
13357    /**
13358     * The visual y position of this view, in pixels. This is equivalent to the
13359     * {@link #setTranslationY(float) translationY} property plus the current
13360     * {@link #getTop() top} property.
13361     *
13362     * @return The visual y position of this view, in pixels.
13363     */
13364    @ViewDebug.ExportedProperty(category = "drawing")
13365    public float getY() {
13366        return mTop + getTranslationY();
13367    }
13368
13369    /**
13370     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
13371     * {@link #setTranslationY(float) translationY} property to be the difference between
13372     * the y value passed in and the current {@link #getTop() top} property.
13373     *
13374     * @param y The visual y position of this view, in pixels.
13375     */
13376    public void setY(float y) {
13377        setTranslationY(y - mTop);
13378    }
13379
13380    /**
13381     * The visual z position of this view, in pixels. This is equivalent to the
13382     * {@link #setTranslationZ(float) translationZ} property plus the current
13383     * {@link #getElevation() elevation} property.
13384     *
13385     * @return The visual z position of this view, in pixels.
13386     */
13387    @ViewDebug.ExportedProperty(category = "drawing")
13388    public float getZ() {
13389        return getElevation() + getTranslationZ();
13390    }
13391
13392    /**
13393     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
13394     * {@link #setTranslationZ(float) translationZ} property to be the difference between
13395     * the x value passed in and the current {@link #getElevation() elevation} property.
13396     *
13397     * @param z The visual z position of this view, in pixels.
13398     */
13399    public void setZ(float z) {
13400        setTranslationZ(z - getElevation());
13401    }
13402
13403    /**
13404     * The base elevation of this view relative to its parent, in pixels.
13405     *
13406     * @return The base depth position of the view, in pixels.
13407     */
13408    @ViewDebug.ExportedProperty(category = "drawing")
13409    public float getElevation() {
13410        return mRenderNode.getElevation();
13411    }
13412
13413    /**
13414     * Sets the base elevation of this view, in pixels.
13415     *
13416     * @attr ref android.R.styleable#View_elevation
13417     */
13418    public void setElevation(float elevation) {
13419        if (elevation != getElevation()) {
13420            invalidateViewProperty(true, false);
13421            mRenderNode.setElevation(elevation);
13422            invalidateViewProperty(false, true);
13423
13424            invalidateParentIfNeededAndWasQuickRejected();
13425        }
13426    }
13427
13428    /**
13429     * The horizontal location of this view relative to its {@link #getLeft() left} position.
13430     * This position is post-layout, in addition to wherever the object's
13431     * layout placed it.
13432     *
13433     * @return The horizontal position of this view relative to its left position, in pixels.
13434     */
13435    @ViewDebug.ExportedProperty(category = "drawing")
13436    public float getTranslationX() {
13437        return mRenderNode.getTranslationX();
13438    }
13439
13440    /**
13441     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
13442     * This effectively positions the object post-layout, in addition to wherever the object's
13443     * layout placed it.
13444     *
13445     * @param translationX The horizontal position of this view relative to its left position,
13446     * in pixels.
13447     *
13448     * @attr ref android.R.styleable#View_translationX
13449     */
13450    public void setTranslationX(float translationX) {
13451        if (translationX != getTranslationX()) {
13452            invalidateViewProperty(true, false);
13453            mRenderNode.setTranslationX(translationX);
13454            invalidateViewProperty(false, true);
13455
13456            invalidateParentIfNeededAndWasQuickRejected();
13457            notifySubtreeAccessibilityStateChangedIfNeeded();
13458        }
13459    }
13460
13461    /**
13462     * The vertical location of this view relative to its {@link #getTop() top} position.
13463     * This position is post-layout, in addition to wherever the object's
13464     * layout placed it.
13465     *
13466     * @return The vertical position of this view relative to its top position,
13467     * in pixels.
13468     */
13469    @ViewDebug.ExportedProperty(category = "drawing")
13470    public float getTranslationY() {
13471        return mRenderNode.getTranslationY();
13472    }
13473
13474    /**
13475     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
13476     * This effectively positions the object post-layout, in addition to wherever the object's
13477     * layout placed it.
13478     *
13479     * @param translationY The vertical position of this view relative to its top position,
13480     * in pixels.
13481     *
13482     * @attr ref android.R.styleable#View_translationY
13483     */
13484    public void setTranslationY(float translationY) {
13485        if (translationY != getTranslationY()) {
13486            invalidateViewProperty(true, false);
13487            mRenderNode.setTranslationY(translationY);
13488            invalidateViewProperty(false, true);
13489
13490            invalidateParentIfNeededAndWasQuickRejected();
13491            notifySubtreeAccessibilityStateChangedIfNeeded();
13492        }
13493    }
13494
13495    /**
13496     * The depth location of this view relative to its {@link #getElevation() elevation}.
13497     *
13498     * @return The depth of this view relative to its elevation.
13499     */
13500    @ViewDebug.ExportedProperty(category = "drawing")
13501    public float getTranslationZ() {
13502        return mRenderNode.getTranslationZ();
13503    }
13504
13505    /**
13506     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
13507     *
13508     * @attr ref android.R.styleable#View_translationZ
13509     */
13510    public void setTranslationZ(float translationZ) {
13511        if (translationZ != getTranslationZ()) {
13512            invalidateViewProperty(true, false);
13513            mRenderNode.setTranslationZ(translationZ);
13514            invalidateViewProperty(false, true);
13515
13516            invalidateParentIfNeededAndWasQuickRejected();
13517        }
13518    }
13519
13520    /** @hide */
13521    public void setAnimationMatrix(Matrix matrix) {
13522        invalidateViewProperty(true, false);
13523        mRenderNode.setAnimationMatrix(matrix);
13524        invalidateViewProperty(false, true);
13525
13526        invalidateParentIfNeededAndWasQuickRejected();
13527    }
13528
13529    /**
13530     * Returns the current StateListAnimator if exists.
13531     *
13532     * @return StateListAnimator or null if it does not exists
13533     * @see    #setStateListAnimator(android.animation.StateListAnimator)
13534     */
13535    public StateListAnimator getStateListAnimator() {
13536        return mStateListAnimator;
13537    }
13538
13539    /**
13540     * Attaches the provided StateListAnimator to this View.
13541     * <p>
13542     * Any previously attached StateListAnimator will be detached.
13543     *
13544     * @param stateListAnimator The StateListAnimator to update the view
13545     * @see {@link android.animation.StateListAnimator}
13546     */
13547    public void setStateListAnimator(StateListAnimator stateListAnimator) {
13548        if (mStateListAnimator == stateListAnimator) {
13549            return;
13550        }
13551        if (mStateListAnimator != null) {
13552            mStateListAnimator.setTarget(null);
13553        }
13554        mStateListAnimator = stateListAnimator;
13555        if (stateListAnimator != null) {
13556            stateListAnimator.setTarget(this);
13557            if (isAttachedToWindow()) {
13558                stateListAnimator.setState(getDrawableState());
13559            }
13560        }
13561    }
13562
13563    /**
13564     * Returns whether the Outline should be used to clip the contents of the View.
13565     * <p>
13566     * Note that this flag will only be respected if the View's Outline returns true from
13567     * {@link Outline#canClip()}.
13568     *
13569     * @see #setOutlineProvider(ViewOutlineProvider)
13570     * @see #setClipToOutline(boolean)
13571     */
13572    public final boolean getClipToOutline() {
13573        return mRenderNode.getClipToOutline();
13574    }
13575
13576    /**
13577     * Sets whether the View's Outline should be used to clip the contents of the View.
13578     * <p>
13579     * Only a single non-rectangular clip can be applied on a View at any time.
13580     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
13581     * circular reveal} animation take priority over Outline clipping, and
13582     * child Outline clipping takes priority over Outline clipping done by a
13583     * parent.
13584     * <p>
13585     * Note that this flag will only be respected if the View's Outline returns true from
13586     * {@link Outline#canClip()}.
13587     *
13588     * @see #setOutlineProvider(ViewOutlineProvider)
13589     * @see #getClipToOutline()
13590     */
13591    public void setClipToOutline(boolean clipToOutline) {
13592        damageInParent();
13593        if (getClipToOutline() != clipToOutline) {
13594            mRenderNode.setClipToOutline(clipToOutline);
13595        }
13596    }
13597
13598    // correspond to the enum values of View_outlineProvider
13599    private static final int PROVIDER_BACKGROUND = 0;
13600    private static final int PROVIDER_NONE = 1;
13601    private static final int PROVIDER_BOUNDS = 2;
13602    private static final int PROVIDER_PADDED_BOUNDS = 3;
13603    private void setOutlineProviderFromAttribute(int providerInt) {
13604        switch (providerInt) {
13605            case PROVIDER_BACKGROUND:
13606                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
13607                break;
13608            case PROVIDER_NONE:
13609                setOutlineProvider(null);
13610                break;
13611            case PROVIDER_BOUNDS:
13612                setOutlineProvider(ViewOutlineProvider.BOUNDS);
13613                break;
13614            case PROVIDER_PADDED_BOUNDS:
13615                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
13616                break;
13617        }
13618    }
13619
13620    /**
13621     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
13622     * the shape of the shadow it casts, and enables outline clipping.
13623     * <p>
13624     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
13625     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
13626     * outline provider with this method allows this behavior to be overridden.
13627     * <p>
13628     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
13629     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
13630     * <p>
13631     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
13632     *
13633     * @see #setClipToOutline(boolean)
13634     * @see #getClipToOutline()
13635     * @see #getOutlineProvider()
13636     */
13637    public void setOutlineProvider(ViewOutlineProvider provider) {
13638        mOutlineProvider = provider;
13639        invalidateOutline();
13640    }
13641
13642    /**
13643     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
13644     * that defines the shape of the shadow it casts, and enables outline clipping.
13645     *
13646     * @see #setOutlineProvider(ViewOutlineProvider)
13647     */
13648    public ViewOutlineProvider getOutlineProvider() {
13649        return mOutlineProvider;
13650    }
13651
13652    /**
13653     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
13654     *
13655     * @see #setOutlineProvider(ViewOutlineProvider)
13656     */
13657    public void invalidateOutline() {
13658        rebuildOutline();
13659
13660        notifySubtreeAccessibilityStateChangedIfNeeded();
13661        invalidateViewProperty(false, false);
13662    }
13663
13664    /**
13665     * Internal version of {@link #invalidateOutline()} which invalidates the
13666     * outline without invalidating the view itself. This is intended to be called from
13667     * within methods in the View class itself which are the result of the view being
13668     * invalidated already. For example, when we are drawing the background of a View,
13669     * we invalidate the outline in case it changed in the meantime, but we do not
13670     * need to invalidate the view because we're already drawing the background as part
13671     * of drawing the view in response to an earlier invalidation of the view.
13672     */
13673    private void rebuildOutline() {
13674        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
13675        if (mAttachInfo == null) return;
13676
13677        if (mOutlineProvider == null) {
13678            // no provider, remove outline
13679            mRenderNode.setOutline(null);
13680        } else {
13681            final Outline outline = mAttachInfo.mTmpOutline;
13682            outline.setEmpty();
13683            outline.setAlpha(1.0f);
13684
13685            mOutlineProvider.getOutline(this, outline);
13686            mRenderNode.setOutline(outline);
13687        }
13688    }
13689
13690    /**
13691     * HierarchyViewer only
13692     *
13693     * @hide
13694     */
13695    @ViewDebug.ExportedProperty(category = "drawing")
13696    public boolean hasShadow() {
13697        return mRenderNode.hasShadow();
13698    }
13699
13700
13701    /** @hide */
13702    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13703        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13704        invalidateViewProperty(false, false);
13705    }
13706
13707    /**
13708     * Hit rectangle in parent's coordinates
13709     *
13710     * @param outRect The hit rectangle of the view.
13711     */
13712    public void getHitRect(Rect outRect) {
13713        if (hasIdentityMatrix() || mAttachInfo == null) {
13714            outRect.set(mLeft, mTop, mRight, mBottom);
13715        } else {
13716            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13717            tmpRect.set(0, 0, getWidth(), getHeight());
13718            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13719            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13720                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13721        }
13722    }
13723
13724    /**
13725     * Determines whether the given point, in local coordinates is inside the view.
13726     */
13727    /*package*/ final boolean pointInView(float localX, float localY) {
13728        return pointInView(localX, localY, 0);
13729    }
13730
13731    /**
13732     * Utility method to determine whether the given point, in local coordinates,
13733     * is inside the view, where the area of the view is expanded by the slop factor.
13734     * This method is called while processing touch-move events to determine if the event
13735     * is still within the view.
13736     *
13737     * @hide
13738     */
13739    public boolean pointInView(float localX, float localY, float slop) {
13740        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13741                localY < ((mBottom - mTop) + slop);
13742    }
13743
13744    /**
13745     * When a view has focus and the user navigates away from it, the next view is searched for
13746     * starting from the rectangle filled in by this method.
13747     *
13748     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13749     * of the view.  However, if your view maintains some idea of internal selection,
13750     * such as a cursor, or a selected row or column, you should override this method and
13751     * fill in a more specific rectangle.
13752     *
13753     * @param r The rectangle to fill in, in this view's coordinates.
13754     */
13755    public void getFocusedRect(Rect r) {
13756        getDrawingRect(r);
13757    }
13758
13759    /**
13760     * If some part of this view is not clipped by any of its parents, then
13761     * return that area in r in global (root) coordinates. To convert r to local
13762     * coordinates (without taking possible View rotations into account), offset
13763     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13764     * If the view is completely clipped or translated out, return false.
13765     *
13766     * @param r If true is returned, r holds the global coordinates of the
13767     *        visible portion of this view.
13768     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13769     *        between this view and its root. globalOffet may be null.
13770     * @return true if r is non-empty (i.e. part of the view is visible at the
13771     *         root level.
13772     */
13773    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13774        int width = mRight - mLeft;
13775        int height = mBottom - mTop;
13776        if (width > 0 && height > 0) {
13777            r.set(0, 0, width, height);
13778            if (globalOffset != null) {
13779                globalOffset.set(-mScrollX, -mScrollY);
13780            }
13781            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13782        }
13783        return false;
13784    }
13785
13786    public final boolean getGlobalVisibleRect(Rect r) {
13787        return getGlobalVisibleRect(r, null);
13788    }
13789
13790    public final boolean getLocalVisibleRect(Rect r) {
13791        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13792        if (getGlobalVisibleRect(r, offset)) {
13793            r.offset(-offset.x, -offset.y); // make r local
13794            return true;
13795        }
13796        return false;
13797    }
13798
13799    /**
13800     * Offset this view's vertical location by the specified number of pixels.
13801     *
13802     * @param offset the number of pixels to offset the view by
13803     */
13804    public void offsetTopAndBottom(int offset) {
13805        if (offset != 0) {
13806            final boolean matrixIsIdentity = hasIdentityMatrix();
13807            if (matrixIsIdentity) {
13808                if (isHardwareAccelerated()) {
13809                    invalidateViewProperty(false, false);
13810                } else {
13811                    final ViewParent p = mParent;
13812                    if (p != null && mAttachInfo != null) {
13813                        final Rect r = mAttachInfo.mTmpInvalRect;
13814                        int minTop;
13815                        int maxBottom;
13816                        int yLoc;
13817                        if (offset < 0) {
13818                            minTop = mTop + offset;
13819                            maxBottom = mBottom;
13820                            yLoc = offset;
13821                        } else {
13822                            minTop = mTop;
13823                            maxBottom = mBottom + offset;
13824                            yLoc = 0;
13825                        }
13826                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13827                        p.invalidateChild(this, r);
13828                    }
13829                }
13830            } else {
13831                invalidateViewProperty(false, false);
13832            }
13833
13834            mTop += offset;
13835            mBottom += offset;
13836            mRenderNode.offsetTopAndBottom(offset);
13837            if (isHardwareAccelerated()) {
13838                invalidateViewProperty(false, false);
13839                invalidateParentIfNeededAndWasQuickRejected();
13840            } else {
13841                if (!matrixIsIdentity) {
13842                    invalidateViewProperty(false, true);
13843                }
13844                invalidateParentIfNeeded();
13845            }
13846            notifySubtreeAccessibilityStateChangedIfNeeded();
13847        }
13848    }
13849
13850    /**
13851     * Offset this view's horizontal location by the specified amount of pixels.
13852     *
13853     * @param offset the number of pixels to offset the view by
13854     */
13855    public void offsetLeftAndRight(int offset) {
13856        if (offset != 0) {
13857            final boolean matrixIsIdentity = hasIdentityMatrix();
13858            if (matrixIsIdentity) {
13859                if (isHardwareAccelerated()) {
13860                    invalidateViewProperty(false, false);
13861                } else {
13862                    final ViewParent p = mParent;
13863                    if (p != null && mAttachInfo != null) {
13864                        final Rect r = mAttachInfo.mTmpInvalRect;
13865                        int minLeft;
13866                        int maxRight;
13867                        if (offset < 0) {
13868                            minLeft = mLeft + offset;
13869                            maxRight = mRight;
13870                        } else {
13871                            minLeft = mLeft;
13872                            maxRight = mRight + offset;
13873                        }
13874                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13875                        p.invalidateChild(this, r);
13876                    }
13877                }
13878            } else {
13879                invalidateViewProperty(false, false);
13880            }
13881
13882            mLeft += offset;
13883            mRight += offset;
13884            mRenderNode.offsetLeftAndRight(offset);
13885            if (isHardwareAccelerated()) {
13886                invalidateViewProperty(false, false);
13887                invalidateParentIfNeededAndWasQuickRejected();
13888            } else {
13889                if (!matrixIsIdentity) {
13890                    invalidateViewProperty(false, true);
13891                }
13892                invalidateParentIfNeeded();
13893            }
13894            notifySubtreeAccessibilityStateChangedIfNeeded();
13895        }
13896    }
13897
13898    /**
13899     * Get the LayoutParams associated with this view. All views should have
13900     * layout parameters. These supply parameters to the <i>parent</i> of this
13901     * view specifying how it should be arranged. There are many subclasses of
13902     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13903     * of ViewGroup that are responsible for arranging their children.
13904     *
13905     * This method may return null if this View is not attached to a parent
13906     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13907     * was not invoked successfully. When a View is attached to a parent
13908     * ViewGroup, this method must not return null.
13909     *
13910     * @return The LayoutParams associated with this view, or null if no
13911     *         parameters have been set yet
13912     */
13913    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13914    public ViewGroup.LayoutParams getLayoutParams() {
13915        return mLayoutParams;
13916    }
13917
13918    /**
13919     * Set the layout parameters associated with this view. These supply
13920     * parameters to the <i>parent</i> of this view specifying how it should be
13921     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13922     * correspond to the different subclasses of ViewGroup that are responsible
13923     * for arranging their children.
13924     *
13925     * @param params The layout parameters for this view, cannot be null
13926     */
13927    public void setLayoutParams(ViewGroup.LayoutParams params) {
13928        if (params == null) {
13929            throw new NullPointerException("Layout parameters cannot be null");
13930        }
13931        mLayoutParams = params;
13932        resolveLayoutParams();
13933        if (mParent instanceof ViewGroup) {
13934            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13935        }
13936        requestLayout();
13937    }
13938
13939    /**
13940     * Resolve the layout parameters depending on the resolved layout direction
13941     *
13942     * @hide
13943     */
13944    public void resolveLayoutParams() {
13945        if (mLayoutParams != null) {
13946            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13947        }
13948    }
13949
13950    /**
13951     * Set the scrolled position of your view. This will cause a call to
13952     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13953     * invalidated.
13954     * @param x the x position to scroll to
13955     * @param y the y position to scroll to
13956     */
13957    public void scrollTo(int x, int y) {
13958        if (mScrollX != x || mScrollY != y) {
13959            int oldX = mScrollX;
13960            int oldY = mScrollY;
13961            mScrollX = x;
13962            mScrollY = y;
13963            invalidateParentCaches();
13964            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13965            if (!awakenScrollBars()) {
13966                postInvalidateOnAnimation();
13967            }
13968        }
13969    }
13970
13971    /**
13972     * Move the scrolled position of your view. This will cause a call to
13973     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13974     * invalidated.
13975     * @param x the amount of pixels to scroll by horizontally
13976     * @param y the amount of pixels to scroll by vertically
13977     */
13978    public void scrollBy(int x, int y) {
13979        scrollTo(mScrollX + x, mScrollY + y);
13980    }
13981
13982    /**
13983     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13984     * animation to fade the scrollbars out after a default delay. If a subclass
13985     * provides animated scrolling, the start delay should equal the duration
13986     * of the scrolling animation.</p>
13987     *
13988     * <p>The animation starts only if at least one of the scrollbars is
13989     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13990     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13991     * this method returns true, and false otherwise. If the animation is
13992     * started, this method calls {@link #invalidate()}; in that case the
13993     * caller should not call {@link #invalidate()}.</p>
13994     *
13995     * <p>This method should be invoked every time a subclass directly updates
13996     * the scroll parameters.</p>
13997     *
13998     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13999     * and {@link #scrollTo(int, int)}.</p>
14000     *
14001     * @return true if the animation is played, false otherwise
14002     *
14003     * @see #awakenScrollBars(int)
14004     * @see #scrollBy(int, int)
14005     * @see #scrollTo(int, int)
14006     * @see #isHorizontalScrollBarEnabled()
14007     * @see #isVerticalScrollBarEnabled()
14008     * @see #setHorizontalScrollBarEnabled(boolean)
14009     * @see #setVerticalScrollBarEnabled(boolean)
14010     */
14011    protected boolean awakenScrollBars() {
14012        return mScrollCache != null &&
14013                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
14014    }
14015
14016    /**
14017     * Trigger the scrollbars to draw.
14018     * This method differs from awakenScrollBars() only in its default duration.
14019     * initialAwakenScrollBars() will show the scroll bars for longer than
14020     * usual to give the user more of a chance to notice them.
14021     *
14022     * @return true if the animation is played, false otherwise.
14023     */
14024    private boolean initialAwakenScrollBars() {
14025        return mScrollCache != null &&
14026                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
14027    }
14028
14029    /**
14030     * <p>
14031     * Trigger the scrollbars to draw. When invoked this method starts an
14032     * animation to fade the scrollbars out after a fixed delay. If a subclass
14033     * provides animated scrolling, the start delay should equal the duration of
14034     * the scrolling animation.
14035     * </p>
14036     *
14037     * <p>
14038     * The animation starts only if at least one of the scrollbars is enabled,
14039     * 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 caller
14043     * should not call {@link #invalidate()}.
14044     * </p>
14045     *
14046     * <p>
14047     * This method should be invoked every time a subclass directly updates the
14048     * scroll parameters.
14049     * </p>
14050     *
14051     * @param startDelay the delay, in milliseconds, after which the animation
14052     *        should start; when the delay is 0, the animation starts
14053     *        immediately
14054     * @return true if the animation is played, false otherwise
14055     *
14056     * @see #scrollBy(int, int)
14057     * @see #scrollTo(int, int)
14058     * @see #isHorizontalScrollBarEnabled()
14059     * @see #isVerticalScrollBarEnabled()
14060     * @see #setHorizontalScrollBarEnabled(boolean)
14061     * @see #setVerticalScrollBarEnabled(boolean)
14062     */
14063    protected boolean awakenScrollBars(int startDelay) {
14064        return awakenScrollBars(startDelay, true);
14065    }
14066
14067    /**
14068     * <p>
14069     * Trigger the scrollbars to draw. When invoked this method starts an
14070     * animation to fade the scrollbars out after a fixed delay. If a subclass
14071     * provides animated scrolling, the start delay should equal the duration of
14072     * the scrolling animation.
14073     * </p>
14074     *
14075     * <p>
14076     * The animation starts only if at least one of the scrollbars is enabled,
14077     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14078     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14079     * this method returns true, and false otherwise. If the animation is
14080     * started, this method calls {@link #invalidate()} if the invalidate parameter
14081     * is set to true; in that case the caller
14082     * should not call {@link #invalidate()}.
14083     * </p>
14084     *
14085     * <p>
14086     * This method should be invoked every time a subclass directly updates the
14087     * scroll parameters.
14088     * </p>
14089     *
14090     * @param startDelay the delay, in milliseconds, after which the animation
14091     *        should start; when the delay is 0, the animation starts
14092     *        immediately
14093     *
14094     * @param invalidate Whether this method should call invalidate
14095     *
14096     * @return true if the animation is played, false otherwise
14097     *
14098     * @see #scrollBy(int, int)
14099     * @see #scrollTo(int, int)
14100     * @see #isHorizontalScrollBarEnabled()
14101     * @see #isVerticalScrollBarEnabled()
14102     * @see #setHorizontalScrollBarEnabled(boolean)
14103     * @see #setVerticalScrollBarEnabled(boolean)
14104     */
14105    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
14106        final ScrollabilityCache scrollCache = mScrollCache;
14107
14108        if (scrollCache == null || !scrollCache.fadeScrollBars) {
14109            return false;
14110        }
14111
14112        if (scrollCache.scrollBar == null) {
14113            scrollCache.scrollBar = new ScrollBarDrawable();
14114            scrollCache.scrollBar.setState(getDrawableState());
14115            scrollCache.scrollBar.setCallback(this);
14116        }
14117
14118        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
14119
14120            if (invalidate) {
14121                // Invalidate to show the scrollbars
14122                postInvalidateOnAnimation();
14123            }
14124
14125            if (scrollCache.state == ScrollabilityCache.OFF) {
14126                // FIXME: this is copied from WindowManagerService.
14127                // We should get this value from the system when it
14128                // is possible to do so.
14129                final int KEY_REPEAT_FIRST_DELAY = 750;
14130                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
14131            }
14132
14133            // Tell mScrollCache when we should start fading. This may
14134            // extend the fade start time if one was already scheduled
14135            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
14136            scrollCache.fadeStartTime = fadeStartTime;
14137            scrollCache.state = ScrollabilityCache.ON;
14138
14139            // Schedule our fader to run, unscheduling any old ones first
14140            if (mAttachInfo != null) {
14141                mAttachInfo.mHandler.removeCallbacks(scrollCache);
14142                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
14143            }
14144
14145            return true;
14146        }
14147
14148        return false;
14149    }
14150
14151    /**
14152     * Do not invalidate views which are not visible and which are not running an animation. They
14153     * will not get drawn and they should not set dirty flags as if they will be drawn
14154     */
14155    private boolean skipInvalidate() {
14156        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
14157                (!(mParent instanceof ViewGroup) ||
14158                        !((ViewGroup) mParent).isViewTransitioning(this));
14159    }
14160
14161    /**
14162     * Mark the area defined by dirty as needing to be drawn. If the view is
14163     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14164     * point in the future.
14165     * <p>
14166     * This must be called from a UI thread. To call from a non-UI thread, call
14167     * {@link #postInvalidate()}.
14168     * <p>
14169     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
14170     * {@code dirty}.
14171     *
14172     * @param dirty the rectangle representing the bounds of the dirty region
14173     */
14174    public void invalidate(Rect dirty) {
14175        final int scrollX = mScrollX;
14176        final int scrollY = mScrollY;
14177        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
14178                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
14179    }
14180
14181    /**
14182     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
14183     * coordinates of the dirty rect are relative to the view. If the view is
14184     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14185     * point in the future.
14186     * <p>
14187     * This must be called from a UI thread. To call from a non-UI thread, call
14188     * {@link #postInvalidate()}.
14189     *
14190     * @param l the left position of the dirty region
14191     * @param t the top position of the dirty region
14192     * @param r the right position of the dirty region
14193     * @param b the bottom position of the dirty region
14194     */
14195    public void invalidate(int l, int t, int r, int b) {
14196        final int scrollX = mScrollX;
14197        final int scrollY = mScrollY;
14198        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
14199    }
14200
14201    /**
14202     * Invalidate the whole view. If the view is visible,
14203     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
14204     * the future.
14205     * <p>
14206     * This must be called from a UI thread. To call from a non-UI thread, call
14207     * {@link #postInvalidate()}.
14208     */
14209    public void invalidate() {
14210        invalidate(true);
14211    }
14212
14213    /**
14214     * This is where the invalidate() work actually happens. A full invalidate()
14215     * causes the drawing cache to be invalidated, but this function can be
14216     * called with invalidateCache set to false to skip that invalidation step
14217     * for cases that do not need it (for example, a component that remains at
14218     * the same dimensions with the same content).
14219     *
14220     * @param invalidateCache Whether the drawing cache for this view should be
14221     *            invalidated as well. This is usually true for a full
14222     *            invalidate, but may be set to false if the View's contents or
14223     *            dimensions have not changed.
14224     * @hide
14225     */
14226    public void invalidate(boolean invalidateCache) {
14227        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
14228    }
14229
14230    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
14231            boolean fullInvalidate) {
14232        if (mGhostView != null) {
14233            mGhostView.invalidate(true);
14234            return;
14235        }
14236
14237        if (skipInvalidate()) {
14238            return;
14239        }
14240
14241        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
14242                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
14243                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
14244                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
14245            if (fullInvalidate) {
14246                mLastIsOpaque = isOpaque();
14247                mPrivateFlags &= ~PFLAG_DRAWN;
14248            }
14249
14250            mPrivateFlags |= PFLAG_DIRTY;
14251
14252            if (invalidateCache) {
14253                mPrivateFlags |= PFLAG_INVALIDATED;
14254                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14255            }
14256
14257            // Propagate the damage rectangle to the parent view.
14258            final AttachInfo ai = mAttachInfo;
14259            final ViewParent p = mParent;
14260            if (p != null && ai != null && l < r && t < b) {
14261                final Rect damage = ai.mTmpInvalRect;
14262                damage.set(l, t, r, b);
14263                p.invalidateChild(this, damage);
14264            }
14265
14266            // Damage the entire projection receiver, if necessary.
14267            if (mBackground != null && mBackground.isProjected()) {
14268                final View receiver = getProjectionReceiver();
14269                if (receiver != null) {
14270                    receiver.damageInParent();
14271                }
14272            }
14273        }
14274    }
14275
14276    /**
14277     * @return this view's projection receiver, or {@code null} if none exists
14278     */
14279    private View getProjectionReceiver() {
14280        ViewParent p = getParent();
14281        while (p != null && p instanceof View) {
14282            final View v = (View) p;
14283            if (v.isProjectionReceiver()) {
14284                return v;
14285            }
14286            p = p.getParent();
14287        }
14288
14289        return null;
14290    }
14291
14292    /**
14293     * @return whether the view is a projection receiver
14294     */
14295    private boolean isProjectionReceiver() {
14296        return mBackground != null;
14297    }
14298
14299    /**
14300     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
14301     * set any flags or handle all of the cases handled by the default invalidation methods.
14302     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
14303     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
14304     * walk up the hierarchy, transforming the dirty rect as necessary.
14305     *
14306     * The method also handles normal invalidation logic if display list properties are not
14307     * being used in this view. The invalidateParent and forceRedraw flags are used by that
14308     * backup approach, to handle these cases used in the various property-setting methods.
14309     *
14310     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
14311     * are not being used in this view
14312     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
14313     * list properties are not being used in this view
14314     */
14315    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
14316        if (!isHardwareAccelerated()
14317                || !mRenderNode.isValid()
14318                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
14319            if (invalidateParent) {
14320                invalidateParentCaches();
14321            }
14322            if (forceRedraw) {
14323                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14324            }
14325            invalidate(false);
14326        } else {
14327            damageInParent();
14328        }
14329    }
14330
14331    /**
14332     * Tells the parent view to damage this view's bounds.
14333     *
14334     * @hide
14335     */
14336    protected void damageInParent() {
14337        final AttachInfo ai = mAttachInfo;
14338        final ViewParent p = mParent;
14339        if (p != null && ai != null) {
14340            final Rect r = ai.mTmpInvalRect;
14341            r.set(0, 0, mRight - mLeft, mBottom - mTop);
14342            if (mParent instanceof ViewGroup) {
14343                ((ViewGroup) mParent).damageChild(this, r);
14344            } else {
14345                mParent.invalidateChild(this, r);
14346            }
14347        }
14348    }
14349
14350    /**
14351     * Utility method to transform a given Rect by the current matrix of this view.
14352     */
14353    void transformRect(final Rect rect) {
14354        if (!getMatrix().isIdentity()) {
14355            RectF boundingRect = mAttachInfo.mTmpTransformRect;
14356            boundingRect.set(rect);
14357            getMatrix().mapRect(boundingRect);
14358            rect.set((int) Math.floor(boundingRect.left),
14359                    (int) Math.floor(boundingRect.top),
14360                    (int) Math.ceil(boundingRect.right),
14361                    (int) Math.ceil(boundingRect.bottom));
14362        }
14363    }
14364
14365    /**
14366     * Used to indicate that the parent of this view should clear its caches. This functionality
14367     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14368     * which is necessary when various parent-managed properties of the view change, such as
14369     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
14370     * clears the parent caches and does not causes an invalidate event.
14371     *
14372     * @hide
14373     */
14374    protected void invalidateParentCaches() {
14375        if (mParent instanceof View) {
14376            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
14377        }
14378    }
14379
14380    /**
14381     * Used to indicate that the parent of this view should be invalidated. This functionality
14382     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14383     * which is necessary when various parent-managed properties of the view change, such as
14384     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
14385     * an invalidation event to the parent.
14386     *
14387     * @hide
14388     */
14389    protected void invalidateParentIfNeeded() {
14390        if (isHardwareAccelerated() && mParent instanceof View) {
14391            ((View) mParent).invalidate(true);
14392        }
14393    }
14394
14395    /**
14396     * @hide
14397     */
14398    protected void invalidateParentIfNeededAndWasQuickRejected() {
14399        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
14400            // View was rejected last time it was drawn by its parent; this may have changed
14401            invalidateParentIfNeeded();
14402        }
14403    }
14404
14405    /**
14406     * Indicates whether this View is opaque. An opaque View guarantees that it will
14407     * draw all the pixels overlapping its bounds using a fully opaque color.
14408     *
14409     * Subclasses of View should override this method whenever possible to indicate
14410     * whether an instance is opaque. Opaque Views are treated in a special way by
14411     * the View hierarchy, possibly allowing it to perform optimizations during
14412     * invalidate/draw passes.
14413     *
14414     * @return True if this View is guaranteed to be fully opaque, false otherwise.
14415     */
14416    @ViewDebug.ExportedProperty(category = "drawing")
14417    public boolean isOpaque() {
14418        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
14419                getFinalAlpha() >= 1.0f;
14420    }
14421
14422    /**
14423     * @hide
14424     */
14425    protected void computeOpaqueFlags() {
14426        // Opaque if:
14427        //   - Has a background
14428        //   - Background is opaque
14429        //   - Doesn't have scrollbars or scrollbars overlay
14430
14431        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
14432            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
14433        } else {
14434            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
14435        }
14436
14437        final int flags = mViewFlags;
14438        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
14439                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
14440                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
14441            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
14442        } else {
14443            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
14444        }
14445    }
14446
14447    /**
14448     * @hide
14449     */
14450    protected boolean hasOpaqueScrollbars() {
14451        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
14452    }
14453
14454    /**
14455     * @return A handler associated with the thread running the View. This
14456     * handler can be used to pump events in the UI events queue.
14457     */
14458    public Handler getHandler() {
14459        final AttachInfo attachInfo = mAttachInfo;
14460        if (attachInfo != null) {
14461            return attachInfo.mHandler;
14462        }
14463        return null;
14464    }
14465
14466    /**
14467     * Returns the queue of runnable for this view.
14468     *
14469     * @return the queue of runnables for this view
14470     */
14471    private HandlerActionQueue getRunQueue() {
14472        if (mRunQueue == null) {
14473            mRunQueue = new HandlerActionQueue();
14474        }
14475        return mRunQueue;
14476    }
14477
14478    /**
14479     * Gets the view root associated with the View.
14480     * @return The view root, or null if none.
14481     * @hide
14482     */
14483    public ViewRootImpl getViewRootImpl() {
14484        if (mAttachInfo != null) {
14485            return mAttachInfo.mViewRootImpl;
14486        }
14487        return null;
14488    }
14489
14490    /**
14491     * @hide
14492     */
14493    public ThreadedRenderer getThreadedRenderer() {
14494        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
14495    }
14496
14497    /**
14498     * <p>Causes the Runnable to be added to the message queue.
14499     * The runnable will be run on the user interface thread.</p>
14500     *
14501     * @param action The Runnable that will be executed.
14502     *
14503     * @return Returns true if the Runnable was successfully placed in to the
14504     *         message queue.  Returns false on failure, usually because the
14505     *         looper processing the message queue is exiting.
14506     *
14507     * @see #postDelayed
14508     * @see #removeCallbacks
14509     */
14510    public boolean post(Runnable action) {
14511        final AttachInfo attachInfo = mAttachInfo;
14512        if (attachInfo != null) {
14513            return attachInfo.mHandler.post(action);
14514        }
14515
14516        // Postpone the runnable until we know on which thread it needs to run.
14517        // Assume that the runnable will be successfully placed after attach.
14518        getRunQueue().post(action);
14519        return true;
14520    }
14521
14522    /**
14523     * <p>Causes the Runnable to be added to the message queue, to be run
14524     * after the specified amount of time elapses.
14525     * The runnable will be run on the user interface thread.</p>
14526     *
14527     * @param action The Runnable that will be executed.
14528     * @param delayMillis The delay (in milliseconds) until the Runnable
14529     *        will be executed.
14530     *
14531     * @return true if the Runnable was successfully placed in to the
14532     *         message queue.  Returns false on failure, usually because the
14533     *         looper processing the message queue is exiting.  Note that a
14534     *         result of true does not mean the Runnable will be processed --
14535     *         if the looper is quit before the delivery time of the message
14536     *         occurs then the message will be dropped.
14537     *
14538     * @see #post
14539     * @see #removeCallbacks
14540     */
14541    public boolean postDelayed(Runnable action, long delayMillis) {
14542        final AttachInfo attachInfo = mAttachInfo;
14543        if (attachInfo != null) {
14544            return attachInfo.mHandler.postDelayed(action, delayMillis);
14545        }
14546
14547        // Postpone the runnable until we know on which thread it needs to run.
14548        // Assume that the runnable will be successfully placed after attach.
14549        getRunQueue().postDelayed(action, delayMillis);
14550        return true;
14551    }
14552
14553    /**
14554     * <p>Causes the Runnable to execute on the next animation time step.
14555     * The runnable will be run on the user interface thread.</p>
14556     *
14557     * @param action The Runnable that will be executed.
14558     *
14559     * @see #postOnAnimationDelayed
14560     * @see #removeCallbacks
14561     */
14562    public void postOnAnimation(Runnable action) {
14563        final AttachInfo attachInfo = mAttachInfo;
14564        if (attachInfo != null) {
14565            attachInfo.mViewRootImpl.mChoreographer.postCallback(
14566                    Choreographer.CALLBACK_ANIMATION, action, null);
14567        } else {
14568            // Postpone the runnable until we know
14569            // on which thread it needs to run.
14570            getRunQueue().post(action);
14571        }
14572    }
14573
14574    /**
14575     * <p>Causes the Runnable to execute on the next animation time step,
14576     * after the specified amount of time elapses.
14577     * The runnable will be run on the user interface thread.</p>
14578     *
14579     * @param action The Runnable that will be executed.
14580     * @param delayMillis The delay (in milliseconds) until the Runnable
14581     *        will be executed.
14582     *
14583     * @see #postOnAnimation
14584     * @see #removeCallbacks
14585     */
14586    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14587        final AttachInfo attachInfo = mAttachInfo;
14588        if (attachInfo != null) {
14589            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14590                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14591        } else {
14592            // Postpone the runnable until we know
14593            // on which thread it needs to run.
14594            getRunQueue().postDelayed(action, delayMillis);
14595        }
14596    }
14597
14598    /**
14599     * <p>Removes the specified Runnable from the message queue.</p>
14600     *
14601     * @param action The Runnable to remove from the message handling queue
14602     *
14603     * @return true if this view could ask the Handler to remove the Runnable,
14604     *         false otherwise. When the returned value is true, the Runnable
14605     *         may or may not have been actually removed from the message queue
14606     *         (for instance, if the Runnable was not in the queue already.)
14607     *
14608     * @see #post
14609     * @see #postDelayed
14610     * @see #postOnAnimation
14611     * @see #postOnAnimationDelayed
14612     */
14613    public boolean removeCallbacks(Runnable action) {
14614        if (action != null) {
14615            final AttachInfo attachInfo = mAttachInfo;
14616            if (attachInfo != null) {
14617                attachInfo.mHandler.removeCallbacks(action);
14618                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14619                        Choreographer.CALLBACK_ANIMATION, action, null);
14620            }
14621            getRunQueue().removeCallbacks(action);
14622        }
14623        return true;
14624    }
14625
14626    /**
14627     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14628     * Use this to invalidate the View from a non-UI thread.</p>
14629     *
14630     * <p>This method can be invoked from outside of the UI thread
14631     * only when this View is attached to a window.</p>
14632     *
14633     * @see #invalidate()
14634     * @see #postInvalidateDelayed(long)
14635     */
14636    public void postInvalidate() {
14637        postInvalidateDelayed(0);
14638    }
14639
14640    /**
14641     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14642     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14643     *
14644     * <p>This method can be invoked from outside of the UI thread
14645     * only when this View is attached to a window.</p>
14646     *
14647     * @param left The left coordinate of the rectangle to invalidate.
14648     * @param top The top coordinate of the rectangle to invalidate.
14649     * @param right The right coordinate of the rectangle to invalidate.
14650     * @param bottom The bottom coordinate of the rectangle to invalidate.
14651     *
14652     * @see #invalidate(int, int, int, int)
14653     * @see #invalidate(Rect)
14654     * @see #postInvalidateDelayed(long, int, int, int, int)
14655     */
14656    public void postInvalidate(int left, int top, int right, int bottom) {
14657        postInvalidateDelayed(0, left, top, right, bottom);
14658    }
14659
14660    /**
14661     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14662     * loop. Waits for the specified amount of time.</p>
14663     *
14664     * <p>This method can be invoked from outside of the UI thread
14665     * only when this View is attached to a window.</p>
14666     *
14667     * @param delayMilliseconds the duration in milliseconds to delay the
14668     *         invalidation by
14669     *
14670     * @see #invalidate()
14671     * @see #postInvalidate()
14672     */
14673    public void postInvalidateDelayed(long delayMilliseconds) {
14674        // We try only with the AttachInfo because there's no point in invalidating
14675        // if we are not attached to our window
14676        final AttachInfo attachInfo = mAttachInfo;
14677        if (attachInfo != null) {
14678            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14679        }
14680    }
14681
14682    /**
14683     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14684     * through the event loop. Waits for the specified amount of time.</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 delayMilliseconds the duration in milliseconds to delay the
14690     *         invalidation by
14691     * @param left The left coordinate of the rectangle to invalidate.
14692     * @param top The top coordinate of the rectangle to invalidate.
14693     * @param right The right coordinate of the rectangle to invalidate.
14694     * @param bottom The bottom coordinate of the rectangle to invalidate.
14695     *
14696     * @see #invalidate(int, int, int, int)
14697     * @see #invalidate(Rect)
14698     * @see #postInvalidate(int, int, int, int)
14699     */
14700    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14701            int right, int bottom) {
14702
14703        // We try only with the AttachInfo because there's no point in invalidating
14704        // if we are not attached to our window
14705        final AttachInfo attachInfo = mAttachInfo;
14706        if (attachInfo != null) {
14707            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14708            info.target = this;
14709            info.left = left;
14710            info.top = top;
14711            info.right = right;
14712            info.bottom = bottom;
14713
14714            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14715        }
14716    }
14717
14718    /**
14719     * <p>Cause an invalidate to happen on the next animation time step, typically the
14720     * next display frame.</p>
14721     *
14722     * <p>This method can be invoked from outside of the UI thread
14723     * only when this View is attached to a window.</p>
14724     *
14725     * @see #invalidate()
14726     */
14727    public void postInvalidateOnAnimation() {
14728        // We try only with the AttachInfo because there's no point in invalidating
14729        // if we are not attached to our window
14730        final AttachInfo attachInfo = mAttachInfo;
14731        if (attachInfo != null) {
14732            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14733        }
14734    }
14735
14736    /**
14737     * <p>Cause an invalidate of the specified area to happen on the next animation
14738     * time step, typically the next display frame.</p>
14739     *
14740     * <p>This method can be invoked from outside of the UI thread
14741     * only when this View is attached to a window.</p>
14742     *
14743     * @param left The left coordinate of the rectangle to invalidate.
14744     * @param top The top coordinate of the rectangle to invalidate.
14745     * @param right The right coordinate of the rectangle to invalidate.
14746     * @param bottom The bottom coordinate of the rectangle to invalidate.
14747     *
14748     * @see #invalidate(int, int, int, int)
14749     * @see #invalidate(Rect)
14750     */
14751    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14752        // We try only with the AttachInfo because there's no point in invalidating
14753        // if we are not attached to our window
14754        final AttachInfo attachInfo = mAttachInfo;
14755        if (attachInfo != null) {
14756            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14757            info.target = this;
14758            info.left = left;
14759            info.top = top;
14760            info.right = right;
14761            info.bottom = bottom;
14762
14763            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14764        }
14765    }
14766
14767    /**
14768     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14769     * This event is sent at most once every
14770     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14771     */
14772    private void postSendViewScrolledAccessibilityEventCallback() {
14773        if (mSendViewScrolledAccessibilityEvent == null) {
14774            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14775        }
14776        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14777            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14778            postDelayed(mSendViewScrolledAccessibilityEvent,
14779                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14780        }
14781    }
14782
14783    /**
14784     * Called by a parent to request that a child update its values for mScrollX
14785     * and mScrollY if necessary. This will typically be done if the child is
14786     * animating a scroll using a {@link android.widget.Scroller Scroller}
14787     * object.
14788     */
14789    public void computeScroll() {
14790    }
14791
14792    /**
14793     * <p>Indicate whether the horizontal edges are faded when the view is
14794     * scrolled horizontally.</p>
14795     *
14796     * @return true if the horizontal edges should are faded on scroll, false
14797     *         otherwise
14798     *
14799     * @see #setHorizontalFadingEdgeEnabled(boolean)
14800     *
14801     * @attr ref android.R.styleable#View_requiresFadingEdge
14802     */
14803    public boolean isHorizontalFadingEdgeEnabled() {
14804        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14805    }
14806
14807    /**
14808     * <p>Define whether the horizontal edges should be faded when this view
14809     * is scrolled horizontally.</p>
14810     *
14811     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14812     *                                    be faded when the view is scrolled
14813     *                                    horizontally
14814     *
14815     * @see #isHorizontalFadingEdgeEnabled()
14816     *
14817     * @attr ref android.R.styleable#View_requiresFadingEdge
14818     */
14819    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14820        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14821            if (horizontalFadingEdgeEnabled) {
14822                initScrollCache();
14823            }
14824
14825            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14826        }
14827    }
14828
14829    /**
14830     * <p>Indicate whether the vertical edges are faded when the view is
14831     * scrolled horizontally.</p>
14832     *
14833     * @return true if the vertical edges should are faded on scroll, false
14834     *         otherwise
14835     *
14836     * @see #setVerticalFadingEdgeEnabled(boolean)
14837     *
14838     * @attr ref android.R.styleable#View_requiresFadingEdge
14839     */
14840    public boolean isVerticalFadingEdgeEnabled() {
14841        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14842    }
14843
14844    /**
14845     * <p>Define whether the vertical edges should be faded when this view
14846     * is scrolled vertically.</p>
14847     *
14848     * @param verticalFadingEdgeEnabled true if the vertical edges should
14849     *                                  be faded when the view is scrolled
14850     *                                  vertically
14851     *
14852     * @see #isVerticalFadingEdgeEnabled()
14853     *
14854     * @attr ref android.R.styleable#View_requiresFadingEdge
14855     */
14856    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14857        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14858            if (verticalFadingEdgeEnabled) {
14859                initScrollCache();
14860            }
14861
14862            mViewFlags ^= FADING_EDGE_VERTICAL;
14863        }
14864    }
14865
14866    /**
14867     * Returns the strength, or intensity, of the top faded edge. The strength is
14868     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14869     * returns 0.0 or 1.0 but no value in between.
14870     *
14871     * Subclasses should override this method to provide a smoother fade transition
14872     * when scrolling occurs.
14873     *
14874     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14875     */
14876    protected float getTopFadingEdgeStrength() {
14877        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14878    }
14879
14880    /**
14881     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14882     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14883     * returns 0.0 or 1.0 but no value in between.
14884     *
14885     * Subclasses should override this method to provide a smoother fade transition
14886     * when scrolling occurs.
14887     *
14888     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14889     */
14890    protected float getBottomFadingEdgeStrength() {
14891        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14892                computeVerticalScrollRange() ? 1.0f : 0.0f;
14893    }
14894
14895    /**
14896     * Returns the strength, or intensity, of the left faded edge. The strength is
14897     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14898     * returns 0.0 or 1.0 but no value in between.
14899     *
14900     * Subclasses should override this method to provide a smoother fade transition
14901     * when scrolling occurs.
14902     *
14903     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14904     */
14905    protected float getLeftFadingEdgeStrength() {
14906        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14907    }
14908
14909    /**
14910     * Returns the strength, or intensity, of the right faded edge. The strength is
14911     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14912     * returns 0.0 or 1.0 but no value in between.
14913     *
14914     * Subclasses should override this method to provide a smoother fade transition
14915     * when scrolling occurs.
14916     *
14917     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14918     */
14919    protected float getRightFadingEdgeStrength() {
14920        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14921                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14922    }
14923
14924    /**
14925     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14926     * scrollbar is not drawn by default.</p>
14927     *
14928     * @return true if the horizontal scrollbar should be painted, false
14929     *         otherwise
14930     *
14931     * @see #setHorizontalScrollBarEnabled(boolean)
14932     */
14933    public boolean isHorizontalScrollBarEnabled() {
14934        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14935    }
14936
14937    /**
14938     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14939     * scrollbar is not drawn by default.</p>
14940     *
14941     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14942     *                                   be painted
14943     *
14944     * @see #isHorizontalScrollBarEnabled()
14945     */
14946    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14947        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14948            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14949            computeOpaqueFlags();
14950            resolvePadding();
14951        }
14952    }
14953
14954    /**
14955     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14956     * scrollbar is not drawn by default.</p>
14957     *
14958     * @return true if the vertical scrollbar should be painted, false
14959     *         otherwise
14960     *
14961     * @see #setVerticalScrollBarEnabled(boolean)
14962     */
14963    public boolean isVerticalScrollBarEnabled() {
14964        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14965    }
14966
14967    /**
14968     * <p>Define whether the vertical scrollbar should be drawn or not. The
14969     * scrollbar is not drawn by default.</p>
14970     *
14971     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14972     *                                 be painted
14973     *
14974     * @see #isVerticalScrollBarEnabled()
14975     */
14976    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14977        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14978            mViewFlags ^= SCROLLBARS_VERTICAL;
14979            computeOpaqueFlags();
14980            resolvePadding();
14981        }
14982    }
14983
14984    /**
14985     * @hide
14986     */
14987    protected void recomputePadding() {
14988        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14989    }
14990
14991    /**
14992     * Define whether scrollbars will fade when the view is not scrolling.
14993     *
14994     * @param fadeScrollbars whether to enable fading
14995     *
14996     * @attr ref android.R.styleable#View_fadeScrollbars
14997     */
14998    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14999        initScrollCache();
15000        final ScrollabilityCache scrollabilityCache = mScrollCache;
15001        scrollabilityCache.fadeScrollBars = fadeScrollbars;
15002        if (fadeScrollbars) {
15003            scrollabilityCache.state = ScrollabilityCache.OFF;
15004        } else {
15005            scrollabilityCache.state = ScrollabilityCache.ON;
15006        }
15007    }
15008
15009    /**
15010     *
15011     * Returns true if scrollbars will fade when this view is not scrolling
15012     *
15013     * @return true if scrollbar fading is enabled
15014     *
15015     * @attr ref android.R.styleable#View_fadeScrollbars
15016     */
15017    public boolean isScrollbarFadingEnabled() {
15018        return mScrollCache != null && mScrollCache.fadeScrollBars;
15019    }
15020
15021    /**
15022     *
15023     * Returns the delay before scrollbars fade.
15024     *
15025     * @return the delay before scrollbars fade
15026     *
15027     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15028     */
15029    public int getScrollBarDefaultDelayBeforeFade() {
15030        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
15031                mScrollCache.scrollBarDefaultDelayBeforeFade;
15032    }
15033
15034    /**
15035     * Define the delay before scrollbars fade.
15036     *
15037     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
15038     *
15039     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15040     */
15041    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
15042        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
15043    }
15044
15045    /**
15046     *
15047     * Returns the scrollbar fade duration.
15048     *
15049     * @return the scrollbar fade duration, in milliseconds
15050     *
15051     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15052     */
15053    public int getScrollBarFadeDuration() {
15054        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
15055                mScrollCache.scrollBarFadeDuration;
15056    }
15057
15058    /**
15059     * Define the scrollbar fade duration.
15060     *
15061     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
15062     *
15063     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15064     */
15065    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
15066        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
15067    }
15068
15069    /**
15070     *
15071     * Returns the scrollbar size.
15072     *
15073     * @return the scrollbar size
15074     *
15075     * @attr ref android.R.styleable#View_scrollbarSize
15076     */
15077    public int getScrollBarSize() {
15078        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
15079                mScrollCache.scrollBarSize;
15080    }
15081
15082    /**
15083     * Define the scrollbar size.
15084     *
15085     * @param scrollBarSize - the scrollbar size
15086     *
15087     * @attr ref android.R.styleable#View_scrollbarSize
15088     */
15089    public void setScrollBarSize(int scrollBarSize) {
15090        getScrollCache().scrollBarSize = scrollBarSize;
15091    }
15092
15093    /**
15094     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
15095     * inset. When inset, they add to the padding of the view. And the scrollbars
15096     * can be drawn inside the padding area or on the edge of the view. For example,
15097     * if a view has a background drawable and you want to draw the scrollbars
15098     * inside the padding specified by the drawable, you can use
15099     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
15100     * appear at the edge of the view, ignoring the padding, then you can use
15101     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
15102     * @param style the style of the scrollbars. Should be one of
15103     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
15104     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
15105     * @see #SCROLLBARS_INSIDE_OVERLAY
15106     * @see #SCROLLBARS_INSIDE_INSET
15107     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15108     * @see #SCROLLBARS_OUTSIDE_INSET
15109     *
15110     * @attr ref android.R.styleable#View_scrollbarStyle
15111     */
15112    public void setScrollBarStyle(@ScrollBarStyle int style) {
15113        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
15114            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
15115            computeOpaqueFlags();
15116            resolvePadding();
15117        }
15118    }
15119
15120    /**
15121     * <p>Returns the current scrollbar style.</p>
15122     * @return the current scrollbar style
15123     * @see #SCROLLBARS_INSIDE_OVERLAY
15124     * @see #SCROLLBARS_INSIDE_INSET
15125     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15126     * @see #SCROLLBARS_OUTSIDE_INSET
15127     *
15128     * @attr ref android.R.styleable#View_scrollbarStyle
15129     */
15130    @ViewDebug.ExportedProperty(mapping = {
15131            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
15132            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
15133            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
15134            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
15135    })
15136    @ScrollBarStyle
15137    public int getScrollBarStyle() {
15138        return mViewFlags & SCROLLBARS_STYLE_MASK;
15139    }
15140
15141    /**
15142     * <p>Compute the horizontal range that the horizontal scrollbar
15143     * represents.</p>
15144     *
15145     * <p>The range is expressed in arbitrary units that must be the same as the
15146     * units used by {@link #computeHorizontalScrollExtent()} and
15147     * {@link #computeHorizontalScrollOffset()}.</p>
15148     *
15149     * <p>The default range is the drawing width of this view.</p>
15150     *
15151     * @return the total horizontal range represented by the horizontal
15152     *         scrollbar
15153     *
15154     * @see #computeHorizontalScrollExtent()
15155     * @see #computeHorizontalScrollOffset()
15156     * @see android.widget.ScrollBarDrawable
15157     */
15158    protected int computeHorizontalScrollRange() {
15159        return getWidth();
15160    }
15161
15162    /**
15163     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
15164     * within the horizontal range. This value is used to compute the position
15165     * of the thumb within the scrollbar's track.</p>
15166     *
15167     * <p>The range is expressed in arbitrary units that must be the same as the
15168     * units used by {@link #computeHorizontalScrollRange()} and
15169     * {@link #computeHorizontalScrollExtent()}.</p>
15170     *
15171     * <p>The default offset is the scroll offset of this view.</p>
15172     *
15173     * @return the horizontal offset of the scrollbar's thumb
15174     *
15175     * @see #computeHorizontalScrollRange()
15176     * @see #computeHorizontalScrollExtent()
15177     * @see android.widget.ScrollBarDrawable
15178     */
15179    protected int computeHorizontalScrollOffset() {
15180        return mScrollX;
15181    }
15182
15183    /**
15184     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
15185     * within the horizontal range. This value is used to compute the length
15186     * of the thumb within the scrollbar's track.</p>
15187     *
15188     * <p>The range is expressed in arbitrary units that must be the same as the
15189     * units used by {@link #computeHorizontalScrollRange()} and
15190     * {@link #computeHorizontalScrollOffset()}.</p>
15191     *
15192     * <p>The default extent is the drawing width of this view.</p>
15193     *
15194     * @return the horizontal extent of the scrollbar's thumb
15195     *
15196     * @see #computeHorizontalScrollRange()
15197     * @see #computeHorizontalScrollOffset()
15198     * @see android.widget.ScrollBarDrawable
15199     */
15200    protected int computeHorizontalScrollExtent() {
15201        return getWidth();
15202    }
15203
15204    /**
15205     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
15206     *
15207     * <p>The range is expressed in arbitrary units that must be the same as the
15208     * units used by {@link #computeVerticalScrollExtent()} and
15209     * {@link #computeVerticalScrollOffset()}.</p>
15210     *
15211     * @return the total vertical range represented by the vertical scrollbar
15212     *
15213     * <p>The default range is the drawing height of this view.</p>
15214     *
15215     * @see #computeVerticalScrollExtent()
15216     * @see #computeVerticalScrollOffset()
15217     * @see android.widget.ScrollBarDrawable
15218     */
15219    protected int computeVerticalScrollRange() {
15220        return getHeight();
15221    }
15222
15223    /**
15224     * <p>Compute the vertical offset of the vertical scrollbar's thumb
15225     * within the horizontal range. This value is used to compute the position
15226     * of the thumb within the scrollbar's track.</p>
15227     *
15228     * <p>The range is expressed in arbitrary units that must be the same as the
15229     * units used by {@link #computeVerticalScrollRange()} and
15230     * {@link #computeVerticalScrollExtent()}.</p>
15231     *
15232     * <p>The default offset is the scroll offset of this view.</p>
15233     *
15234     * @return the vertical offset of the scrollbar's thumb
15235     *
15236     * @see #computeVerticalScrollRange()
15237     * @see #computeVerticalScrollExtent()
15238     * @see android.widget.ScrollBarDrawable
15239     */
15240    protected int computeVerticalScrollOffset() {
15241        return mScrollY;
15242    }
15243
15244    /**
15245     * <p>Compute the vertical extent of the vertical scrollbar's thumb
15246     * within the vertical range. This value is used to compute the length
15247     * of the thumb within the scrollbar's track.</p>
15248     *
15249     * <p>The range is expressed in arbitrary units that must be the same as the
15250     * units used by {@link #computeVerticalScrollRange()} and
15251     * {@link #computeVerticalScrollOffset()}.</p>
15252     *
15253     * <p>The default extent is the drawing height of this view.</p>
15254     *
15255     * @return the vertical extent of the scrollbar's thumb
15256     *
15257     * @see #computeVerticalScrollRange()
15258     * @see #computeVerticalScrollOffset()
15259     * @see android.widget.ScrollBarDrawable
15260     */
15261    protected int computeVerticalScrollExtent() {
15262        return getHeight();
15263    }
15264
15265    /**
15266     * Check if this view can be scrolled horizontally in a certain direction.
15267     *
15268     * @param direction Negative to check scrolling left, positive to check scrolling right.
15269     * @return true if this view can be scrolled in the specified direction, false otherwise.
15270     */
15271    public boolean canScrollHorizontally(int direction) {
15272        final int offset = computeHorizontalScrollOffset();
15273        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
15274        if (range == 0) return false;
15275        if (direction < 0) {
15276            return offset > 0;
15277        } else {
15278            return offset < range - 1;
15279        }
15280    }
15281
15282    /**
15283     * Check if this view can be scrolled vertically in a certain direction.
15284     *
15285     * @param direction Negative to check scrolling up, positive to check scrolling down.
15286     * @return true if this view can be scrolled in the specified direction, false otherwise.
15287     */
15288    public boolean canScrollVertically(int direction) {
15289        final int offset = computeVerticalScrollOffset();
15290        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
15291        if (range == 0) return false;
15292        if (direction < 0) {
15293            return offset > 0;
15294        } else {
15295            return offset < range - 1;
15296        }
15297    }
15298
15299    void getScrollIndicatorBounds(@NonNull Rect out) {
15300        out.left = mScrollX;
15301        out.right = mScrollX + mRight - mLeft;
15302        out.top = mScrollY;
15303        out.bottom = mScrollY + mBottom - mTop;
15304    }
15305
15306    private void onDrawScrollIndicators(Canvas c) {
15307        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
15308            // No scroll indicators enabled.
15309            return;
15310        }
15311
15312        final Drawable dr = mScrollIndicatorDrawable;
15313        if (dr == null) {
15314            // Scroll indicators aren't supported here.
15315            return;
15316        }
15317
15318        final int h = dr.getIntrinsicHeight();
15319        final int w = dr.getIntrinsicWidth();
15320        final Rect rect = mAttachInfo.mTmpInvalRect;
15321        getScrollIndicatorBounds(rect);
15322
15323        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
15324            final boolean canScrollUp = canScrollVertically(-1);
15325            if (canScrollUp) {
15326                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
15327                dr.draw(c);
15328            }
15329        }
15330
15331        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
15332            final boolean canScrollDown = canScrollVertically(1);
15333            if (canScrollDown) {
15334                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
15335                dr.draw(c);
15336            }
15337        }
15338
15339        final int leftRtl;
15340        final int rightRtl;
15341        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15342            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
15343            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
15344        } else {
15345            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
15346            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
15347        }
15348
15349        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
15350        if ((mPrivateFlags3 & leftMask) != 0) {
15351            final boolean canScrollLeft = canScrollHorizontally(-1);
15352            if (canScrollLeft) {
15353                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
15354                dr.draw(c);
15355            }
15356        }
15357
15358        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
15359        if ((mPrivateFlags3 & rightMask) != 0) {
15360            final boolean canScrollRight = canScrollHorizontally(1);
15361            if (canScrollRight) {
15362                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
15363                dr.draw(c);
15364            }
15365        }
15366    }
15367
15368    private void getHorizontalScrollBarBounds(Rect bounds) {
15369        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15370        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15371                && !isVerticalScrollBarHidden();
15372        final int size = getHorizontalScrollbarHeight();
15373        final int verticalScrollBarGap = drawVerticalScrollBar ?
15374                getVerticalScrollbarWidth() : 0;
15375        final int width = mRight - mLeft;
15376        final int height = mBottom - mTop;
15377        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
15378        bounds.left = mScrollX + (mPaddingLeft & inside);
15379        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
15380        bounds.bottom = bounds.top + size;
15381    }
15382
15383    private void getVerticalScrollBarBounds(Rect bounds) {
15384        if (mRoundScrollbarRenderer == null) {
15385            getStraightVerticalScrollBarBounds(bounds);
15386        } else {
15387            getRoundVerticalScrollBarBounds(bounds);
15388        }
15389    }
15390
15391    private void getRoundVerticalScrollBarBounds(Rect bounds) {
15392        final int width = mRight - mLeft;
15393        final int height = mBottom - mTop;
15394        // Do not take padding into account as we always want the scrollbars
15395        // to hug the screen for round wearable devices.
15396        bounds.left = mScrollX;
15397        bounds.top = mScrollY;
15398        bounds.right = bounds.left + width;
15399        bounds.bottom = mScrollY + height;
15400    }
15401
15402    private void getStraightVerticalScrollBarBounds(Rect bounds) {
15403        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15404        final int size = getVerticalScrollbarWidth();
15405        int verticalScrollbarPosition = mVerticalScrollbarPosition;
15406        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
15407            verticalScrollbarPosition = isLayoutRtl() ?
15408                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
15409        }
15410        final int width = mRight - mLeft;
15411        final int height = mBottom - mTop;
15412        switch (verticalScrollbarPosition) {
15413            default:
15414            case SCROLLBAR_POSITION_RIGHT:
15415                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
15416                break;
15417            case SCROLLBAR_POSITION_LEFT:
15418                bounds.left = mScrollX + (mUserPaddingLeft & inside);
15419                break;
15420        }
15421        bounds.top = mScrollY + (mPaddingTop & inside);
15422        bounds.right = bounds.left + size;
15423        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
15424    }
15425
15426    /**
15427     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
15428     * scrollbars are painted only if they have been awakened first.</p>
15429     *
15430     * @param canvas the canvas on which to draw the scrollbars
15431     *
15432     * @see #awakenScrollBars(int)
15433     */
15434    protected final void onDrawScrollBars(Canvas canvas) {
15435        // scrollbars are drawn only when the animation is running
15436        final ScrollabilityCache cache = mScrollCache;
15437
15438        if (cache != null) {
15439
15440            int state = cache.state;
15441
15442            if (state == ScrollabilityCache.OFF) {
15443                return;
15444            }
15445
15446            boolean invalidate = false;
15447
15448            if (state == ScrollabilityCache.FADING) {
15449                // We're fading -- get our fade interpolation
15450                if (cache.interpolatorValues == null) {
15451                    cache.interpolatorValues = new float[1];
15452                }
15453
15454                float[] values = cache.interpolatorValues;
15455
15456                // Stops the animation if we're done
15457                if (cache.scrollBarInterpolator.timeToValues(values) ==
15458                        Interpolator.Result.FREEZE_END) {
15459                    cache.state = ScrollabilityCache.OFF;
15460                } else {
15461                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
15462                }
15463
15464                // This will make the scroll bars inval themselves after
15465                // drawing. We only want this when we're fading so that
15466                // we prevent excessive redraws
15467                invalidate = true;
15468            } else {
15469                // We're just on -- but we may have been fading before so
15470                // reset alpha
15471                cache.scrollBar.mutate().setAlpha(255);
15472            }
15473
15474            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
15475            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15476                    && !isVerticalScrollBarHidden();
15477
15478            // Fork out the scroll bar drawing for round wearable devices.
15479            if (mRoundScrollbarRenderer != null) {
15480                if (drawVerticalScrollBar) {
15481                    final Rect bounds = cache.mScrollBarBounds;
15482                    getVerticalScrollBarBounds(bounds);
15483                    mRoundScrollbarRenderer.drawRoundScrollbars(
15484                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
15485                    if (invalidate) {
15486                        invalidate();
15487                    }
15488                }
15489                // Do not draw horizontal scroll bars for round wearable devices.
15490            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
15491                final ScrollBarDrawable scrollBar = cache.scrollBar;
15492
15493                if (drawHorizontalScrollBar) {
15494                    scrollBar.setParameters(computeHorizontalScrollRange(),
15495                            computeHorizontalScrollOffset(),
15496                            computeHorizontalScrollExtent(), false);
15497                    final Rect bounds = cache.mScrollBarBounds;
15498                    getHorizontalScrollBarBounds(bounds);
15499                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15500                            bounds.right, bounds.bottom);
15501                    if (invalidate) {
15502                        invalidate(bounds);
15503                    }
15504                }
15505
15506                if (drawVerticalScrollBar) {
15507                    scrollBar.setParameters(computeVerticalScrollRange(),
15508                            computeVerticalScrollOffset(),
15509                            computeVerticalScrollExtent(), true);
15510                    final Rect bounds = cache.mScrollBarBounds;
15511                    getVerticalScrollBarBounds(bounds);
15512                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15513                            bounds.right, bounds.bottom);
15514                    if (invalidate) {
15515                        invalidate(bounds);
15516                    }
15517                }
15518            }
15519        }
15520    }
15521
15522    /**
15523     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
15524     * FastScroller is visible.
15525     * @return whether to temporarily hide the vertical scrollbar
15526     * @hide
15527     */
15528    protected boolean isVerticalScrollBarHidden() {
15529        return false;
15530    }
15531
15532    /**
15533     * <p>Draw the horizontal scrollbar if
15534     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
15535     *
15536     * @param canvas the canvas on which to draw the scrollbar
15537     * @param scrollBar the scrollbar's drawable
15538     *
15539     * @see #isHorizontalScrollBarEnabled()
15540     * @see #computeHorizontalScrollRange()
15541     * @see #computeHorizontalScrollExtent()
15542     * @see #computeHorizontalScrollOffset()
15543     * @see android.widget.ScrollBarDrawable
15544     * @hide
15545     */
15546    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
15547            int l, int t, int r, int b) {
15548        scrollBar.setBounds(l, t, r, b);
15549        scrollBar.draw(canvas);
15550    }
15551
15552    /**
15553     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
15554     * returns true.</p>
15555     *
15556     * @param canvas the canvas on which to draw the scrollbar
15557     * @param scrollBar the scrollbar's drawable
15558     *
15559     * @see #isVerticalScrollBarEnabled()
15560     * @see #computeVerticalScrollRange()
15561     * @see #computeVerticalScrollExtent()
15562     * @see #computeVerticalScrollOffset()
15563     * @see android.widget.ScrollBarDrawable
15564     * @hide
15565     */
15566    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
15567            int l, int t, int r, int b) {
15568        scrollBar.setBounds(l, t, r, b);
15569        scrollBar.draw(canvas);
15570    }
15571
15572    /**
15573     * Implement this to do your drawing.
15574     *
15575     * @param canvas the canvas on which the background will be drawn
15576     */
15577    protected void onDraw(Canvas canvas) {
15578    }
15579
15580    /*
15581     * Caller is responsible for calling requestLayout if necessary.
15582     * (This allows addViewInLayout to not request a new layout.)
15583     */
15584    void assignParent(ViewParent parent) {
15585        if (mParent == null) {
15586            mParent = parent;
15587        } else if (parent == null) {
15588            mParent = null;
15589        } else {
15590            throw new RuntimeException("view " + this + " being added, but"
15591                    + " it already has a parent");
15592        }
15593    }
15594
15595    /**
15596     * This is called when the view is attached to a window.  At this point it
15597     * has a Surface and will start drawing.  Note that this function is
15598     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15599     * however it may be called any time before the first onDraw -- including
15600     * before or after {@link #onMeasure(int, int)}.
15601     *
15602     * @see #onDetachedFromWindow()
15603     */
15604    @CallSuper
15605    protected void onAttachedToWindow() {
15606        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15607            mParent.requestTransparentRegion(this);
15608        }
15609
15610        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15611
15612        jumpDrawablesToCurrentState();
15613
15614        resetSubtreeAccessibilityStateChanged();
15615
15616        // rebuild, since Outline not maintained while View is detached
15617        rebuildOutline();
15618
15619        if (isFocused()) {
15620            InputMethodManager imm = InputMethodManager.peekInstance();
15621            if (imm != null) {
15622                imm.focusIn(this);
15623            }
15624        }
15625    }
15626
15627    /**
15628     * Resolve all RTL related properties.
15629     *
15630     * @return true if resolution of RTL properties has been done
15631     *
15632     * @hide
15633     */
15634    public boolean resolveRtlPropertiesIfNeeded() {
15635        if (!needRtlPropertiesResolution()) return false;
15636
15637        // Order is important here: LayoutDirection MUST be resolved first
15638        if (!isLayoutDirectionResolved()) {
15639            resolveLayoutDirection();
15640            resolveLayoutParams();
15641        }
15642        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15643        if (!isTextDirectionResolved()) {
15644            resolveTextDirection();
15645        }
15646        if (!isTextAlignmentResolved()) {
15647            resolveTextAlignment();
15648        }
15649        // Should resolve Drawables before Padding because we need the layout direction of the
15650        // Drawable to correctly resolve Padding.
15651        if (!areDrawablesResolved()) {
15652            resolveDrawables();
15653        }
15654        if (!isPaddingResolved()) {
15655            resolvePadding();
15656        }
15657        onRtlPropertiesChanged(getLayoutDirection());
15658        return true;
15659    }
15660
15661    /**
15662     * Reset resolution of all RTL related properties.
15663     *
15664     * @hide
15665     */
15666    public void resetRtlProperties() {
15667        resetResolvedLayoutDirection();
15668        resetResolvedTextDirection();
15669        resetResolvedTextAlignment();
15670        resetResolvedPadding();
15671        resetResolvedDrawables();
15672    }
15673
15674    /**
15675     * @see #onScreenStateChanged(int)
15676     */
15677    void dispatchScreenStateChanged(int screenState) {
15678        onScreenStateChanged(screenState);
15679    }
15680
15681    /**
15682     * This method is called whenever the state of the screen this view is
15683     * attached to changes. A state change will usually occurs when the screen
15684     * turns on or off (whether it happens automatically or the user does it
15685     * manually.)
15686     *
15687     * @param screenState The new state of the screen. Can be either
15688     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15689     */
15690    public void onScreenStateChanged(int screenState) {
15691    }
15692
15693    /**
15694     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
15695     */
15696    private boolean hasRtlSupport() {
15697        return mContext.getApplicationInfo().hasRtlSupport();
15698    }
15699
15700    /**
15701     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15702     * RTL not supported)
15703     */
15704    private boolean isRtlCompatibilityMode() {
15705        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15706        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15707    }
15708
15709    /**
15710     * @return true if RTL properties need resolution.
15711     *
15712     */
15713    private boolean needRtlPropertiesResolution() {
15714        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15715    }
15716
15717    /**
15718     * Called when any RTL property (layout direction or text direction or text alignment) has
15719     * been changed.
15720     *
15721     * Subclasses need to override this method to take care of cached information that depends on the
15722     * resolved layout direction, or to inform child views that inherit their layout direction.
15723     *
15724     * The default implementation does nothing.
15725     *
15726     * @param layoutDirection the direction of the layout
15727     *
15728     * @see #LAYOUT_DIRECTION_LTR
15729     * @see #LAYOUT_DIRECTION_RTL
15730     */
15731    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15732    }
15733
15734    /**
15735     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15736     * that the parent directionality can and will be resolved before its children.
15737     *
15738     * @return true if resolution has been done, false otherwise.
15739     *
15740     * @hide
15741     */
15742    public boolean resolveLayoutDirection() {
15743        // Clear any previous layout direction resolution
15744        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15745
15746        if (hasRtlSupport()) {
15747            // Set resolved depending on layout direction
15748            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15749                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15750                case LAYOUT_DIRECTION_INHERIT:
15751                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15752                    // later to get the correct resolved value
15753                    if (!canResolveLayoutDirection()) return false;
15754
15755                    // Parent has not yet resolved, LTR is still the default
15756                    try {
15757                        if (!mParent.isLayoutDirectionResolved()) return false;
15758
15759                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15760                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15761                        }
15762                    } catch (AbstractMethodError e) {
15763                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15764                                " does not fully implement ViewParent", e);
15765                    }
15766                    break;
15767                case LAYOUT_DIRECTION_RTL:
15768                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15769                    break;
15770                case LAYOUT_DIRECTION_LOCALE:
15771                    if((LAYOUT_DIRECTION_RTL ==
15772                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15773                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15774                    }
15775                    break;
15776                default:
15777                    // Nothing to do, LTR by default
15778            }
15779        }
15780
15781        // Set to resolved
15782        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15783        return true;
15784    }
15785
15786    /**
15787     * Check if layout direction resolution can be done.
15788     *
15789     * @return true if layout direction resolution can be done otherwise return false.
15790     */
15791    public boolean canResolveLayoutDirection() {
15792        switch (getRawLayoutDirection()) {
15793            case LAYOUT_DIRECTION_INHERIT:
15794                if (mParent != null) {
15795                    try {
15796                        return mParent.canResolveLayoutDirection();
15797                    } catch (AbstractMethodError e) {
15798                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15799                                " does not fully implement ViewParent", e);
15800                    }
15801                }
15802                return false;
15803
15804            default:
15805                return true;
15806        }
15807    }
15808
15809    /**
15810     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15811     * {@link #onMeasure(int, int)}.
15812     *
15813     * @hide
15814     */
15815    public void resetResolvedLayoutDirection() {
15816        // Reset the current resolved bits
15817        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15818    }
15819
15820    /**
15821     * @return true if the layout direction is inherited.
15822     *
15823     * @hide
15824     */
15825    public boolean isLayoutDirectionInherited() {
15826        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15827    }
15828
15829    /**
15830     * @return true if layout direction has been resolved.
15831     */
15832    public boolean isLayoutDirectionResolved() {
15833        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15834    }
15835
15836    /**
15837     * Return if padding has been resolved
15838     *
15839     * @hide
15840     */
15841    boolean isPaddingResolved() {
15842        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15843    }
15844
15845    /**
15846     * Resolves padding depending on layout direction, if applicable, and
15847     * recomputes internal padding values to adjust for scroll bars.
15848     *
15849     * @hide
15850     */
15851    public void resolvePadding() {
15852        final int resolvedLayoutDirection = getLayoutDirection();
15853
15854        if (!isRtlCompatibilityMode()) {
15855            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15856            // If start / end padding are defined, they will be resolved (hence overriding) to
15857            // left / right or right / left depending on the resolved layout direction.
15858            // If start / end padding are not defined, use the left / right ones.
15859            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15860                Rect padding = sThreadLocal.get();
15861                if (padding == null) {
15862                    padding = new Rect();
15863                    sThreadLocal.set(padding);
15864                }
15865                mBackground.getPadding(padding);
15866                if (!mLeftPaddingDefined) {
15867                    mUserPaddingLeftInitial = padding.left;
15868                }
15869                if (!mRightPaddingDefined) {
15870                    mUserPaddingRightInitial = padding.right;
15871                }
15872            }
15873            switch (resolvedLayoutDirection) {
15874                case LAYOUT_DIRECTION_RTL:
15875                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15876                        mUserPaddingRight = mUserPaddingStart;
15877                    } else {
15878                        mUserPaddingRight = mUserPaddingRightInitial;
15879                    }
15880                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15881                        mUserPaddingLeft = mUserPaddingEnd;
15882                    } else {
15883                        mUserPaddingLeft = mUserPaddingLeftInitial;
15884                    }
15885                    break;
15886                case LAYOUT_DIRECTION_LTR:
15887                default:
15888                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15889                        mUserPaddingLeft = mUserPaddingStart;
15890                    } else {
15891                        mUserPaddingLeft = mUserPaddingLeftInitial;
15892                    }
15893                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15894                        mUserPaddingRight = mUserPaddingEnd;
15895                    } else {
15896                        mUserPaddingRight = mUserPaddingRightInitial;
15897                    }
15898            }
15899
15900            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15901        }
15902
15903        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15904        onRtlPropertiesChanged(resolvedLayoutDirection);
15905
15906        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15907    }
15908
15909    /**
15910     * Reset the resolved layout direction.
15911     *
15912     * @hide
15913     */
15914    public void resetResolvedPadding() {
15915        resetResolvedPaddingInternal();
15916    }
15917
15918    /**
15919     * Used when we only want to reset *this* view's padding and not trigger overrides
15920     * in ViewGroup that reset children too.
15921     */
15922    void resetResolvedPaddingInternal() {
15923        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15924    }
15925
15926    /**
15927     * This is called when the view is detached from a window.  At this point it
15928     * no longer has a surface for drawing.
15929     *
15930     * @see #onAttachedToWindow()
15931     */
15932    @CallSuper
15933    protected void onDetachedFromWindow() {
15934    }
15935
15936    /**
15937     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15938     * after onDetachedFromWindow().
15939     *
15940     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15941     * The super method should be called at the end of the overridden method to ensure
15942     * subclasses are destroyed first
15943     *
15944     * @hide
15945     */
15946    @CallSuper
15947    protected void onDetachedFromWindowInternal() {
15948        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15949        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15950        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15951
15952        removeUnsetPressCallback();
15953        removeLongPressCallback();
15954        removePerformClickCallback();
15955        removeSendViewScrolledAccessibilityEventCallback();
15956        stopNestedScroll();
15957
15958        // Anything that started animating right before detach should already
15959        // be in its final state when re-attached.
15960        jumpDrawablesToCurrentState();
15961
15962        destroyDrawingCache();
15963
15964        cleanupDraw();
15965        mCurrentAnimation = null;
15966
15967        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
15968            hideTooltip();
15969        }
15970    }
15971
15972    private void cleanupDraw() {
15973        resetDisplayList();
15974        if (mAttachInfo != null) {
15975            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15976        }
15977    }
15978
15979    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15980    }
15981
15982    /**
15983     * @return The number of times this view has been attached to a window
15984     */
15985    protected int getWindowAttachCount() {
15986        return mWindowAttachCount;
15987    }
15988
15989    /**
15990     * Retrieve a unique token identifying the window this view is attached to.
15991     * @return Return the window's token for use in
15992     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15993     */
15994    public IBinder getWindowToken() {
15995        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15996    }
15997
15998    /**
15999     * Retrieve the {@link WindowId} for the window this view is
16000     * currently attached to.
16001     */
16002    public WindowId getWindowId() {
16003        if (mAttachInfo == null) {
16004            return null;
16005        }
16006        if (mAttachInfo.mWindowId == null) {
16007            try {
16008                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
16009                        mAttachInfo.mWindowToken);
16010                mAttachInfo.mWindowId = new WindowId(
16011                        mAttachInfo.mIWindowId);
16012            } catch (RemoteException e) {
16013            }
16014        }
16015        return mAttachInfo.mWindowId;
16016    }
16017
16018    /**
16019     * Retrieve a unique token identifying the top-level "real" window of
16020     * the window that this view is attached to.  That is, this is like
16021     * {@link #getWindowToken}, except if the window this view in is a panel
16022     * window (attached to another containing window), then the token of
16023     * the containing window is returned instead.
16024     *
16025     * @return Returns the associated window token, either
16026     * {@link #getWindowToken()} or the containing window's token.
16027     */
16028    public IBinder getApplicationWindowToken() {
16029        AttachInfo ai = mAttachInfo;
16030        if (ai != null) {
16031            IBinder appWindowToken = ai.mPanelParentWindowToken;
16032            if (appWindowToken == null) {
16033                appWindowToken = ai.mWindowToken;
16034            }
16035            return appWindowToken;
16036        }
16037        return null;
16038    }
16039
16040    /**
16041     * Gets the logical display to which the view's window has been attached.
16042     *
16043     * @return The logical display, or null if the view is not currently attached to a window.
16044     */
16045    public Display getDisplay() {
16046        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
16047    }
16048
16049    /**
16050     * Retrieve private session object this view hierarchy is using to
16051     * communicate with the window manager.
16052     * @return the session object to communicate with the window manager
16053     */
16054    /*package*/ IWindowSession getWindowSession() {
16055        return mAttachInfo != null ? mAttachInfo.mSession : null;
16056    }
16057
16058    /**
16059     * Return the visibility value of the least visible component passed.
16060     */
16061    int combineVisibility(int vis1, int vis2) {
16062        // This works because VISIBLE < INVISIBLE < GONE.
16063        return Math.max(vis1, vis2);
16064    }
16065
16066    /**
16067     * @param info the {@link android.view.View.AttachInfo} to associated with
16068     *        this view
16069     */
16070    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
16071        mAttachInfo = info;
16072        if (mOverlay != null) {
16073            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
16074        }
16075        mWindowAttachCount++;
16076        // We will need to evaluate the drawable state at least once.
16077        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16078        if (mFloatingTreeObserver != null) {
16079            info.mTreeObserver.merge(mFloatingTreeObserver);
16080            mFloatingTreeObserver = null;
16081        }
16082
16083        registerPendingFrameMetricsObservers();
16084
16085        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
16086            mAttachInfo.mScrollContainers.add(this);
16087            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
16088        }
16089        // Transfer all pending runnables.
16090        if (mRunQueue != null) {
16091            mRunQueue.executeActions(info.mHandler);
16092            mRunQueue = null;
16093        }
16094        performCollectViewAttributes(mAttachInfo, visibility);
16095        onAttachedToWindow();
16096
16097        ListenerInfo li = mListenerInfo;
16098        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16099                li != null ? li.mOnAttachStateChangeListeners : null;
16100        if (listeners != null && listeners.size() > 0) {
16101            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16102            // perform the dispatching. The iterator is a safe guard against listeners that
16103            // could mutate the list by calling the various add/remove methods. This prevents
16104            // the array from being modified while we iterate it.
16105            for (OnAttachStateChangeListener listener : listeners) {
16106                listener.onViewAttachedToWindow(this);
16107            }
16108        }
16109
16110        int vis = info.mWindowVisibility;
16111        if (vis != GONE) {
16112            onWindowVisibilityChanged(vis);
16113            if (isShown()) {
16114                // Calling onVisibilityAggregated directly here since the subtree will also
16115                // receive dispatchAttachedToWindow and this same call
16116                onVisibilityAggregated(vis == VISIBLE);
16117            }
16118        }
16119
16120        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
16121        // As all views in the subtree will already receive dispatchAttachedToWindow
16122        // traversing the subtree again here is not desired.
16123        onVisibilityChanged(this, visibility);
16124
16125        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
16126            // If nobody has evaluated the drawable state yet, then do it now.
16127            refreshDrawableState();
16128        }
16129        needGlobalAttributesUpdate(false);
16130    }
16131
16132    void dispatchDetachedFromWindow() {
16133        AttachInfo info = mAttachInfo;
16134        if (info != null) {
16135            int vis = info.mWindowVisibility;
16136            if (vis != GONE) {
16137                onWindowVisibilityChanged(GONE);
16138                if (isShown()) {
16139                    // Invoking onVisibilityAggregated directly here since the subtree
16140                    // will also receive detached from window
16141                    onVisibilityAggregated(false);
16142                }
16143            }
16144        }
16145
16146        onDetachedFromWindow();
16147        onDetachedFromWindowInternal();
16148
16149        InputMethodManager imm = InputMethodManager.peekInstance();
16150        if (imm != null) {
16151            imm.onViewDetachedFromWindow(this);
16152        }
16153
16154        ListenerInfo li = mListenerInfo;
16155        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16156                li != null ? li.mOnAttachStateChangeListeners : null;
16157        if (listeners != null && listeners.size() > 0) {
16158            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16159            // perform the dispatching. The iterator is a safe guard against listeners that
16160            // could mutate the list by calling the various add/remove methods. This prevents
16161            // the array from being modified while we iterate it.
16162            for (OnAttachStateChangeListener listener : listeners) {
16163                listener.onViewDetachedFromWindow(this);
16164            }
16165        }
16166
16167        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
16168            mAttachInfo.mScrollContainers.remove(this);
16169            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
16170        }
16171
16172        mAttachInfo = null;
16173        if (mOverlay != null) {
16174            mOverlay.getOverlayView().dispatchDetachedFromWindow();
16175        }
16176    }
16177
16178    /**
16179     * Cancel any deferred high-level input events that were previously posted to the event queue.
16180     *
16181     * <p>Many views post high-level events such as click handlers to the event queue
16182     * to run deferred in order to preserve a desired user experience - clearing visible
16183     * pressed states before executing, etc. This method will abort any events of this nature
16184     * that are currently in flight.</p>
16185     *
16186     * <p>Custom views that generate their own high-level deferred input events should override
16187     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
16188     *
16189     * <p>This will also cancel pending input events for any child views.</p>
16190     *
16191     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
16192     * This will not impact newer events posted after this call that may occur as a result of
16193     * lower-level input events still waiting in the queue. If you are trying to prevent
16194     * double-submitted  events for the duration of some sort of asynchronous transaction
16195     * you should also take other steps to protect against unexpected double inputs e.g. calling
16196     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
16197     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
16198     */
16199    public final void cancelPendingInputEvents() {
16200        dispatchCancelPendingInputEvents();
16201    }
16202
16203    /**
16204     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
16205     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
16206     */
16207    void dispatchCancelPendingInputEvents() {
16208        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
16209        onCancelPendingInputEvents();
16210        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
16211            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
16212                    " did not call through to super.onCancelPendingInputEvents()");
16213        }
16214    }
16215
16216    /**
16217     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
16218     * a parent view.
16219     *
16220     * <p>This method is responsible for removing any pending high-level input events that were
16221     * posted to the event queue to run later. Custom view classes that post their own deferred
16222     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
16223     * {@link android.os.Handler} should override this method, call
16224     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
16225     * </p>
16226     */
16227    public void onCancelPendingInputEvents() {
16228        removePerformClickCallback();
16229        cancelLongPress();
16230        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
16231    }
16232
16233    /**
16234     * Store this view hierarchy's frozen state into the given container.
16235     *
16236     * @param container The SparseArray in which to save the view's state.
16237     *
16238     * @see #restoreHierarchyState(android.util.SparseArray)
16239     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16240     * @see #onSaveInstanceState()
16241     */
16242    public void saveHierarchyState(SparseArray<Parcelable> container) {
16243        dispatchSaveInstanceState(container);
16244    }
16245
16246    /**
16247     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
16248     * this view and its children. May be overridden to modify how freezing happens to a
16249     * view's children; for example, some views may want to not store state for their children.
16250     *
16251     * @param container The SparseArray in which to save the view's state.
16252     *
16253     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16254     * @see #saveHierarchyState(android.util.SparseArray)
16255     * @see #onSaveInstanceState()
16256     */
16257    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
16258        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
16259            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16260            Parcelable state = onSaveInstanceState();
16261            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16262                throw new IllegalStateException(
16263                        "Derived class did not call super.onSaveInstanceState()");
16264            }
16265            if (state != null) {
16266                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
16267                // + ": " + state);
16268                container.put(mID, state);
16269            }
16270        }
16271    }
16272
16273    /**
16274     * Hook allowing a view to generate a representation of its internal state
16275     * that can later be used to create a new instance with that same state.
16276     * This state should only contain information that is not persistent or can
16277     * not be reconstructed later. For example, you will never store your
16278     * current position on screen because that will be computed again when a
16279     * new instance of the view is placed in its view hierarchy.
16280     * <p>
16281     * Some examples of things you may store here: the current cursor position
16282     * in a text view (but usually not the text itself since that is stored in a
16283     * content provider or other persistent storage), the currently selected
16284     * item in a list view.
16285     *
16286     * @return Returns a Parcelable object containing the view's current dynamic
16287     *         state, or null if there is nothing interesting to save. The
16288     *         default implementation returns null.
16289     * @see #onRestoreInstanceState(android.os.Parcelable)
16290     * @see #saveHierarchyState(android.util.SparseArray)
16291     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16292     * @see #setSaveEnabled(boolean)
16293     */
16294    @CallSuper
16295    protected Parcelable onSaveInstanceState() {
16296        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16297        if (mStartActivityRequestWho != null) {
16298            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
16299            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
16300            return state;
16301        }
16302        return BaseSavedState.EMPTY_STATE;
16303    }
16304
16305    /**
16306     * Restore this view hierarchy's frozen state from the given container.
16307     *
16308     * @param container The SparseArray which holds previously frozen states.
16309     *
16310     * @see #saveHierarchyState(android.util.SparseArray)
16311     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16312     * @see #onRestoreInstanceState(android.os.Parcelable)
16313     */
16314    public void restoreHierarchyState(SparseArray<Parcelable> container) {
16315        dispatchRestoreInstanceState(container);
16316    }
16317
16318    /**
16319     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
16320     * state for this view and its children. May be overridden to modify how restoring
16321     * happens to a view's children; for example, some views may want to not store state
16322     * for their children.
16323     *
16324     * @param container The SparseArray which holds previously saved state.
16325     *
16326     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16327     * @see #restoreHierarchyState(android.util.SparseArray)
16328     * @see #onRestoreInstanceState(android.os.Parcelable)
16329     */
16330    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
16331        if (mID != NO_ID) {
16332            Parcelable state = container.get(mID);
16333            if (state != null) {
16334                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
16335                // + ": " + state);
16336                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16337                onRestoreInstanceState(state);
16338                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16339                    throw new IllegalStateException(
16340                            "Derived class did not call super.onRestoreInstanceState()");
16341                }
16342            }
16343        }
16344    }
16345
16346    /**
16347     * Hook allowing a view to re-apply a representation of its internal state that had previously
16348     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
16349     * null state.
16350     *
16351     * @param state The frozen state that had previously been returned by
16352     *        {@link #onSaveInstanceState}.
16353     *
16354     * @see #onSaveInstanceState()
16355     * @see #restoreHierarchyState(android.util.SparseArray)
16356     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16357     */
16358    @CallSuper
16359    protected void onRestoreInstanceState(Parcelable state) {
16360        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16361        if (state != null && !(state instanceof AbsSavedState)) {
16362            throw new IllegalArgumentException("Wrong state class, expecting View State but "
16363                    + "received " + state.getClass().toString() + " instead. This usually happens "
16364                    + "when two views of different type have the same id in the same hierarchy. "
16365                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
16366                    + "other views do not use the same id.");
16367        }
16368        if (state != null && state instanceof BaseSavedState) {
16369            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
16370        }
16371    }
16372
16373    /**
16374     * <p>Return the time at which the drawing of the view hierarchy started.</p>
16375     *
16376     * @return the drawing start time in milliseconds
16377     */
16378    public long getDrawingTime() {
16379        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
16380    }
16381
16382    /**
16383     * <p>Enables or disables the duplication of the parent's state into this view. When
16384     * duplication is enabled, this view gets its drawable state from its parent rather
16385     * than from its own internal properties.</p>
16386     *
16387     * <p>Note: in the current implementation, setting this property to true after the
16388     * view was added to a ViewGroup might have no effect at all. This property should
16389     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
16390     *
16391     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
16392     * property is enabled, an exception will be thrown.</p>
16393     *
16394     * <p>Note: if the child view uses and updates additional states which are unknown to the
16395     * parent, these states should not be affected by this method.</p>
16396     *
16397     * @param enabled True to enable duplication of the parent's drawable state, false
16398     *                to disable it.
16399     *
16400     * @see #getDrawableState()
16401     * @see #isDuplicateParentStateEnabled()
16402     */
16403    public void setDuplicateParentStateEnabled(boolean enabled) {
16404        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
16405    }
16406
16407    /**
16408     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
16409     *
16410     * @return True if this view's drawable state is duplicated from the parent,
16411     *         false otherwise
16412     *
16413     * @see #getDrawableState()
16414     * @see #setDuplicateParentStateEnabled(boolean)
16415     */
16416    public boolean isDuplicateParentStateEnabled() {
16417        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
16418    }
16419
16420    /**
16421     * <p>Specifies the type of layer backing this view. The layer can be
16422     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16423     * {@link #LAYER_TYPE_HARDWARE}.</p>
16424     *
16425     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16426     * instance that controls how the layer is composed on screen. The following
16427     * properties of the paint are taken into account when composing the layer:</p>
16428     * <ul>
16429     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16430     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16431     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16432     * </ul>
16433     *
16434     * <p>If this view has an alpha value set to < 1.0 by calling
16435     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
16436     * by this view's alpha value.</p>
16437     *
16438     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
16439     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
16440     * for more information on when and how to use layers.</p>
16441     *
16442     * @param layerType The type of layer to use with this view, must be one of
16443     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16444     *        {@link #LAYER_TYPE_HARDWARE}
16445     * @param paint The paint used to compose the layer. This argument is optional
16446     *        and can be null. It is ignored when the layer type is
16447     *        {@link #LAYER_TYPE_NONE}
16448     *
16449     * @see #getLayerType()
16450     * @see #LAYER_TYPE_NONE
16451     * @see #LAYER_TYPE_SOFTWARE
16452     * @see #LAYER_TYPE_HARDWARE
16453     * @see #setAlpha(float)
16454     *
16455     * @attr ref android.R.styleable#View_layerType
16456     */
16457    public void setLayerType(int layerType, @Nullable Paint paint) {
16458        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
16459            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
16460                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
16461        }
16462
16463        boolean typeChanged = mRenderNode.setLayerType(layerType);
16464
16465        if (!typeChanged) {
16466            setLayerPaint(paint);
16467            return;
16468        }
16469
16470        if (layerType != LAYER_TYPE_SOFTWARE) {
16471            // Destroy any previous software drawing cache if present
16472            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
16473            // drawing cache created in View#draw when drawing to a SW canvas.
16474            destroyDrawingCache();
16475        }
16476
16477        mLayerType = layerType;
16478        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
16479        mRenderNode.setLayerPaint(mLayerPaint);
16480
16481        // draw() behaves differently if we are on a layer, so we need to
16482        // invalidate() here
16483        invalidateParentCaches();
16484        invalidate(true);
16485    }
16486
16487    /**
16488     * Updates the {@link Paint} object used with the current layer (used only if the current
16489     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
16490     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
16491     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
16492     * ensure that the view gets redrawn immediately.
16493     *
16494     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16495     * instance that controls how the layer is composed on screen. The following
16496     * properties of the paint are taken into account when composing the layer:</p>
16497     * <ul>
16498     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16499     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16500     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16501     * </ul>
16502     *
16503     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
16504     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
16505     *
16506     * @param paint The paint used to compose the layer. This argument is optional
16507     *        and can be null. It is ignored when the layer type is
16508     *        {@link #LAYER_TYPE_NONE}
16509     *
16510     * @see #setLayerType(int, android.graphics.Paint)
16511     */
16512    public void setLayerPaint(@Nullable Paint paint) {
16513        int layerType = getLayerType();
16514        if (layerType != LAYER_TYPE_NONE) {
16515            mLayerPaint = paint;
16516            if (layerType == LAYER_TYPE_HARDWARE) {
16517                if (mRenderNode.setLayerPaint(paint)) {
16518                    invalidateViewProperty(false, false);
16519                }
16520            } else {
16521                invalidate();
16522            }
16523        }
16524    }
16525
16526    /**
16527     * Indicates what type of layer is currently associated with this view. By default
16528     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
16529     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
16530     * for more information on the different types of layers.
16531     *
16532     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16533     *         {@link #LAYER_TYPE_HARDWARE}
16534     *
16535     * @see #setLayerType(int, android.graphics.Paint)
16536     * @see #buildLayer()
16537     * @see #LAYER_TYPE_NONE
16538     * @see #LAYER_TYPE_SOFTWARE
16539     * @see #LAYER_TYPE_HARDWARE
16540     */
16541    public int getLayerType() {
16542        return mLayerType;
16543    }
16544
16545    /**
16546     * Forces this view's layer to be created and this view to be rendered
16547     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
16548     * invoking this method will have no effect.
16549     *
16550     * This method can for instance be used to render a view into its layer before
16551     * starting an animation. If this view is complex, rendering into the layer
16552     * before starting the animation will avoid skipping frames.
16553     *
16554     * @throws IllegalStateException If this view is not attached to a window
16555     *
16556     * @see #setLayerType(int, android.graphics.Paint)
16557     */
16558    public void buildLayer() {
16559        if (mLayerType == LAYER_TYPE_NONE) return;
16560
16561        final AttachInfo attachInfo = mAttachInfo;
16562        if (attachInfo == null) {
16563            throw new IllegalStateException("This view must be attached to a window first");
16564        }
16565
16566        if (getWidth() == 0 || getHeight() == 0) {
16567            return;
16568        }
16569
16570        switch (mLayerType) {
16571            case LAYER_TYPE_HARDWARE:
16572                updateDisplayListIfDirty();
16573                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
16574                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
16575                }
16576                break;
16577            case LAYER_TYPE_SOFTWARE:
16578                buildDrawingCache(true);
16579                break;
16580        }
16581    }
16582
16583    /**
16584     * Destroys all hardware rendering resources. This method is invoked
16585     * when the system needs to reclaim resources. Upon execution of this
16586     * method, you should free any OpenGL resources created by the view.
16587     *
16588     * Note: you <strong>must</strong> call
16589     * <code>super.destroyHardwareResources()</code> when overriding
16590     * this method.
16591     *
16592     * @hide
16593     */
16594    @CallSuper
16595    protected void destroyHardwareResources() {
16596        if (mOverlay != null) {
16597            mOverlay.getOverlayView().destroyHardwareResources();
16598        }
16599        if (mGhostView != null) {
16600            mGhostView.destroyHardwareResources();
16601        }
16602    }
16603
16604    /**
16605     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16606     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16607     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16608     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16609     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16610     * null.</p>
16611     *
16612     * <p>Enabling the drawing cache is similar to
16613     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16614     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16615     * drawing cache has no effect on rendering because the system uses a different mechanism
16616     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16617     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16618     * for information on how to enable software and hardware layers.</p>
16619     *
16620     * <p>This API can be used to manually generate
16621     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16622     * {@link #getDrawingCache()}.</p>
16623     *
16624     * @param enabled true to enable the drawing cache, false otherwise
16625     *
16626     * @see #isDrawingCacheEnabled()
16627     * @see #getDrawingCache()
16628     * @see #buildDrawingCache()
16629     * @see #setLayerType(int, android.graphics.Paint)
16630     */
16631    public void setDrawingCacheEnabled(boolean enabled) {
16632        mCachingFailed = false;
16633        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16634    }
16635
16636    /**
16637     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16638     *
16639     * @return true if the drawing cache is enabled
16640     *
16641     * @see #setDrawingCacheEnabled(boolean)
16642     * @see #getDrawingCache()
16643     */
16644    @ViewDebug.ExportedProperty(category = "drawing")
16645    public boolean isDrawingCacheEnabled() {
16646        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16647    }
16648
16649    /**
16650     * Debugging utility which recursively outputs the dirty state of a view and its
16651     * descendants.
16652     *
16653     * @hide
16654     */
16655    @SuppressWarnings({"UnusedDeclaration"})
16656    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16657        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16658                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16659                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16660                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16661        if (clear) {
16662            mPrivateFlags &= clearMask;
16663        }
16664        if (this instanceof ViewGroup) {
16665            ViewGroup parent = (ViewGroup) this;
16666            final int count = parent.getChildCount();
16667            for (int i = 0; i < count; i++) {
16668                final View child = parent.getChildAt(i);
16669                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16670            }
16671        }
16672    }
16673
16674    /**
16675     * This method is used by ViewGroup to cause its children to restore or recreate their
16676     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16677     * to recreate its own display list, which would happen if it went through the normal
16678     * draw/dispatchDraw mechanisms.
16679     *
16680     * @hide
16681     */
16682    protected void dispatchGetDisplayList() {}
16683
16684    /**
16685     * A view that is not attached or hardware accelerated cannot create a display list.
16686     * This method checks these conditions and returns the appropriate result.
16687     *
16688     * @return true if view has the ability to create a display list, false otherwise.
16689     *
16690     * @hide
16691     */
16692    public boolean canHaveDisplayList() {
16693        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
16694    }
16695
16696    /**
16697     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
16698     * @hide
16699     */
16700    @NonNull
16701    public RenderNode updateDisplayListIfDirty() {
16702        final RenderNode renderNode = mRenderNode;
16703        if (!canHaveDisplayList()) {
16704            // can't populate RenderNode, don't try
16705            return renderNode;
16706        }
16707
16708        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16709                || !renderNode.isValid()
16710                || (mRecreateDisplayList)) {
16711            // Don't need to recreate the display list, just need to tell our
16712            // children to restore/recreate theirs
16713            if (renderNode.isValid()
16714                    && !mRecreateDisplayList) {
16715                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16716                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16717                dispatchGetDisplayList();
16718
16719                return renderNode; // no work needed
16720            }
16721
16722            // If we got here, we're recreating it. Mark it as such to ensure that
16723            // we copy in child display lists into ours in drawChild()
16724            mRecreateDisplayList = true;
16725
16726            int width = mRight - mLeft;
16727            int height = mBottom - mTop;
16728            int layerType = getLayerType();
16729
16730            final DisplayListCanvas canvas = renderNode.start(width, height);
16731            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16732
16733            try {
16734                if (layerType == LAYER_TYPE_SOFTWARE) {
16735                    buildDrawingCache(true);
16736                    Bitmap cache = getDrawingCache(true);
16737                    if (cache != null) {
16738                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16739                    }
16740                } else {
16741                    computeScroll();
16742
16743                    canvas.translate(-mScrollX, -mScrollY);
16744                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16745                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16746
16747                    // Fast path for layouts with no backgrounds
16748                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16749                        dispatchDraw(canvas);
16750                        if (mOverlay != null && !mOverlay.isEmpty()) {
16751                            mOverlay.getOverlayView().draw(canvas);
16752                        }
16753                        if (debugDraw()) {
16754                            debugDrawFocus(canvas);
16755                        }
16756                    } else {
16757                        draw(canvas);
16758                    }
16759                }
16760            } finally {
16761                renderNode.end(canvas);
16762                setDisplayListProperties(renderNode);
16763            }
16764        } else {
16765            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16766            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16767        }
16768        return renderNode;
16769    }
16770
16771    private void resetDisplayList() {
16772        mRenderNode.discardDisplayList();
16773        if (mBackgroundRenderNode != null) {
16774            mBackgroundRenderNode.discardDisplayList();
16775        }
16776    }
16777
16778    /**
16779     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16780     *
16781     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16782     *
16783     * @see #getDrawingCache(boolean)
16784     */
16785    public Bitmap getDrawingCache() {
16786        return getDrawingCache(false);
16787    }
16788
16789    /**
16790     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16791     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16792     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16793     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16794     * request the drawing cache by calling this method and draw it on screen if the
16795     * returned bitmap is not null.</p>
16796     *
16797     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16798     * this method will create a bitmap of the same size as this view. Because this bitmap
16799     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16800     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16801     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16802     * size than the view. This implies that your application must be able to handle this
16803     * size.</p>
16804     *
16805     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16806     *        the current density of the screen when the application is in compatibility
16807     *        mode.
16808     *
16809     * @return A bitmap representing this view or null if cache is disabled.
16810     *
16811     * @see #setDrawingCacheEnabled(boolean)
16812     * @see #isDrawingCacheEnabled()
16813     * @see #buildDrawingCache(boolean)
16814     * @see #destroyDrawingCache()
16815     */
16816    public Bitmap getDrawingCache(boolean autoScale) {
16817        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16818            return null;
16819        }
16820        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16821            buildDrawingCache(autoScale);
16822        }
16823        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16824    }
16825
16826    /**
16827     * <p>Frees the resources used by the drawing cache. If you call
16828     * {@link #buildDrawingCache()} manually without calling
16829     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16830     * should cleanup the cache with this method afterwards.</p>
16831     *
16832     * @see #setDrawingCacheEnabled(boolean)
16833     * @see #buildDrawingCache()
16834     * @see #getDrawingCache()
16835     */
16836    public void destroyDrawingCache() {
16837        if (mDrawingCache != null) {
16838            mDrawingCache.recycle();
16839            mDrawingCache = null;
16840        }
16841        if (mUnscaledDrawingCache != null) {
16842            mUnscaledDrawingCache.recycle();
16843            mUnscaledDrawingCache = null;
16844        }
16845    }
16846
16847    /**
16848     * Setting a solid background color for the drawing cache's bitmaps will improve
16849     * performance and memory usage. Note, though that this should only be used if this
16850     * view will always be drawn on top of a solid color.
16851     *
16852     * @param color The background color to use for the drawing cache's bitmap
16853     *
16854     * @see #setDrawingCacheEnabled(boolean)
16855     * @see #buildDrawingCache()
16856     * @see #getDrawingCache()
16857     */
16858    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16859        if (color != mDrawingCacheBackgroundColor) {
16860            mDrawingCacheBackgroundColor = color;
16861            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16862        }
16863    }
16864
16865    /**
16866     * @see #setDrawingCacheBackgroundColor(int)
16867     *
16868     * @return The background color to used for the drawing cache's bitmap
16869     */
16870    @ColorInt
16871    public int getDrawingCacheBackgroundColor() {
16872        return mDrawingCacheBackgroundColor;
16873    }
16874
16875    /**
16876     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16877     *
16878     * @see #buildDrawingCache(boolean)
16879     */
16880    public void buildDrawingCache() {
16881        buildDrawingCache(false);
16882    }
16883
16884    /**
16885     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16886     *
16887     * <p>If you call {@link #buildDrawingCache()} manually without calling
16888     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16889     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16890     *
16891     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16892     * this method will create a bitmap of the same size as this view. Because this bitmap
16893     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16894     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16895     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16896     * size than the view. This implies that your application must be able to handle this
16897     * size.</p>
16898     *
16899     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16900     * you do not need the drawing cache bitmap, calling this method will increase memory
16901     * usage and cause the view to be rendered in software once, thus negatively impacting
16902     * performance.</p>
16903     *
16904     * @see #getDrawingCache()
16905     * @see #destroyDrawingCache()
16906     */
16907    public void buildDrawingCache(boolean autoScale) {
16908        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16909                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16910            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16911                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16912                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16913            }
16914            try {
16915                buildDrawingCacheImpl(autoScale);
16916            } finally {
16917                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16918            }
16919        }
16920    }
16921
16922    /**
16923     * private, internal implementation of buildDrawingCache, used to enable tracing
16924     */
16925    private void buildDrawingCacheImpl(boolean autoScale) {
16926        mCachingFailed = false;
16927
16928        int width = mRight - mLeft;
16929        int height = mBottom - mTop;
16930
16931        final AttachInfo attachInfo = mAttachInfo;
16932        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16933
16934        if (autoScale && scalingRequired) {
16935            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16936            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16937        }
16938
16939        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16940        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16941        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16942
16943        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16944        final long drawingCacheSize =
16945                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16946        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16947            if (width > 0 && height > 0) {
16948                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16949                        + " too large to fit into a software layer (or drawing cache), needs "
16950                        + projectedBitmapSize + " bytes, only "
16951                        + drawingCacheSize + " available");
16952            }
16953            destroyDrawingCache();
16954            mCachingFailed = true;
16955            return;
16956        }
16957
16958        boolean clear = true;
16959        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16960
16961        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16962            Bitmap.Config quality;
16963            if (!opaque) {
16964                // Never pick ARGB_4444 because it looks awful
16965                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16966                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16967                    case DRAWING_CACHE_QUALITY_AUTO:
16968                    case DRAWING_CACHE_QUALITY_LOW:
16969                    case DRAWING_CACHE_QUALITY_HIGH:
16970                    default:
16971                        quality = Bitmap.Config.ARGB_8888;
16972                        break;
16973                }
16974            } else {
16975                // Optimization for translucent windows
16976                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16977                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16978            }
16979
16980            // Try to cleanup memory
16981            if (bitmap != null) bitmap.recycle();
16982
16983            try {
16984                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16985                        width, height, quality);
16986                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16987                if (autoScale) {
16988                    mDrawingCache = bitmap;
16989                } else {
16990                    mUnscaledDrawingCache = bitmap;
16991                }
16992                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16993            } catch (OutOfMemoryError e) {
16994                // If there is not enough memory to create the bitmap cache, just
16995                // ignore the issue as bitmap caches are not required to draw the
16996                // view hierarchy
16997                if (autoScale) {
16998                    mDrawingCache = null;
16999                } else {
17000                    mUnscaledDrawingCache = null;
17001                }
17002                mCachingFailed = true;
17003                return;
17004            }
17005
17006            clear = drawingCacheBackgroundColor != 0;
17007        }
17008
17009        Canvas canvas;
17010        if (attachInfo != null) {
17011            canvas = attachInfo.mCanvas;
17012            if (canvas == null) {
17013                canvas = new Canvas();
17014            }
17015            canvas.setBitmap(bitmap);
17016            // Temporarily clobber the cached Canvas in case one of our children
17017            // is also using a drawing cache. Without this, the children would
17018            // steal the canvas by attaching their own bitmap to it and bad, bad
17019            // thing would happen (invisible views, corrupted drawings, etc.)
17020            attachInfo.mCanvas = null;
17021        } else {
17022            // This case should hopefully never or seldom happen
17023            canvas = new Canvas(bitmap);
17024        }
17025
17026        if (clear) {
17027            bitmap.eraseColor(drawingCacheBackgroundColor);
17028        }
17029
17030        computeScroll();
17031        final int restoreCount = canvas.save();
17032
17033        if (autoScale && scalingRequired) {
17034            final float scale = attachInfo.mApplicationScale;
17035            canvas.scale(scale, scale);
17036        }
17037
17038        canvas.translate(-mScrollX, -mScrollY);
17039
17040        mPrivateFlags |= PFLAG_DRAWN;
17041        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
17042                mLayerType != LAYER_TYPE_NONE) {
17043            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
17044        }
17045
17046        // Fast path for layouts with no backgrounds
17047        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17048            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17049            dispatchDraw(canvas);
17050            if (mOverlay != null && !mOverlay.isEmpty()) {
17051                mOverlay.getOverlayView().draw(canvas);
17052            }
17053        } else {
17054            draw(canvas);
17055        }
17056
17057        canvas.restoreToCount(restoreCount);
17058        canvas.setBitmap(null);
17059
17060        if (attachInfo != null) {
17061            // Restore the cached Canvas for our siblings
17062            attachInfo.mCanvas = canvas;
17063        }
17064    }
17065
17066    /**
17067     * Create a snapshot of the view into a bitmap.  We should probably make
17068     * some form of this public, but should think about the API.
17069     *
17070     * @hide
17071     */
17072    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
17073        int width = mRight - mLeft;
17074        int height = mBottom - mTop;
17075
17076        final AttachInfo attachInfo = mAttachInfo;
17077        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
17078        width = (int) ((width * scale) + 0.5f);
17079        height = (int) ((height * scale) + 0.5f);
17080
17081        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17082                width > 0 ? width : 1, height > 0 ? height : 1, quality);
17083        if (bitmap == null) {
17084            throw new OutOfMemoryError();
17085        }
17086
17087        Resources resources = getResources();
17088        if (resources != null) {
17089            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
17090        }
17091
17092        Canvas canvas;
17093        if (attachInfo != null) {
17094            canvas = attachInfo.mCanvas;
17095            if (canvas == null) {
17096                canvas = new Canvas();
17097            }
17098            canvas.setBitmap(bitmap);
17099            // Temporarily clobber the cached Canvas in case one of our children
17100            // is also using a drawing cache. Without this, the children would
17101            // steal the canvas by attaching their own bitmap to it and bad, bad
17102            // things would happen (invisible views, corrupted drawings, etc.)
17103            attachInfo.mCanvas = null;
17104        } else {
17105            // This case should hopefully never or seldom happen
17106            canvas = new Canvas(bitmap);
17107        }
17108
17109        if ((backgroundColor & 0xff000000) != 0) {
17110            bitmap.eraseColor(backgroundColor);
17111        }
17112
17113        computeScroll();
17114        final int restoreCount = canvas.save();
17115        canvas.scale(scale, scale);
17116        canvas.translate(-mScrollX, -mScrollY);
17117
17118        // Temporarily remove the dirty mask
17119        int flags = mPrivateFlags;
17120        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17121
17122        // Fast path for layouts with no backgrounds
17123        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17124            dispatchDraw(canvas);
17125            if (mOverlay != null && !mOverlay.isEmpty()) {
17126                mOverlay.getOverlayView().draw(canvas);
17127            }
17128        } else {
17129            draw(canvas);
17130        }
17131
17132        mPrivateFlags = flags;
17133
17134        canvas.restoreToCount(restoreCount);
17135        canvas.setBitmap(null);
17136
17137        if (attachInfo != null) {
17138            // Restore the cached Canvas for our siblings
17139            attachInfo.mCanvas = canvas;
17140        }
17141
17142        return bitmap;
17143    }
17144
17145    /**
17146     * Indicates whether this View is currently in edit mode. A View is usually
17147     * in edit mode when displayed within a developer tool. For instance, if
17148     * this View is being drawn by a visual user interface builder, this method
17149     * should return true.
17150     *
17151     * Subclasses should check the return value of this method to provide
17152     * different behaviors if their normal behavior might interfere with the
17153     * host environment. For instance: the class spawns a thread in its
17154     * constructor, the drawing code relies on device-specific features, etc.
17155     *
17156     * This method is usually checked in the drawing code of custom widgets.
17157     *
17158     * @return True if this View is in edit mode, false otherwise.
17159     */
17160    public boolean isInEditMode() {
17161        return false;
17162    }
17163
17164    /**
17165     * If the View draws content inside its padding and enables fading edges,
17166     * it needs to support padding offsets. Padding offsets are added to the
17167     * fading edges to extend the length of the fade so that it covers pixels
17168     * drawn inside the padding.
17169     *
17170     * Subclasses of this class should override this method if they need
17171     * to draw content inside the padding.
17172     *
17173     * @return True if padding offset must be applied, false otherwise.
17174     *
17175     * @see #getLeftPaddingOffset()
17176     * @see #getRightPaddingOffset()
17177     * @see #getTopPaddingOffset()
17178     * @see #getBottomPaddingOffset()
17179     *
17180     * @since CURRENT
17181     */
17182    protected boolean isPaddingOffsetRequired() {
17183        return false;
17184    }
17185
17186    /**
17187     * Amount by which to extend the left fading region. Called only when
17188     * {@link #isPaddingOffsetRequired()} returns true.
17189     *
17190     * @return The left padding offset in pixels.
17191     *
17192     * @see #isPaddingOffsetRequired()
17193     *
17194     * @since CURRENT
17195     */
17196    protected int getLeftPaddingOffset() {
17197        return 0;
17198    }
17199
17200    /**
17201     * Amount by which to extend the right fading region. Called only when
17202     * {@link #isPaddingOffsetRequired()} returns true.
17203     *
17204     * @return The right padding offset in pixels.
17205     *
17206     * @see #isPaddingOffsetRequired()
17207     *
17208     * @since CURRENT
17209     */
17210    protected int getRightPaddingOffset() {
17211        return 0;
17212    }
17213
17214    /**
17215     * Amount by which to extend the top fading region. Called only when
17216     * {@link #isPaddingOffsetRequired()} returns true.
17217     *
17218     * @return The top padding offset in pixels.
17219     *
17220     * @see #isPaddingOffsetRequired()
17221     *
17222     * @since CURRENT
17223     */
17224    protected int getTopPaddingOffset() {
17225        return 0;
17226    }
17227
17228    /**
17229     * Amount by which to extend the bottom fading region. Called only when
17230     * {@link #isPaddingOffsetRequired()} returns true.
17231     *
17232     * @return The bottom padding offset in pixels.
17233     *
17234     * @see #isPaddingOffsetRequired()
17235     *
17236     * @since CURRENT
17237     */
17238    protected int getBottomPaddingOffset() {
17239        return 0;
17240    }
17241
17242    /**
17243     * @hide
17244     * @param offsetRequired
17245     */
17246    protected int getFadeTop(boolean offsetRequired) {
17247        int top = mPaddingTop;
17248        if (offsetRequired) top += getTopPaddingOffset();
17249        return top;
17250    }
17251
17252    /**
17253     * @hide
17254     * @param offsetRequired
17255     */
17256    protected int getFadeHeight(boolean offsetRequired) {
17257        int padding = mPaddingTop;
17258        if (offsetRequired) padding += getTopPaddingOffset();
17259        return mBottom - mTop - mPaddingBottom - padding;
17260    }
17261
17262    /**
17263     * <p>Indicates whether this view is attached to a hardware accelerated
17264     * window or not.</p>
17265     *
17266     * <p>Even if this method returns true, it does not mean that every call
17267     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
17268     * accelerated {@link android.graphics.Canvas}. For instance, if this view
17269     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
17270     * window is hardware accelerated,
17271     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
17272     * return false, and this method will return true.</p>
17273     *
17274     * @return True if the view is attached to a window and the window is
17275     *         hardware accelerated; false in any other case.
17276     */
17277    @ViewDebug.ExportedProperty(category = "drawing")
17278    public boolean isHardwareAccelerated() {
17279        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
17280    }
17281
17282    /**
17283     * Sets a rectangular area on this view to which the view will be clipped
17284     * when it is drawn. Setting the value to null will remove the clip bounds
17285     * and the view will draw normally, using its full bounds.
17286     *
17287     * @param clipBounds The rectangular area, in the local coordinates of
17288     * this view, to which future drawing operations will be clipped.
17289     */
17290    public void setClipBounds(Rect clipBounds) {
17291        if (clipBounds == mClipBounds
17292                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
17293            return;
17294        }
17295        if (clipBounds != null) {
17296            if (mClipBounds == null) {
17297                mClipBounds = new Rect(clipBounds);
17298            } else {
17299                mClipBounds.set(clipBounds);
17300            }
17301        } else {
17302            mClipBounds = null;
17303        }
17304        mRenderNode.setClipBounds(mClipBounds);
17305        invalidateViewProperty(false, false);
17306    }
17307
17308    /**
17309     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
17310     *
17311     * @return A copy of the current clip bounds if clip bounds are set,
17312     * otherwise null.
17313     */
17314    public Rect getClipBounds() {
17315        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
17316    }
17317
17318
17319    /**
17320     * Populates an output rectangle with the clip bounds of the view,
17321     * returning {@code true} if successful or {@code false} if the view's
17322     * clip bounds are {@code null}.
17323     *
17324     * @param outRect rectangle in which to place the clip bounds of the view
17325     * @return {@code true} if successful or {@code false} if the view's
17326     *         clip bounds are {@code null}
17327     */
17328    public boolean getClipBounds(Rect outRect) {
17329        if (mClipBounds != null) {
17330            outRect.set(mClipBounds);
17331            return true;
17332        }
17333        return false;
17334    }
17335
17336    /**
17337     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
17338     * case of an active Animation being run on the view.
17339     */
17340    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
17341            Animation a, boolean scalingRequired) {
17342        Transformation invalidationTransform;
17343        final int flags = parent.mGroupFlags;
17344        final boolean initialized = a.isInitialized();
17345        if (!initialized) {
17346            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
17347            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
17348            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
17349            onAnimationStart();
17350        }
17351
17352        final Transformation t = parent.getChildTransformation();
17353        boolean more = a.getTransformation(drawingTime, t, 1f);
17354        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
17355            if (parent.mInvalidationTransformation == null) {
17356                parent.mInvalidationTransformation = new Transformation();
17357            }
17358            invalidationTransform = parent.mInvalidationTransformation;
17359            a.getTransformation(drawingTime, invalidationTransform, 1f);
17360        } else {
17361            invalidationTransform = t;
17362        }
17363
17364        if (more) {
17365            if (!a.willChangeBounds()) {
17366                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
17367                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
17368                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
17369                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
17370                    // The child need to draw an animation, potentially offscreen, so
17371                    // make sure we do not cancel invalidate requests
17372                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17373                    parent.invalidate(mLeft, mTop, mRight, mBottom);
17374                }
17375            } else {
17376                if (parent.mInvalidateRegion == null) {
17377                    parent.mInvalidateRegion = new RectF();
17378                }
17379                final RectF region = parent.mInvalidateRegion;
17380                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
17381                        invalidationTransform);
17382
17383                // The child need to draw an animation, potentially offscreen, so
17384                // make sure we do not cancel invalidate requests
17385                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17386
17387                final int left = mLeft + (int) region.left;
17388                final int top = mTop + (int) region.top;
17389                parent.invalidate(left, top, left + (int) (region.width() + .5f),
17390                        top + (int) (region.height() + .5f));
17391            }
17392        }
17393        return more;
17394    }
17395
17396    /**
17397     * This method is called by getDisplayList() when a display list is recorded for a View.
17398     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
17399     */
17400    void setDisplayListProperties(RenderNode renderNode) {
17401        if (renderNode != null) {
17402            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
17403            renderNode.setClipToBounds(mParent instanceof ViewGroup
17404                    && ((ViewGroup) mParent).getClipChildren());
17405
17406            float alpha = 1;
17407            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
17408                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17409                ViewGroup parentVG = (ViewGroup) mParent;
17410                final Transformation t = parentVG.getChildTransformation();
17411                if (parentVG.getChildStaticTransformation(this, t)) {
17412                    final int transformType = t.getTransformationType();
17413                    if (transformType != Transformation.TYPE_IDENTITY) {
17414                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
17415                            alpha = t.getAlpha();
17416                        }
17417                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
17418                            renderNode.setStaticMatrix(t.getMatrix());
17419                        }
17420                    }
17421                }
17422            }
17423            if (mTransformationInfo != null) {
17424                alpha *= getFinalAlpha();
17425                if (alpha < 1) {
17426                    final int multipliedAlpha = (int) (255 * alpha);
17427                    if (onSetAlpha(multipliedAlpha)) {
17428                        alpha = 1;
17429                    }
17430                }
17431                renderNode.setAlpha(alpha);
17432            } else if (alpha < 1) {
17433                renderNode.setAlpha(alpha);
17434            }
17435        }
17436    }
17437
17438    /**
17439     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
17440     *
17441     * This is where the View specializes rendering behavior based on layer type,
17442     * and hardware acceleration.
17443     */
17444    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
17445        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
17446        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
17447         *
17448         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
17449         * HW accelerated, it can't handle drawing RenderNodes.
17450         */
17451        boolean drawingWithRenderNode = mAttachInfo != null
17452                && mAttachInfo.mHardwareAccelerated
17453                && hardwareAcceleratedCanvas;
17454
17455        boolean more = false;
17456        final boolean childHasIdentityMatrix = hasIdentityMatrix();
17457        final int parentFlags = parent.mGroupFlags;
17458
17459        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
17460            parent.getChildTransformation().clear();
17461            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17462        }
17463
17464        Transformation transformToApply = null;
17465        boolean concatMatrix = false;
17466        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
17467        final Animation a = getAnimation();
17468        if (a != null) {
17469            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
17470            concatMatrix = a.willChangeTransformationMatrix();
17471            if (concatMatrix) {
17472                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17473            }
17474            transformToApply = parent.getChildTransformation();
17475        } else {
17476            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
17477                // No longer animating: clear out old animation matrix
17478                mRenderNode.setAnimationMatrix(null);
17479                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17480            }
17481            if (!drawingWithRenderNode
17482                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17483                final Transformation t = parent.getChildTransformation();
17484                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
17485                if (hasTransform) {
17486                    final int transformType = t.getTransformationType();
17487                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
17488                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
17489                }
17490            }
17491        }
17492
17493        concatMatrix |= !childHasIdentityMatrix;
17494
17495        // Sets the flag as early as possible to allow draw() implementations
17496        // to call invalidate() successfully when doing animations
17497        mPrivateFlags |= PFLAG_DRAWN;
17498
17499        if (!concatMatrix &&
17500                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
17501                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
17502                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
17503                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
17504            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
17505            return more;
17506        }
17507        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
17508
17509        if (hardwareAcceleratedCanvas) {
17510            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
17511            // retain the flag's value temporarily in the mRecreateDisplayList flag
17512            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
17513            mPrivateFlags &= ~PFLAG_INVALIDATED;
17514        }
17515
17516        RenderNode renderNode = null;
17517        Bitmap cache = null;
17518        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
17519        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
17520             if (layerType != LAYER_TYPE_NONE) {
17521                 // If not drawing with RenderNode, treat HW layers as SW
17522                 layerType = LAYER_TYPE_SOFTWARE;
17523                 buildDrawingCache(true);
17524            }
17525            cache = getDrawingCache(true);
17526        }
17527
17528        if (drawingWithRenderNode) {
17529            // Delay getting the display list until animation-driven alpha values are
17530            // set up and possibly passed on to the view
17531            renderNode = updateDisplayListIfDirty();
17532            if (!renderNode.isValid()) {
17533                // Uncommon, but possible. If a view is removed from the hierarchy during the call
17534                // to getDisplayList(), the display list will be marked invalid and we should not
17535                // try to use it again.
17536                renderNode = null;
17537                drawingWithRenderNode = false;
17538            }
17539        }
17540
17541        int sx = 0;
17542        int sy = 0;
17543        if (!drawingWithRenderNode) {
17544            computeScroll();
17545            sx = mScrollX;
17546            sy = mScrollY;
17547        }
17548
17549        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
17550        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
17551
17552        int restoreTo = -1;
17553        if (!drawingWithRenderNode || transformToApply != null) {
17554            restoreTo = canvas.save();
17555        }
17556        if (offsetForScroll) {
17557            canvas.translate(mLeft - sx, mTop - sy);
17558        } else {
17559            if (!drawingWithRenderNode) {
17560                canvas.translate(mLeft, mTop);
17561            }
17562            if (scalingRequired) {
17563                if (drawingWithRenderNode) {
17564                    // TODO: Might not need this if we put everything inside the DL
17565                    restoreTo = canvas.save();
17566                }
17567                // mAttachInfo cannot be null, otherwise scalingRequired == false
17568                final float scale = 1.0f / mAttachInfo.mApplicationScale;
17569                canvas.scale(scale, scale);
17570            }
17571        }
17572
17573        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
17574        if (transformToApply != null
17575                || alpha < 1
17576                || !hasIdentityMatrix()
17577                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17578            if (transformToApply != null || !childHasIdentityMatrix) {
17579                int transX = 0;
17580                int transY = 0;
17581
17582                if (offsetForScroll) {
17583                    transX = -sx;
17584                    transY = -sy;
17585                }
17586
17587                if (transformToApply != null) {
17588                    if (concatMatrix) {
17589                        if (drawingWithRenderNode) {
17590                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17591                        } else {
17592                            // Undo the scroll translation, apply the transformation matrix,
17593                            // then redo the scroll translate to get the correct result.
17594                            canvas.translate(-transX, -transY);
17595                            canvas.concat(transformToApply.getMatrix());
17596                            canvas.translate(transX, transY);
17597                        }
17598                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17599                    }
17600
17601                    float transformAlpha = transformToApply.getAlpha();
17602                    if (transformAlpha < 1) {
17603                        alpha *= transformAlpha;
17604                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17605                    }
17606                }
17607
17608                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17609                    canvas.translate(-transX, -transY);
17610                    canvas.concat(getMatrix());
17611                    canvas.translate(transX, transY);
17612                }
17613            }
17614
17615            // Deal with alpha if it is or used to be <1
17616            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17617                if (alpha < 1) {
17618                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17619                } else {
17620                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17621                }
17622                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17623                if (!drawingWithDrawingCache) {
17624                    final int multipliedAlpha = (int) (255 * alpha);
17625                    if (!onSetAlpha(multipliedAlpha)) {
17626                        if (drawingWithRenderNode) {
17627                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17628                        } else if (layerType == LAYER_TYPE_NONE) {
17629                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17630                                    multipliedAlpha);
17631                        }
17632                    } else {
17633                        // Alpha is handled by the child directly, clobber the layer's alpha
17634                        mPrivateFlags |= PFLAG_ALPHA_SET;
17635                    }
17636                }
17637            }
17638        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17639            onSetAlpha(255);
17640            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17641        }
17642
17643        if (!drawingWithRenderNode) {
17644            // apply clips directly, since RenderNode won't do it for this draw
17645            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17646                if (offsetForScroll) {
17647                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17648                } else {
17649                    if (!scalingRequired || cache == null) {
17650                        canvas.clipRect(0, 0, getWidth(), getHeight());
17651                    } else {
17652                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17653                    }
17654                }
17655            }
17656
17657            if (mClipBounds != null) {
17658                // clip bounds ignore scroll
17659                canvas.clipRect(mClipBounds);
17660            }
17661        }
17662
17663        if (!drawingWithDrawingCache) {
17664            if (drawingWithRenderNode) {
17665                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17666                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17667            } else {
17668                // Fast path for layouts with no backgrounds
17669                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17670                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17671                    dispatchDraw(canvas);
17672                } else {
17673                    draw(canvas);
17674                }
17675            }
17676        } else if (cache != null) {
17677            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17678            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17679                // no layer paint, use temporary paint to draw bitmap
17680                Paint cachePaint = parent.mCachePaint;
17681                if (cachePaint == null) {
17682                    cachePaint = new Paint();
17683                    cachePaint.setDither(false);
17684                    parent.mCachePaint = cachePaint;
17685                }
17686                cachePaint.setAlpha((int) (alpha * 255));
17687                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17688            } else {
17689                // use layer paint to draw the bitmap, merging the two alphas, but also restore
17690                int layerPaintAlpha = mLayerPaint.getAlpha();
17691                if (alpha < 1) {
17692                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
17693                }
17694                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17695                if (alpha < 1) {
17696                    mLayerPaint.setAlpha(layerPaintAlpha);
17697                }
17698            }
17699        }
17700
17701        if (restoreTo >= 0) {
17702            canvas.restoreToCount(restoreTo);
17703        }
17704
17705        if (a != null && !more) {
17706            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17707                onSetAlpha(255);
17708            }
17709            parent.finishAnimatingView(this, a);
17710        }
17711
17712        if (more && hardwareAcceleratedCanvas) {
17713            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17714                // alpha animations should cause the child to recreate its display list
17715                invalidate(true);
17716            }
17717        }
17718
17719        mRecreateDisplayList = false;
17720
17721        return more;
17722    }
17723
17724    static Paint getDebugPaint() {
17725        if (sDebugPaint == null) {
17726            sDebugPaint = new Paint();
17727            sDebugPaint.setAntiAlias(false);
17728        }
17729        return sDebugPaint;
17730    }
17731
17732    final int dipsToPixels(int dips) {
17733        float scale = getContext().getResources().getDisplayMetrics().density;
17734        return (int) (dips * scale + 0.5f);
17735    }
17736
17737    final private void debugDrawFocus(Canvas canvas) {
17738        if (isFocused()) {
17739            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
17740            final int l = mScrollX;
17741            final int r = l + mRight - mLeft;
17742            final int t = mScrollY;
17743            final int b = t + mBottom - mTop;
17744
17745            final Paint paint = getDebugPaint();
17746            paint.setColor(DEBUG_CORNERS_COLOR);
17747
17748            // Draw squares in corners.
17749            paint.setStyle(Paint.Style.FILL);
17750            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
17751            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
17752            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
17753            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
17754
17755            // Draw big X across the view.
17756            paint.setStyle(Paint.Style.STROKE);
17757            canvas.drawLine(l, t, r, b, paint);
17758            canvas.drawLine(l, b, r, t, paint);
17759        }
17760    }
17761
17762    /**
17763     * Manually render this view (and all of its children) to the given Canvas.
17764     * The view must have already done a full layout before this function is
17765     * called.  When implementing a view, implement
17766     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17767     * If you do need to override this method, call the superclass version.
17768     *
17769     * @param canvas The Canvas to which the View is rendered.
17770     */
17771    @CallSuper
17772    public void draw(Canvas canvas) {
17773        final int privateFlags = mPrivateFlags;
17774        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17775                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17776        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17777
17778        /*
17779         * Draw traversal performs several drawing steps which must be executed
17780         * in the appropriate order:
17781         *
17782         *      1. Draw the background
17783         *      2. If necessary, save the canvas' layers to prepare for fading
17784         *      3. Draw view's content
17785         *      4. Draw children
17786         *      5. If necessary, draw the fading edges and restore layers
17787         *      6. Draw decorations (scrollbars for instance)
17788         */
17789
17790        // Step 1, draw the background, if needed
17791        int saveCount;
17792
17793        if (!dirtyOpaque) {
17794            drawBackground(canvas);
17795        }
17796
17797        // skip step 2 & 5 if possible (common case)
17798        final int viewFlags = mViewFlags;
17799        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17800        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17801        if (!verticalEdges && !horizontalEdges) {
17802            // Step 3, draw the content
17803            if (!dirtyOpaque) onDraw(canvas);
17804
17805            // Step 4, draw the children
17806            dispatchDraw(canvas);
17807
17808            // Overlay is part of the content and draws beneath Foreground
17809            if (mOverlay != null && !mOverlay.isEmpty()) {
17810                mOverlay.getOverlayView().dispatchDraw(canvas);
17811            }
17812
17813            // Step 6, draw decorations (foreground, scrollbars)
17814            onDrawForeground(canvas);
17815
17816            if (debugDraw()) {
17817                debugDrawFocus(canvas);
17818            }
17819
17820            // we're done...
17821            return;
17822        }
17823
17824        /*
17825         * Here we do the full fledged routine...
17826         * (this is an uncommon case where speed matters less,
17827         * this is why we repeat some of the tests that have been
17828         * done above)
17829         */
17830
17831        boolean drawTop = false;
17832        boolean drawBottom = false;
17833        boolean drawLeft = false;
17834        boolean drawRight = false;
17835
17836        float topFadeStrength = 0.0f;
17837        float bottomFadeStrength = 0.0f;
17838        float leftFadeStrength = 0.0f;
17839        float rightFadeStrength = 0.0f;
17840
17841        // Step 2, save the canvas' layers
17842        int paddingLeft = mPaddingLeft;
17843
17844        final boolean offsetRequired = isPaddingOffsetRequired();
17845        if (offsetRequired) {
17846            paddingLeft += getLeftPaddingOffset();
17847        }
17848
17849        int left = mScrollX + paddingLeft;
17850        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17851        int top = mScrollY + getFadeTop(offsetRequired);
17852        int bottom = top + getFadeHeight(offsetRequired);
17853
17854        if (offsetRequired) {
17855            right += getRightPaddingOffset();
17856            bottom += getBottomPaddingOffset();
17857        }
17858
17859        final ScrollabilityCache scrollabilityCache = mScrollCache;
17860        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17861        int length = (int) fadeHeight;
17862
17863        // clip the fade length if top and bottom fades overlap
17864        // overlapping fades produce odd-looking artifacts
17865        if (verticalEdges && (top + length > bottom - length)) {
17866            length = (bottom - top) / 2;
17867        }
17868
17869        // also clip horizontal fades if necessary
17870        if (horizontalEdges && (left + length > right - length)) {
17871            length = (right - left) / 2;
17872        }
17873
17874        if (verticalEdges) {
17875            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17876            drawTop = topFadeStrength * fadeHeight > 1.0f;
17877            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17878            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17879        }
17880
17881        if (horizontalEdges) {
17882            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17883            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17884            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17885            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17886        }
17887
17888        saveCount = canvas.getSaveCount();
17889
17890        int solidColor = getSolidColor();
17891        if (solidColor == 0) {
17892            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17893
17894            if (drawTop) {
17895                canvas.saveLayer(left, top, right, top + length, null, flags);
17896            }
17897
17898            if (drawBottom) {
17899                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17900            }
17901
17902            if (drawLeft) {
17903                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17904            }
17905
17906            if (drawRight) {
17907                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17908            }
17909        } else {
17910            scrollabilityCache.setFadeColor(solidColor);
17911        }
17912
17913        // Step 3, draw the content
17914        if (!dirtyOpaque) onDraw(canvas);
17915
17916        // Step 4, draw the children
17917        dispatchDraw(canvas);
17918
17919        // Step 5, draw the fade effect and restore layers
17920        final Paint p = scrollabilityCache.paint;
17921        final Matrix matrix = scrollabilityCache.matrix;
17922        final Shader fade = scrollabilityCache.shader;
17923
17924        if (drawTop) {
17925            matrix.setScale(1, fadeHeight * topFadeStrength);
17926            matrix.postTranslate(left, top);
17927            fade.setLocalMatrix(matrix);
17928            p.setShader(fade);
17929            canvas.drawRect(left, top, right, top + length, p);
17930        }
17931
17932        if (drawBottom) {
17933            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17934            matrix.postRotate(180);
17935            matrix.postTranslate(left, bottom);
17936            fade.setLocalMatrix(matrix);
17937            p.setShader(fade);
17938            canvas.drawRect(left, bottom - length, right, bottom, p);
17939        }
17940
17941        if (drawLeft) {
17942            matrix.setScale(1, fadeHeight * leftFadeStrength);
17943            matrix.postRotate(-90);
17944            matrix.postTranslate(left, top);
17945            fade.setLocalMatrix(matrix);
17946            p.setShader(fade);
17947            canvas.drawRect(left, top, left + length, bottom, p);
17948        }
17949
17950        if (drawRight) {
17951            matrix.setScale(1, fadeHeight * rightFadeStrength);
17952            matrix.postRotate(90);
17953            matrix.postTranslate(right, top);
17954            fade.setLocalMatrix(matrix);
17955            p.setShader(fade);
17956            canvas.drawRect(right - length, top, right, bottom, p);
17957        }
17958
17959        canvas.restoreToCount(saveCount);
17960
17961        // Overlay is part of the content and draws beneath Foreground
17962        if (mOverlay != null && !mOverlay.isEmpty()) {
17963            mOverlay.getOverlayView().dispatchDraw(canvas);
17964        }
17965
17966        // Step 6, draw decorations (foreground, scrollbars)
17967        onDrawForeground(canvas);
17968
17969        if (debugDraw()) {
17970            debugDrawFocus(canvas);
17971        }
17972    }
17973
17974    /**
17975     * Draws the background onto the specified canvas.
17976     *
17977     * @param canvas Canvas on which to draw the background
17978     */
17979    private void drawBackground(Canvas canvas) {
17980        final Drawable background = mBackground;
17981        if (background == null) {
17982            return;
17983        }
17984
17985        setBackgroundBounds();
17986
17987        // Attempt to use a display list if requested.
17988        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17989                && mAttachInfo.mThreadedRenderer != null) {
17990            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17991
17992            final RenderNode renderNode = mBackgroundRenderNode;
17993            if (renderNode != null && renderNode.isValid()) {
17994                setBackgroundRenderNodeProperties(renderNode);
17995                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17996                return;
17997            }
17998        }
17999
18000        final int scrollX = mScrollX;
18001        final int scrollY = mScrollY;
18002        if ((scrollX | scrollY) == 0) {
18003            background.draw(canvas);
18004        } else {
18005            canvas.translate(scrollX, scrollY);
18006            background.draw(canvas);
18007            canvas.translate(-scrollX, -scrollY);
18008        }
18009    }
18010
18011    /**
18012     * Sets the correct background bounds and rebuilds the outline, if needed.
18013     * <p/>
18014     * This is called by LayoutLib.
18015     */
18016    void setBackgroundBounds() {
18017        if (mBackgroundSizeChanged && mBackground != null) {
18018            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
18019            mBackgroundSizeChanged = false;
18020            rebuildOutline();
18021        }
18022    }
18023
18024    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
18025        renderNode.setTranslationX(mScrollX);
18026        renderNode.setTranslationY(mScrollY);
18027    }
18028
18029    /**
18030     * Creates a new display list or updates the existing display list for the
18031     * specified Drawable.
18032     *
18033     * @param drawable Drawable for which to create a display list
18034     * @param renderNode Existing RenderNode, or {@code null}
18035     * @return A valid display list for the specified drawable
18036     */
18037    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
18038        if (renderNode == null) {
18039            renderNode = RenderNode.create(drawable.getClass().getName(), this);
18040        }
18041
18042        final Rect bounds = drawable.getBounds();
18043        final int width = bounds.width();
18044        final int height = bounds.height();
18045        final DisplayListCanvas canvas = renderNode.start(width, height);
18046
18047        // Reverse left/top translation done by drawable canvas, which will
18048        // instead be applied by rendernode's LTRB bounds below. This way, the
18049        // drawable's bounds match with its rendernode bounds and its content
18050        // will lie within those bounds in the rendernode tree.
18051        canvas.translate(-bounds.left, -bounds.top);
18052
18053        try {
18054            drawable.draw(canvas);
18055        } finally {
18056            renderNode.end(canvas);
18057        }
18058
18059        // Set up drawable properties that are view-independent.
18060        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
18061        renderNode.setProjectBackwards(drawable.isProjected());
18062        renderNode.setProjectionReceiver(true);
18063        renderNode.setClipToBounds(false);
18064        return renderNode;
18065    }
18066
18067    /**
18068     * Returns the overlay for this view, creating it if it does not yet exist.
18069     * Adding drawables to the overlay will cause them to be displayed whenever
18070     * the view itself is redrawn. Objects in the overlay should be actively
18071     * managed: remove them when they should not be displayed anymore. The
18072     * overlay will always have the same size as its host view.
18073     *
18074     * <p>Note: Overlays do not currently work correctly with {@link
18075     * SurfaceView} or {@link TextureView}; contents in overlays for these
18076     * types of views may not display correctly.</p>
18077     *
18078     * @return The ViewOverlay object for this view.
18079     * @see ViewOverlay
18080     */
18081    public ViewOverlay getOverlay() {
18082        if (mOverlay == null) {
18083            mOverlay = new ViewOverlay(mContext, this);
18084        }
18085        return mOverlay;
18086    }
18087
18088    /**
18089     * Override this if your view is known to always be drawn on top of a solid color background,
18090     * and needs to draw fading edges. Returning a non-zero color enables the view system to
18091     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
18092     * should be set to 0xFF.
18093     *
18094     * @see #setVerticalFadingEdgeEnabled(boolean)
18095     * @see #setHorizontalFadingEdgeEnabled(boolean)
18096     *
18097     * @return The known solid color background for this view, or 0 if the color may vary
18098     */
18099    @ViewDebug.ExportedProperty(category = "drawing")
18100    @ColorInt
18101    public int getSolidColor() {
18102        return 0;
18103    }
18104
18105    /**
18106     * Build a human readable string representation of the specified view flags.
18107     *
18108     * @param flags the view flags to convert to a string
18109     * @return a String representing the supplied flags
18110     */
18111    private static String printFlags(int flags) {
18112        String output = "";
18113        int numFlags = 0;
18114        if ((flags & FOCUSABLE) == FOCUSABLE) {
18115            output += "TAKES_FOCUS";
18116            numFlags++;
18117        }
18118
18119        switch (flags & VISIBILITY_MASK) {
18120        case INVISIBLE:
18121            if (numFlags > 0) {
18122                output += " ";
18123            }
18124            output += "INVISIBLE";
18125            // USELESS HERE numFlags++;
18126            break;
18127        case GONE:
18128            if (numFlags > 0) {
18129                output += " ";
18130            }
18131            output += "GONE";
18132            // USELESS HERE numFlags++;
18133            break;
18134        default:
18135            break;
18136        }
18137        return output;
18138    }
18139
18140    /**
18141     * Build a human readable string representation of the specified private
18142     * view flags.
18143     *
18144     * @param privateFlags the private view flags to convert to a string
18145     * @return a String representing the supplied flags
18146     */
18147    private static String printPrivateFlags(int privateFlags) {
18148        String output = "";
18149        int numFlags = 0;
18150
18151        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
18152            output += "WANTS_FOCUS";
18153            numFlags++;
18154        }
18155
18156        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
18157            if (numFlags > 0) {
18158                output += " ";
18159            }
18160            output += "FOCUSED";
18161            numFlags++;
18162        }
18163
18164        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
18165            if (numFlags > 0) {
18166                output += " ";
18167            }
18168            output += "SELECTED";
18169            numFlags++;
18170        }
18171
18172        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
18173            if (numFlags > 0) {
18174                output += " ";
18175            }
18176            output += "IS_ROOT_NAMESPACE";
18177            numFlags++;
18178        }
18179
18180        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
18181            if (numFlags > 0) {
18182                output += " ";
18183            }
18184            output += "HAS_BOUNDS";
18185            numFlags++;
18186        }
18187
18188        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
18189            if (numFlags > 0) {
18190                output += " ";
18191            }
18192            output += "DRAWN";
18193            // USELESS HERE numFlags++;
18194        }
18195        return output;
18196    }
18197
18198    /**
18199     * <p>Indicates whether or not this view's layout will be requested during
18200     * the next hierarchy layout pass.</p>
18201     *
18202     * @return true if the layout will be forced during next layout pass
18203     */
18204    public boolean isLayoutRequested() {
18205        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18206    }
18207
18208    /**
18209     * Return true if o is a ViewGroup that is laying out using optical bounds.
18210     * @hide
18211     */
18212    public static boolean isLayoutModeOptical(Object o) {
18213        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
18214    }
18215
18216    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
18217        Insets parentInsets = mParent instanceof View ?
18218                ((View) mParent).getOpticalInsets() : Insets.NONE;
18219        Insets childInsets = getOpticalInsets();
18220        return setFrame(
18221                left   + parentInsets.left - childInsets.left,
18222                top    + parentInsets.top  - childInsets.top,
18223                right  + parentInsets.left + childInsets.right,
18224                bottom + parentInsets.top  + childInsets.bottom);
18225    }
18226
18227    /**
18228     * Assign a size and position to a view and all of its
18229     * descendants
18230     *
18231     * <p>This is the second phase of the layout mechanism.
18232     * (The first is measuring). In this phase, each parent calls
18233     * layout on all of its children to position them.
18234     * This is typically done using the child measurements
18235     * that were stored in the measure pass().</p>
18236     *
18237     * <p>Derived classes should not override this method.
18238     * Derived classes with children should override
18239     * onLayout. In that method, they should
18240     * call layout on each of their children.</p>
18241     *
18242     * @param l Left position, relative to parent
18243     * @param t Top position, relative to parent
18244     * @param r Right position, relative to parent
18245     * @param b Bottom position, relative to parent
18246     */
18247    @SuppressWarnings({"unchecked"})
18248    public void layout(int l, int t, int r, int b) {
18249        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
18250            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
18251            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18252        }
18253
18254        int oldL = mLeft;
18255        int oldT = mTop;
18256        int oldB = mBottom;
18257        int oldR = mRight;
18258
18259        boolean changed = isLayoutModeOptical(mParent) ?
18260                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
18261
18262        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
18263            onLayout(changed, l, t, r, b);
18264
18265            if (shouldDrawRoundScrollbar()) {
18266                if(mRoundScrollbarRenderer == null) {
18267                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
18268                }
18269            } else {
18270                mRoundScrollbarRenderer = null;
18271            }
18272
18273            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
18274
18275            ListenerInfo li = mListenerInfo;
18276            if (li != null && li.mOnLayoutChangeListeners != null) {
18277                ArrayList<OnLayoutChangeListener> listenersCopy =
18278                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
18279                int numListeners = listenersCopy.size();
18280                for (int i = 0; i < numListeners; ++i) {
18281                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
18282                }
18283            }
18284        }
18285
18286        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
18287        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
18288    }
18289
18290    /**
18291     * Called from layout when this view should
18292     * assign a size and position to each of its children.
18293     *
18294     * Derived classes with children should override
18295     * this method and call layout on each of
18296     * their children.
18297     * @param changed This is a new size or position for this view
18298     * @param left Left position, relative to parent
18299     * @param top Top position, relative to parent
18300     * @param right Right position, relative to parent
18301     * @param bottom Bottom position, relative to parent
18302     */
18303    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
18304    }
18305
18306    /**
18307     * Assign a size and position to this view.
18308     *
18309     * This is called from layout.
18310     *
18311     * @param left Left position, relative to parent
18312     * @param top Top position, relative to parent
18313     * @param right Right position, relative to parent
18314     * @param bottom Bottom position, relative to parent
18315     * @return true if the new size and position are different than the
18316     *         previous ones
18317     * {@hide}
18318     */
18319    protected boolean setFrame(int left, int top, int right, int bottom) {
18320        boolean changed = false;
18321
18322        if (DBG) {
18323            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
18324                    + right + "," + bottom + ")");
18325        }
18326
18327        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
18328            changed = true;
18329
18330            // Remember our drawn bit
18331            int drawn = mPrivateFlags & PFLAG_DRAWN;
18332
18333            int oldWidth = mRight - mLeft;
18334            int oldHeight = mBottom - mTop;
18335            int newWidth = right - left;
18336            int newHeight = bottom - top;
18337            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
18338
18339            // Invalidate our old position
18340            invalidate(sizeChanged);
18341
18342            mLeft = left;
18343            mTop = top;
18344            mRight = right;
18345            mBottom = bottom;
18346            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
18347
18348            mPrivateFlags |= PFLAG_HAS_BOUNDS;
18349
18350
18351            if (sizeChanged) {
18352                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
18353            }
18354
18355            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
18356                // If we are visible, force the DRAWN bit to on so that
18357                // this invalidate will go through (at least to our parent).
18358                // This is because someone may have invalidated this view
18359                // before this call to setFrame came in, thereby clearing
18360                // the DRAWN bit.
18361                mPrivateFlags |= PFLAG_DRAWN;
18362                invalidate(sizeChanged);
18363                // parent display list may need to be recreated based on a change in the bounds
18364                // of any child
18365                invalidateParentCaches();
18366            }
18367
18368            // Reset drawn bit to original value (invalidate turns it off)
18369            mPrivateFlags |= drawn;
18370
18371            mBackgroundSizeChanged = true;
18372            if (mForegroundInfo != null) {
18373                mForegroundInfo.mBoundsChanged = true;
18374            }
18375
18376            notifySubtreeAccessibilityStateChangedIfNeeded();
18377        }
18378        return changed;
18379    }
18380
18381    /**
18382     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
18383     * @hide
18384     */
18385    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
18386        setFrame(left, top, right, bottom);
18387    }
18388
18389    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
18390        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
18391        if (mOverlay != null) {
18392            mOverlay.getOverlayView().setRight(newWidth);
18393            mOverlay.getOverlayView().setBottom(newHeight);
18394        }
18395        rebuildOutline();
18396    }
18397
18398    /**
18399     * Finalize inflating a view from XML.  This is called as the last phase
18400     * of inflation, after all child views have been added.
18401     *
18402     * <p>Even if the subclass overrides onFinishInflate, they should always be
18403     * sure to call the super method, so that we get called.
18404     */
18405    @CallSuper
18406    protected void onFinishInflate() {
18407    }
18408
18409    /**
18410     * Returns the resources associated with this view.
18411     *
18412     * @return Resources object.
18413     */
18414    public Resources getResources() {
18415        return mResources;
18416    }
18417
18418    /**
18419     * Invalidates the specified Drawable.
18420     *
18421     * @param drawable the drawable to invalidate
18422     */
18423    @Override
18424    public void invalidateDrawable(@NonNull Drawable drawable) {
18425        if (verifyDrawable(drawable)) {
18426            final Rect dirty = drawable.getDirtyBounds();
18427            final int scrollX = mScrollX;
18428            final int scrollY = mScrollY;
18429
18430            invalidate(dirty.left + scrollX, dirty.top + scrollY,
18431                    dirty.right + scrollX, dirty.bottom + scrollY);
18432            rebuildOutline();
18433        }
18434    }
18435
18436    /**
18437     * Schedules an action on a drawable to occur at a specified time.
18438     *
18439     * @param who the recipient of the action
18440     * @param what the action to run on the drawable
18441     * @param when the time at which the action must occur. Uses the
18442     *        {@link SystemClock#uptimeMillis} timebase.
18443     */
18444    @Override
18445    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
18446        if (verifyDrawable(who) && what != null) {
18447            final long delay = when - SystemClock.uptimeMillis();
18448            if (mAttachInfo != null) {
18449                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
18450                        Choreographer.CALLBACK_ANIMATION, what, who,
18451                        Choreographer.subtractFrameDelay(delay));
18452            } else {
18453                // Postpone the runnable until we know
18454                // on which thread it needs to run.
18455                getRunQueue().postDelayed(what, delay);
18456            }
18457        }
18458    }
18459
18460    /**
18461     * Cancels a scheduled action on a drawable.
18462     *
18463     * @param who the recipient of the action
18464     * @param what the action to cancel
18465     */
18466    @Override
18467    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
18468        if (verifyDrawable(who) && what != null) {
18469            if (mAttachInfo != null) {
18470                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18471                        Choreographer.CALLBACK_ANIMATION, what, who);
18472            }
18473            getRunQueue().removeCallbacks(what);
18474        }
18475    }
18476
18477    /**
18478     * Unschedule any events associated with the given Drawable.  This can be
18479     * used when selecting a new Drawable into a view, so that the previous
18480     * one is completely unscheduled.
18481     *
18482     * @param who The Drawable to unschedule.
18483     *
18484     * @see #drawableStateChanged
18485     */
18486    public void unscheduleDrawable(Drawable who) {
18487        if (mAttachInfo != null && who != null) {
18488            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18489                    Choreographer.CALLBACK_ANIMATION, null, who);
18490        }
18491    }
18492
18493    /**
18494     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
18495     * that the View directionality can and will be resolved before its Drawables.
18496     *
18497     * Will call {@link View#onResolveDrawables} when resolution is done.
18498     *
18499     * @hide
18500     */
18501    protected void resolveDrawables() {
18502        // Drawables resolution may need to happen before resolving the layout direction (which is
18503        // done only during the measure() call).
18504        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
18505        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
18506        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
18507        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
18508        // direction to be resolved as its resolved value will be the same as its raw value.
18509        if (!isLayoutDirectionResolved() &&
18510                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
18511            return;
18512        }
18513
18514        final int layoutDirection = isLayoutDirectionResolved() ?
18515                getLayoutDirection() : getRawLayoutDirection();
18516
18517        if (mBackground != null) {
18518            mBackground.setLayoutDirection(layoutDirection);
18519        }
18520        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18521            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
18522        }
18523        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
18524        onResolveDrawables(layoutDirection);
18525    }
18526
18527    boolean areDrawablesResolved() {
18528        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
18529    }
18530
18531    /**
18532     * Called when layout direction has been resolved.
18533     *
18534     * The default implementation does nothing.
18535     *
18536     * @param layoutDirection The resolved layout direction.
18537     *
18538     * @see #LAYOUT_DIRECTION_LTR
18539     * @see #LAYOUT_DIRECTION_RTL
18540     *
18541     * @hide
18542     */
18543    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
18544    }
18545
18546    /**
18547     * @hide
18548     */
18549    protected void resetResolvedDrawables() {
18550        resetResolvedDrawablesInternal();
18551    }
18552
18553    void resetResolvedDrawablesInternal() {
18554        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
18555    }
18556
18557    /**
18558     * If your view subclass is displaying its own Drawable objects, it should
18559     * override this function and return true for any Drawable it is
18560     * displaying.  This allows animations for those drawables to be
18561     * scheduled.
18562     *
18563     * <p>Be sure to call through to the super class when overriding this
18564     * function.
18565     *
18566     * @param who The Drawable to verify.  Return true if it is one you are
18567     *            displaying, else return the result of calling through to the
18568     *            super class.
18569     *
18570     * @return boolean If true than the Drawable is being displayed in the
18571     *         view; else false and it is not allowed to animate.
18572     *
18573     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
18574     * @see #drawableStateChanged()
18575     */
18576    @CallSuper
18577    protected boolean verifyDrawable(@NonNull Drawable who) {
18578        // Avoid verifying the scroll bar drawable so that we don't end up in
18579        // an invalidation loop. This effectively prevents the scroll bar
18580        // drawable from triggering invalidations and scheduling runnables.
18581        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
18582    }
18583
18584    /**
18585     * This function is called whenever the state of the view changes in such
18586     * a way that it impacts the state of drawables being shown.
18587     * <p>
18588     * If the View has a StateListAnimator, it will also be called to run necessary state
18589     * change animations.
18590     * <p>
18591     * Be sure to call through to the superclass when overriding this function.
18592     *
18593     * @see Drawable#setState(int[])
18594     */
18595    @CallSuper
18596    protected void drawableStateChanged() {
18597        final int[] state = getDrawableState();
18598        boolean changed = false;
18599
18600        final Drawable bg = mBackground;
18601        if (bg != null && bg.isStateful()) {
18602            changed |= bg.setState(state);
18603        }
18604
18605        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18606        if (fg != null && fg.isStateful()) {
18607            changed |= fg.setState(state);
18608        }
18609
18610        if (mScrollCache != null) {
18611            final Drawable scrollBar = mScrollCache.scrollBar;
18612            if (scrollBar != null && scrollBar.isStateful()) {
18613                changed |= scrollBar.setState(state)
18614                        && mScrollCache.state != ScrollabilityCache.OFF;
18615            }
18616        }
18617
18618        if (mStateListAnimator != null) {
18619            mStateListAnimator.setState(state);
18620        }
18621
18622        if (changed) {
18623            invalidate();
18624        }
18625    }
18626
18627    /**
18628     * This function is called whenever the view hotspot changes and needs to
18629     * be propagated to drawables or child views managed by the view.
18630     * <p>
18631     * Dispatching to child views is handled by
18632     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18633     * <p>
18634     * Be sure to call through to the superclass when overriding this function.
18635     *
18636     * @param x hotspot x coordinate
18637     * @param y hotspot y coordinate
18638     */
18639    @CallSuper
18640    public void drawableHotspotChanged(float x, float y) {
18641        if (mBackground != null) {
18642            mBackground.setHotspot(x, y);
18643        }
18644        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18645            mForegroundInfo.mDrawable.setHotspot(x, y);
18646        }
18647
18648        dispatchDrawableHotspotChanged(x, y);
18649    }
18650
18651    /**
18652     * Dispatches drawableHotspotChanged to all of this View's children.
18653     *
18654     * @param x hotspot x coordinate
18655     * @param y hotspot y coordinate
18656     * @see #drawableHotspotChanged(float, float)
18657     */
18658    public void dispatchDrawableHotspotChanged(float x, float y) {
18659    }
18660
18661    /**
18662     * Call this to force a view to update its drawable state. This will cause
18663     * drawableStateChanged to be called on this view. Views that are interested
18664     * in the new state should call getDrawableState.
18665     *
18666     * @see #drawableStateChanged
18667     * @see #getDrawableState
18668     */
18669    public void refreshDrawableState() {
18670        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18671        drawableStateChanged();
18672
18673        ViewParent parent = mParent;
18674        if (parent != null) {
18675            parent.childDrawableStateChanged(this);
18676        }
18677    }
18678
18679    /**
18680     * Return an array of resource IDs of the drawable states representing the
18681     * current state of the view.
18682     *
18683     * @return The current drawable state
18684     *
18685     * @see Drawable#setState(int[])
18686     * @see #drawableStateChanged()
18687     * @see #onCreateDrawableState(int)
18688     */
18689    public final int[] getDrawableState() {
18690        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
18691            return mDrawableState;
18692        } else {
18693            mDrawableState = onCreateDrawableState(0);
18694            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
18695            return mDrawableState;
18696        }
18697    }
18698
18699    /**
18700     * Generate the new {@link android.graphics.drawable.Drawable} state for
18701     * this view. This is called by the view
18702     * system when the cached Drawable state is determined to be invalid.  To
18703     * retrieve the current state, you should use {@link #getDrawableState}.
18704     *
18705     * @param extraSpace if non-zero, this is the number of extra entries you
18706     * would like in the returned array in which you can place your own
18707     * states.
18708     *
18709     * @return Returns an array holding the current {@link Drawable} state of
18710     * the view.
18711     *
18712     * @see #mergeDrawableStates(int[], int[])
18713     */
18714    protected int[] onCreateDrawableState(int extraSpace) {
18715        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
18716                mParent instanceof View) {
18717            return ((View) mParent).onCreateDrawableState(extraSpace);
18718        }
18719
18720        int[] drawableState;
18721
18722        int privateFlags = mPrivateFlags;
18723
18724        int viewStateIndex = 0;
18725        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
18726        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
18727        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
18728        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
18729        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
18730        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
18731        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
18732                ThreadedRenderer.isAvailable()) {
18733            // This is set if HW acceleration is requested, even if the current
18734            // process doesn't allow it.  This is just to allow app preview
18735            // windows to better match their app.
18736            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
18737        }
18738        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
18739
18740        final int privateFlags2 = mPrivateFlags2;
18741        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
18742            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
18743        }
18744        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
18745            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
18746        }
18747
18748        drawableState = StateSet.get(viewStateIndex);
18749
18750        //noinspection ConstantIfStatement
18751        if (false) {
18752            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18753            Log.i("View", toString()
18754                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18755                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18756                    + " fo=" + hasFocus()
18757                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18758                    + " wf=" + hasWindowFocus()
18759                    + ": " + Arrays.toString(drawableState));
18760        }
18761
18762        if (extraSpace == 0) {
18763            return drawableState;
18764        }
18765
18766        final int[] fullState;
18767        if (drawableState != null) {
18768            fullState = new int[drawableState.length + extraSpace];
18769            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18770        } else {
18771            fullState = new int[extraSpace];
18772        }
18773
18774        return fullState;
18775    }
18776
18777    /**
18778     * Merge your own state values in <var>additionalState</var> into the base
18779     * state values <var>baseState</var> that were returned by
18780     * {@link #onCreateDrawableState(int)}.
18781     *
18782     * @param baseState The base state values returned by
18783     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18784     * own additional state values.
18785     *
18786     * @param additionalState The additional state values you would like
18787     * added to <var>baseState</var>; this array is not modified.
18788     *
18789     * @return As a convenience, the <var>baseState</var> array you originally
18790     * passed into the function is returned.
18791     *
18792     * @see #onCreateDrawableState(int)
18793     */
18794    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18795        final int N = baseState.length;
18796        int i = N - 1;
18797        while (i >= 0 && baseState[i] == 0) {
18798            i--;
18799        }
18800        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18801        return baseState;
18802    }
18803
18804    /**
18805     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18806     * on all Drawable objects associated with this view.
18807     * <p>
18808     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18809     * attached to this view.
18810     */
18811    @CallSuper
18812    public void jumpDrawablesToCurrentState() {
18813        if (mBackground != null) {
18814            mBackground.jumpToCurrentState();
18815        }
18816        if (mStateListAnimator != null) {
18817            mStateListAnimator.jumpToCurrentState();
18818        }
18819        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18820            mForegroundInfo.mDrawable.jumpToCurrentState();
18821        }
18822    }
18823
18824    /**
18825     * Sets the background color for this view.
18826     * @param color the color of the background
18827     */
18828    @RemotableViewMethod
18829    public void setBackgroundColor(@ColorInt int color) {
18830        if (mBackground instanceof ColorDrawable) {
18831            ((ColorDrawable) mBackground.mutate()).setColor(color);
18832            computeOpaqueFlags();
18833            mBackgroundResource = 0;
18834        } else {
18835            setBackground(new ColorDrawable(color));
18836        }
18837    }
18838
18839    /**
18840     * Set the background to a given resource. The resource should refer to
18841     * a Drawable object or 0 to remove the background.
18842     * @param resid The identifier of the resource.
18843     *
18844     * @attr ref android.R.styleable#View_background
18845     */
18846    @RemotableViewMethod
18847    public void setBackgroundResource(@DrawableRes int resid) {
18848        if (resid != 0 && resid == mBackgroundResource) {
18849            return;
18850        }
18851
18852        Drawable d = null;
18853        if (resid != 0) {
18854            d = mContext.getDrawable(resid);
18855        }
18856        setBackground(d);
18857
18858        mBackgroundResource = resid;
18859    }
18860
18861    /**
18862     * Set the background to a given Drawable, or remove the background. If the
18863     * background has padding, this View's padding is set to the background's
18864     * padding. However, when a background is removed, this View's padding isn't
18865     * touched. If setting the padding is desired, please use
18866     * {@link #setPadding(int, int, int, int)}.
18867     *
18868     * @param background The Drawable to use as the background, or null to remove the
18869     *        background
18870     */
18871    public void setBackground(Drawable background) {
18872        //noinspection deprecation
18873        setBackgroundDrawable(background);
18874    }
18875
18876    /**
18877     * @deprecated use {@link #setBackground(Drawable)} instead
18878     */
18879    @Deprecated
18880    public void setBackgroundDrawable(Drawable background) {
18881        computeOpaqueFlags();
18882
18883        if (background == mBackground) {
18884            return;
18885        }
18886
18887        boolean requestLayout = false;
18888
18889        mBackgroundResource = 0;
18890
18891        /*
18892         * Regardless of whether we're setting a new background or not, we want
18893         * to clear the previous drawable. setVisible first while we still have the callback set.
18894         */
18895        if (mBackground != null) {
18896            if (isAttachedToWindow()) {
18897                mBackground.setVisible(false, false);
18898            }
18899            mBackground.setCallback(null);
18900            unscheduleDrawable(mBackground);
18901        }
18902
18903        if (background != null) {
18904            Rect padding = sThreadLocal.get();
18905            if (padding == null) {
18906                padding = new Rect();
18907                sThreadLocal.set(padding);
18908            }
18909            resetResolvedDrawablesInternal();
18910            background.setLayoutDirection(getLayoutDirection());
18911            if (background.getPadding(padding)) {
18912                resetResolvedPaddingInternal();
18913                switch (background.getLayoutDirection()) {
18914                    case LAYOUT_DIRECTION_RTL:
18915                        mUserPaddingLeftInitial = padding.right;
18916                        mUserPaddingRightInitial = padding.left;
18917                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18918                        break;
18919                    case LAYOUT_DIRECTION_LTR:
18920                    default:
18921                        mUserPaddingLeftInitial = padding.left;
18922                        mUserPaddingRightInitial = padding.right;
18923                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18924                }
18925                mLeftPaddingDefined = false;
18926                mRightPaddingDefined = false;
18927            }
18928
18929            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18930            // if it has a different minimum size, we should layout again
18931            if (mBackground == null
18932                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18933                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18934                requestLayout = true;
18935            }
18936
18937            // Set mBackground before we set this as the callback and start making other
18938            // background drawable state change calls. In particular, the setVisible call below
18939            // can result in drawables attempting to start animations or otherwise invalidate,
18940            // which requires the view set as the callback (us) to recognize the drawable as
18941            // belonging to it as per verifyDrawable.
18942            mBackground = background;
18943            if (background.isStateful()) {
18944                background.setState(getDrawableState());
18945            }
18946            if (isAttachedToWindow()) {
18947                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18948            }
18949
18950            applyBackgroundTint();
18951
18952            // Set callback last, since the view may still be initializing.
18953            background.setCallback(this);
18954
18955            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18956                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18957                requestLayout = true;
18958            }
18959        } else {
18960            /* Remove the background */
18961            mBackground = null;
18962            if ((mViewFlags & WILL_NOT_DRAW) != 0
18963                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18964                mPrivateFlags |= PFLAG_SKIP_DRAW;
18965            }
18966
18967            /*
18968             * When the background is set, we try to apply its padding to this
18969             * View. When the background is removed, we don't touch this View's
18970             * padding. This is noted in the Javadocs. Hence, we don't need to
18971             * requestLayout(), the invalidate() below is sufficient.
18972             */
18973
18974            // The old background's minimum size could have affected this
18975            // View's layout, so let's requestLayout
18976            requestLayout = true;
18977        }
18978
18979        computeOpaqueFlags();
18980
18981        if (requestLayout) {
18982            requestLayout();
18983        }
18984
18985        mBackgroundSizeChanged = true;
18986        invalidate(true);
18987        invalidateOutline();
18988    }
18989
18990    /**
18991     * Gets the background drawable
18992     *
18993     * @return The drawable used as the background for this view, if any.
18994     *
18995     * @see #setBackground(Drawable)
18996     *
18997     * @attr ref android.R.styleable#View_background
18998     */
18999    public Drawable getBackground() {
19000        return mBackground;
19001    }
19002
19003    /**
19004     * Applies a tint to the background drawable. Does not modify the current tint
19005     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19006     * <p>
19007     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
19008     * mutate the drawable and apply the specified tint and tint mode using
19009     * {@link Drawable#setTintList(ColorStateList)}.
19010     *
19011     * @param tint the tint to apply, may be {@code null} to clear tint
19012     *
19013     * @attr ref android.R.styleable#View_backgroundTint
19014     * @see #getBackgroundTintList()
19015     * @see Drawable#setTintList(ColorStateList)
19016     */
19017    public void setBackgroundTintList(@Nullable ColorStateList tint) {
19018        if (mBackgroundTint == null) {
19019            mBackgroundTint = new TintInfo();
19020        }
19021        mBackgroundTint.mTintList = tint;
19022        mBackgroundTint.mHasTintList = true;
19023
19024        applyBackgroundTint();
19025    }
19026
19027    /**
19028     * Return the tint applied to the background drawable, if specified.
19029     *
19030     * @return the tint applied to the background drawable
19031     * @attr ref android.R.styleable#View_backgroundTint
19032     * @see #setBackgroundTintList(ColorStateList)
19033     */
19034    @Nullable
19035    public ColorStateList getBackgroundTintList() {
19036        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
19037    }
19038
19039    /**
19040     * Specifies the blending mode used to apply the tint specified by
19041     * {@link #setBackgroundTintList(ColorStateList)}} to the background
19042     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19043     *
19044     * @param tintMode the blending mode used to apply the tint, may be
19045     *                 {@code null} to clear tint
19046     * @attr ref android.R.styleable#View_backgroundTintMode
19047     * @see #getBackgroundTintMode()
19048     * @see Drawable#setTintMode(PorterDuff.Mode)
19049     */
19050    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19051        if (mBackgroundTint == null) {
19052            mBackgroundTint = new TintInfo();
19053        }
19054        mBackgroundTint.mTintMode = tintMode;
19055        mBackgroundTint.mHasTintMode = true;
19056
19057        applyBackgroundTint();
19058    }
19059
19060    /**
19061     * Return the blending mode used to apply the tint to the background
19062     * drawable, if specified.
19063     *
19064     * @return the blending mode used to apply the tint to the background
19065     *         drawable
19066     * @attr ref android.R.styleable#View_backgroundTintMode
19067     * @see #setBackgroundTintMode(PorterDuff.Mode)
19068     */
19069    @Nullable
19070    public PorterDuff.Mode getBackgroundTintMode() {
19071        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
19072    }
19073
19074    private void applyBackgroundTint() {
19075        if (mBackground != null && mBackgroundTint != null) {
19076            final TintInfo tintInfo = mBackgroundTint;
19077            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19078                mBackground = mBackground.mutate();
19079
19080                if (tintInfo.mHasTintList) {
19081                    mBackground.setTintList(tintInfo.mTintList);
19082                }
19083
19084                if (tintInfo.mHasTintMode) {
19085                    mBackground.setTintMode(tintInfo.mTintMode);
19086                }
19087
19088                // The drawable (or one of its children) may not have been
19089                // stateful before applying the tint, so let's try again.
19090                if (mBackground.isStateful()) {
19091                    mBackground.setState(getDrawableState());
19092                }
19093            }
19094        }
19095    }
19096
19097    /**
19098     * Returns the drawable used as the foreground of this View. The
19099     * foreground drawable, if non-null, is always drawn on top of the view's content.
19100     *
19101     * @return a Drawable or null if no foreground was set
19102     *
19103     * @see #onDrawForeground(Canvas)
19104     */
19105    public Drawable getForeground() {
19106        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19107    }
19108
19109    /**
19110     * Supply a Drawable that is to be rendered on top of all of the content in the view.
19111     *
19112     * @param foreground the Drawable to be drawn on top of the children
19113     *
19114     * @attr ref android.R.styleable#View_foreground
19115     */
19116    public void setForeground(Drawable foreground) {
19117        if (mForegroundInfo == null) {
19118            if (foreground == null) {
19119                // Nothing to do.
19120                return;
19121            }
19122            mForegroundInfo = new ForegroundInfo();
19123        }
19124
19125        if (foreground == mForegroundInfo.mDrawable) {
19126            // Nothing to do
19127            return;
19128        }
19129
19130        if (mForegroundInfo.mDrawable != null) {
19131            if (isAttachedToWindow()) {
19132                mForegroundInfo.mDrawable.setVisible(false, false);
19133            }
19134            mForegroundInfo.mDrawable.setCallback(null);
19135            unscheduleDrawable(mForegroundInfo.mDrawable);
19136        }
19137
19138        mForegroundInfo.mDrawable = foreground;
19139        mForegroundInfo.mBoundsChanged = true;
19140        if (foreground != null) {
19141            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19142                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19143            }
19144            foreground.setLayoutDirection(getLayoutDirection());
19145            if (foreground.isStateful()) {
19146                foreground.setState(getDrawableState());
19147            }
19148            applyForegroundTint();
19149            if (isAttachedToWindow()) {
19150                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19151            }
19152            // Set callback last, since the view may still be initializing.
19153            foreground.setCallback(this);
19154        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
19155            mPrivateFlags |= PFLAG_SKIP_DRAW;
19156        }
19157        requestLayout();
19158        invalidate();
19159    }
19160
19161    /**
19162     * Magic bit used to support features of framework-internal window decor implementation details.
19163     * This used to live exclusively in FrameLayout.
19164     *
19165     * @return true if the foreground should draw inside the padding region or false
19166     *         if it should draw inset by the view's padding
19167     * @hide internal use only; only used by FrameLayout and internal screen layouts.
19168     */
19169    public boolean isForegroundInsidePadding() {
19170        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
19171    }
19172
19173    /**
19174     * Describes how the foreground is positioned.
19175     *
19176     * @return foreground gravity.
19177     *
19178     * @see #setForegroundGravity(int)
19179     *
19180     * @attr ref android.R.styleable#View_foregroundGravity
19181     */
19182    public int getForegroundGravity() {
19183        return mForegroundInfo != null ? mForegroundInfo.mGravity
19184                : Gravity.START | Gravity.TOP;
19185    }
19186
19187    /**
19188     * Describes how the foreground is positioned. Defaults to START and TOP.
19189     *
19190     * @param gravity see {@link android.view.Gravity}
19191     *
19192     * @see #getForegroundGravity()
19193     *
19194     * @attr ref android.R.styleable#View_foregroundGravity
19195     */
19196    public void setForegroundGravity(int gravity) {
19197        if (mForegroundInfo == null) {
19198            mForegroundInfo = new ForegroundInfo();
19199        }
19200
19201        if (mForegroundInfo.mGravity != gravity) {
19202            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
19203                gravity |= Gravity.START;
19204            }
19205
19206            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
19207                gravity |= Gravity.TOP;
19208            }
19209
19210            mForegroundInfo.mGravity = gravity;
19211            requestLayout();
19212        }
19213    }
19214
19215    /**
19216     * Applies a tint to the foreground drawable. Does not modify the current tint
19217     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19218     * <p>
19219     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
19220     * mutate the drawable and apply the specified tint and tint mode using
19221     * {@link Drawable#setTintList(ColorStateList)}.
19222     *
19223     * @param tint the tint to apply, may be {@code null} to clear tint
19224     *
19225     * @attr ref android.R.styleable#View_foregroundTint
19226     * @see #getForegroundTintList()
19227     * @see Drawable#setTintList(ColorStateList)
19228     */
19229    public void setForegroundTintList(@Nullable ColorStateList tint) {
19230        if (mForegroundInfo == null) {
19231            mForegroundInfo = new ForegroundInfo();
19232        }
19233        if (mForegroundInfo.mTintInfo == null) {
19234            mForegroundInfo.mTintInfo = new TintInfo();
19235        }
19236        mForegroundInfo.mTintInfo.mTintList = tint;
19237        mForegroundInfo.mTintInfo.mHasTintList = true;
19238
19239        applyForegroundTint();
19240    }
19241
19242    /**
19243     * Return the tint applied to the foreground drawable, if specified.
19244     *
19245     * @return the tint applied to the foreground drawable
19246     * @attr ref android.R.styleable#View_foregroundTint
19247     * @see #setForegroundTintList(ColorStateList)
19248     */
19249    @Nullable
19250    public ColorStateList getForegroundTintList() {
19251        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19252                ? mForegroundInfo.mTintInfo.mTintList : null;
19253    }
19254
19255    /**
19256     * Specifies the blending mode used to apply the tint specified by
19257     * {@link #setForegroundTintList(ColorStateList)}} to the background
19258     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19259     *
19260     * @param tintMode the blending mode used to apply the tint, may be
19261     *                 {@code null} to clear tint
19262     * @attr ref android.R.styleable#View_foregroundTintMode
19263     * @see #getForegroundTintMode()
19264     * @see Drawable#setTintMode(PorterDuff.Mode)
19265     */
19266    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19267        if (mForegroundInfo == null) {
19268            mForegroundInfo = new ForegroundInfo();
19269        }
19270        if (mForegroundInfo.mTintInfo == null) {
19271            mForegroundInfo.mTintInfo = new TintInfo();
19272        }
19273        mForegroundInfo.mTintInfo.mTintMode = tintMode;
19274        mForegroundInfo.mTintInfo.mHasTintMode = true;
19275
19276        applyForegroundTint();
19277    }
19278
19279    /**
19280     * Return the blending mode used to apply the tint to the foreground
19281     * drawable, if specified.
19282     *
19283     * @return the blending mode used to apply the tint to the foreground
19284     *         drawable
19285     * @attr ref android.R.styleable#View_foregroundTintMode
19286     * @see #setForegroundTintMode(PorterDuff.Mode)
19287     */
19288    @Nullable
19289    public PorterDuff.Mode getForegroundTintMode() {
19290        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19291                ? mForegroundInfo.mTintInfo.mTintMode : null;
19292    }
19293
19294    private void applyForegroundTint() {
19295        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
19296                && mForegroundInfo.mTintInfo != null) {
19297            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
19298            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19299                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
19300
19301                if (tintInfo.mHasTintList) {
19302                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
19303                }
19304
19305                if (tintInfo.mHasTintMode) {
19306                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
19307                }
19308
19309                // The drawable (or one of its children) may not have been
19310                // stateful before applying the tint, so let's try again.
19311                if (mForegroundInfo.mDrawable.isStateful()) {
19312                    mForegroundInfo.mDrawable.setState(getDrawableState());
19313                }
19314            }
19315        }
19316    }
19317
19318    /**
19319     * Draw any foreground content for this view.
19320     *
19321     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
19322     * drawable or other view-specific decorations. The foreground is drawn on top of the
19323     * primary view content.</p>
19324     *
19325     * @param canvas canvas to draw into
19326     */
19327    public void onDrawForeground(Canvas canvas) {
19328        onDrawScrollIndicators(canvas);
19329        onDrawScrollBars(canvas);
19330
19331        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19332        if (foreground != null) {
19333            if (mForegroundInfo.mBoundsChanged) {
19334                mForegroundInfo.mBoundsChanged = false;
19335                final Rect selfBounds = mForegroundInfo.mSelfBounds;
19336                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
19337
19338                if (mForegroundInfo.mInsidePadding) {
19339                    selfBounds.set(0, 0, getWidth(), getHeight());
19340                } else {
19341                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
19342                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
19343                }
19344
19345                final int ld = getLayoutDirection();
19346                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
19347                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
19348                foreground.setBounds(overlayBounds);
19349            }
19350
19351            foreground.draw(canvas);
19352        }
19353    }
19354
19355    /**
19356     * Sets the padding. The view may add on the space required to display
19357     * the scrollbars, depending on the style and visibility of the scrollbars.
19358     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
19359     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
19360     * from the values set in this call.
19361     *
19362     * @attr ref android.R.styleable#View_padding
19363     * @attr ref android.R.styleable#View_paddingBottom
19364     * @attr ref android.R.styleable#View_paddingLeft
19365     * @attr ref android.R.styleable#View_paddingRight
19366     * @attr ref android.R.styleable#View_paddingTop
19367     * @param left the left padding in pixels
19368     * @param top the top padding in pixels
19369     * @param right the right padding in pixels
19370     * @param bottom the bottom padding in pixels
19371     */
19372    public void setPadding(int left, int top, int right, int bottom) {
19373        resetResolvedPaddingInternal();
19374
19375        mUserPaddingStart = UNDEFINED_PADDING;
19376        mUserPaddingEnd = UNDEFINED_PADDING;
19377
19378        mUserPaddingLeftInitial = left;
19379        mUserPaddingRightInitial = right;
19380
19381        mLeftPaddingDefined = true;
19382        mRightPaddingDefined = true;
19383
19384        internalSetPadding(left, top, right, bottom);
19385    }
19386
19387    /**
19388     * @hide
19389     */
19390    protected void internalSetPadding(int left, int top, int right, int bottom) {
19391        mUserPaddingLeft = left;
19392        mUserPaddingRight = right;
19393        mUserPaddingBottom = bottom;
19394
19395        final int viewFlags = mViewFlags;
19396        boolean changed = false;
19397
19398        // Common case is there are no scroll bars.
19399        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
19400            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
19401                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
19402                        ? 0 : getVerticalScrollbarWidth();
19403                switch (mVerticalScrollbarPosition) {
19404                    case SCROLLBAR_POSITION_DEFAULT:
19405                        if (isLayoutRtl()) {
19406                            left += offset;
19407                        } else {
19408                            right += offset;
19409                        }
19410                        break;
19411                    case SCROLLBAR_POSITION_RIGHT:
19412                        right += offset;
19413                        break;
19414                    case SCROLLBAR_POSITION_LEFT:
19415                        left += offset;
19416                        break;
19417                }
19418            }
19419            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
19420                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
19421                        ? 0 : getHorizontalScrollbarHeight();
19422            }
19423        }
19424
19425        if (mPaddingLeft != left) {
19426            changed = true;
19427            mPaddingLeft = left;
19428        }
19429        if (mPaddingTop != top) {
19430            changed = true;
19431            mPaddingTop = top;
19432        }
19433        if (mPaddingRight != right) {
19434            changed = true;
19435            mPaddingRight = right;
19436        }
19437        if (mPaddingBottom != bottom) {
19438            changed = true;
19439            mPaddingBottom = bottom;
19440        }
19441
19442        if (changed) {
19443            requestLayout();
19444            invalidateOutline();
19445        }
19446    }
19447
19448    /**
19449     * Sets the relative padding. The view may add on the space required to display
19450     * the scrollbars, depending on the style and visibility of the scrollbars.
19451     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
19452     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
19453     * from the values set in this call.
19454     *
19455     * @attr ref android.R.styleable#View_padding
19456     * @attr ref android.R.styleable#View_paddingBottom
19457     * @attr ref android.R.styleable#View_paddingStart
19458     * @attr ref android.R.styleable#View_paddingEnd
19459     * @attr ref android.R.styleable#View_paddingTop
19460     * @param start the start padding in pixels
19461     * @param top the top padding in pixels
19462     * @param end the end padding in pixels
19463     * @param bottom the bottom padding in pixels
19464     */
19465    public void setPaddingRelative(int start, int top, int end, int bottom) {
19466        resetResolvedPaddingInternal();
19467
19468        mUserPaddingStart = start;
19469        mUserPaddingEnd = end;
19470        mLeftPaddingDefined = true;
19471        mRightPaddingDefined = true;
19472
19473        switch(getLayoutDirection()) {
19474            case LAYOUT_DIRECTION_RTL:
19475                mUserPaddingLeftInitial = end;
19476                mUserPaddingRightInitial = start;
19477                internalSetPadding(end, top, start, bottom);
19478                break;
19479            case LAYOUT_DIRECTION_LTR:
19480            default:
19481                mUserPaddingLeftInitial = start;
19482                mUserPaddingRightInitial = end;
19483                internalSetPadding(start, top, end, bottom);
19484        }
19485    }
19486
19487    /**
19488     * Returns the top padding of this view.
19489     *
19490     * @return the top padding in pixels
19491     */
19492    public int getPaddingTop() {
19493        return mPaddingTop;
19494    }
19495
19496    /**
19497     * Returns the bottom padding of this view. If there are inset and enabled
19498     * scrollbars, this value may include the space required to display the
19499     * scrollbars as well.
19500     *
19501     * @return the bottom padding in pixels
19502     */
19503    public int getPaddingBottom() {
19504        return mPaddingBottom;
19505    }
19506
19507    /**
19508     * Returns the left padding of this view. If there are inset and enabled
19509     * scrollbars, this value may include the space required to display the
19510     * scrollbars as well.
19511     *
19512     * @return the left padding in pixels
19513     */
19514    public int getPaddingLeft() {
19515        if (!isPaddingResolved()) {
19516            resolvePadding();
19517        }
19518        return mPaddingLeft;
19519    }
19520
19521    /**
19522     * Returns the start padding of this view depending on its resolved layout direction.
19523     * If there are inset and enabled scrollbars, this value may include the space
19524     * required to display the scrollbars as well.
19525     *
19526     * @return the start padding in pixels
19527     */
19528    public int getPaddingStart() {
19529        if (!isPaddingResolved()) {
19530            resolvePadding();
19531        }
19532        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19533                mPaddingRight : mPaddingLeft;
19534    }
19535
19536    /**
19537     * Returns the right padding of this view. If there are inset and enabled
19538     * scrollbars, this value may include the space required to display the
19539     * scrollbars as well.
19540     *
19541     * @return the right padding in pixels
19542     */
19543    public int getPaddingRight() {
19544        if (!isPaddingResolved()) {
19545            resolvePadding();
19546        }
19547        return mPaddingRight;
19548    }
19549
19550    /**
19551     * Returns the end padding of this view depending on its resolved layout direction.
19552     * If there are inset and enabled scrollbars, this value may include the space
19553     * required to display the scrollbars as well.
19554     *
19555     * @return the end padding in pixels
19556     */
19557    public int getPaddingEnd() {
19558        if (!isPaddingResolved()) {
19559            resolvePadding();
19560        }
19561        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19562                mPaddingLeft : mPaddingRight;
19563    }
19564
19565    /**
19566     * Return if the padding has been set through relative values
19567     * {@link #setPaddingRelative(int, int, int, int)} or through
19568     * @attr ref android.R.styleable#View_paddingStart or
19569     * @attr ref android.R.styleable#View_paddingEnd
19570     *
19571     * @return true if the padding is relative or false if it is not.
19572     */
19573    public boolean isPaddingRelative() {
19574        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
19575    }
19576
19577    Insets computeOpticalInsets() {
19578        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
19579    }
19580
19581    /**
19582     * @hide
19583     */
19584    public void resetPaddingToInitialValues() {
19585        if (isRtlCompatibilityMode()) {
19586            mPaddingLeft = mUserPaddingLeftInitial;
19587            mPaddingRight = mUserPaddingRightInitial;
19588            return;
19589        }
19590        if (isLayoutRtl()) {
19591            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
19592            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
19593        } else {
19594            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
19595            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
19596        }
19597    }
19598
19599    /**
19600     * @hide
19601     */
19602    public Insets getOpticalInsets() {
19603        if (mLayoutInsets == null) {
19604            mLayoutInsets = computeOpticalInsets();
19605        }
19606        return mLayoutInsets;
19607    }
19608
19609    /**
19610     * Set this view's optical insets.
19611     *
19612     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
19613     * property. Views that compute their own optical insets should call it as part of measurement.
19614     * This method does not request layout. If you are setting optical insets outside of
19615     * measure/layout itself you will want to call requestLayout() yourself.
19616     * </p>
19617     * @hide
19618     */
19619    public void setOpticalInsets(Insets insets) {
19620        mLayoutInsets = insets;
19621    }
19622
19623    /**
19624     * Changes the selection state of this view. A view can be selected or not.
19625     * Note that selection is not the same as focus. Views are typically
19626     * selected in the context of an AdapterView like ListView or GridView;
19627     * the selected view is the view that is highlighted.
19628     *
19629     * @param selected true if the view must be selected, false otherwise
19630     */
19631    public void setSelected(boolean selected) {
19632        //noinspection DoubleNegation
19633        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19634            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19635            if (!selected) resetPressedState();
19636            invalidate(true);
19637            refreshDrawableState();
19638            dispatchSetSelected(selected);
19639            if (selected) {
19640                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19641            } else {
19642                notifyViewAccessibilityStateChangedIfNeeded(
19643                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19644            }
19645        }
19646    }
19647
19648    /**
19649     * Dispatch setSelected to all of this View's children.
19650     *
19651     * @see #setSelected(boolean)
19652     *
19653     * @param selected The new selected state
19654     */
19655    protected void dispatchSetSelected(boolean selected) {
19656    }
19657
19658    /**
19659     * Indicates the selection state of this view.
19660     *
19661     * @return true if the view is selected, false otherwise
19662     */
19663    @ViewDebug.ExportedProperty
19664    public boolean isSelected() {
19665        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19666    }
19667
19668    /**
19669     * Changes the activated state of this view. A view can be activated or not.
19670     * Note that activation is not the same as selection.  Selection is
19671     * a transient property, representing the view (hierarchy) the user is
19672     * currently interacting with.  Activation is a longer-term state that the
19673     * user can move views in and out of.  For example, in a list view with
19674     * single or multiple selection enabled, the views in the current selection
19675     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19676     * here.)  The activated state is propagated down to children of the view it
19677     * is set on.
19678     *
19679     * @param activated true if the view must be activated, false otherwise
19680     */
19681    public void setActivated(boolean activated) {
19682        //noinspection DoubleNegation
19683        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19684            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19685            invalidate(true);
19686            refreshDrawableState();
19687            dispatchSetActivated(activated);
19688        }
19689    }
19690
19691    /**
19692     * Dispatch setActivated to all of this View's children.
19693     *
19694     * @see #setActivated(boolean)
19695     *
19696     * @param activated The new activated state
19697     */
19698    protected void dispatchSetActivated(boolean activated) {
19699    }
19700
19701    /**
19702     * Indicates the activation state of this view.
19703     *
19704     * @return true if the view is activated, false otherwise
19705     */
19706    @ViewDebug.ExportedProperty
19707    public boolean isActivated() {
19708        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
19709    }
19710
19711    /**
19712     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
19713     * observer can be used to get notifications when global events, like
19714     * layout, happen.
19715     *
19716     * The returned ViewTreeObserver observer is not guaranteed to remain
19717     * valid for the lifetime of this View. If the caller of this method keeps
19718     * a long-lived reference to ViewTreeObserver, it should always check for
19719     * the return value of {@link ViewTreeObserver#isAlive()}.
19720     *
19721     * @return The ViewTreeObserver for this view's hierarchy.
19722     */
19723    public ViewTreeObserver getViewTreeObserver() {
19724        if (mAttachInfo != null) {
19725            return mAttachInfo.mTreeObserver;
19726        }
19727        if (mFloatingTreeObserver == null) {
19728            mFloatingTreeObserver = new ViewTreeObserver(mContext);
19729        }
19730        return mFloatingTreeObserver;
19731    }
19732
19733    /**
19734     * <p>Finds the topmost view in the current view hierarchy.</p>
19735     *
19736     * @return the topmost view containing this view
19737     */
19738    public View getRootView() {
19739        if (mAttachInfo != null) {
19740            final View v = mAttachInfo.mRootView;
19741            if (v != null) {
19742                return v;
19743            }
19744        }
19745
19746        View parent = this;
19747
19748        while (parent.mParent != null && parent.mParent instanceof View) {
19749            parent = (View) parent.mParent;
19750        }
19751
19752        return parent;
19753    }
19754
19755    /**
19756     * Transforms a motion event from view-local coordinates to on-screen
19757     * coordinates.
19758     *
19759     * @param ev the view-local motion event
19760     * @return false if the transformation could not be applied
19761     * @hide
19762     */
19763    public boolean toGlobalMotionEvent(MotionEvent ev) {
19764        final AttachInfo info = mAttachInfo;
19765        if (info == null) {
19766            return false;
19767        }
19768
19769        final Matrix m = info.mTmpMatrix;
19770        m.set(Matrix.IDENTITY_MATRIX);
19771        transformMatrixToGlobal(m);
19772        ev.transform(m);
19773        return true;
19774    }
19775
19776    /**
19777     * Transforms a motion event from on-screen coordinates to view-local
19778     * coordinates.
19779     *
19780     * @param ev the on-screen motion event
19781     * @return false if the transformation could not be applied
19782     * @hide
19783     */
19784    public boolean toLocalMotionEvent(MotionEvent ev) {
19785        final AttachInfo info = mAttachInfo;
19786        if (info == null) {
19787            return false;
19788        }
19789
19790        final Matrix m = info.mTmpMatrix;
19791        m.set(Matrix.IDENTITY_MATRIX);
19792        transformMatrixToLocal(m);
19793        ev.transform(m);
19794        return true;
19795    }
19796
19797    /**
19798     * Modifies the input matrix such that it maps view-local coordinates to
19799     * on-screen coordinates.
19800     *
19801     * @param m input matrix to modify
19802     * @hide
19803     */
19804    public void transformMatrixToGlobal(Matrix m) {
19805        final ViewParent parent = mParent;
19806        if (parent instanceof View) {
19807            final View vp = (View) parent;
19808            vp.transformMatrixToGlobal(m);
19809            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19810        } else if (parent instanceof ViewRootImpl) {
19811            final ViewRootImpl vr = (ViewRootImpl) parent;
19812            vr.transformMatrixToGlobal(m);
19813            m.preTranslate(0, -vr.mCurScrollY);
19814        }
19815
19816        m.preTranslate(mLeft, mTop);
19817
19818        if (!hasIdentityMatrix()) {
19819            m.preConcat(getMatrix());
19820        }
19821    }
19822
19823    /**
19824     * Modifies the input matrix such that it maps on-screen coordinates to
19825     * view-local coordinates.
19826     *
19827     * @param m input matrix to modify
19828     * @hide
19829     */
19830    public void transformMatrixToLocal(Matrix m) {
19831        final ViewParent parent = mParent;
19832        if (parent instanceof View) {
19833            final View vp = (View) parent;
19834            vp.transformMatrixToLocal(m);
19835            m.postTranslate(vp.mScrollX, vp.mScrollY);
19836        } else if (parent instanceof ViewRootImpl) {
19837            final ViewRootImpl vr = (ViewRootImpl) parent;
19838            vr.transformMatrixToLocal(m);
19839            m.postTranslate(0, vr.mCurScrollY);
19840        }
19841
19842        m.postTranslate(-mLeft, -mTop);
19843
19844        if (!hasIdentityMatrix()) {
19845            m.postConcat(getInverseMatrix());
19846        }
19847    }
19848
19849    /**
19850     * @hide
19851     */
19852    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19853            @ViewDebug.IntToString(from = 0, to = "x"),
19854            @ViewDebug.IntToString(from = 1, to = "y")
19855    })
19856    public int[] getLocationOnScreen() {
19857        int[] location = new int[2];
19858        getLocationOnScreen(location);
19859        return location;
19860    }
19861
19862    /**
19863     * <p>Computes the coordinates of this view on the screen. The argument
19864     * must be an array of two integers. After the method returns, the array
19865     * contains the x and y location in that order.</p>
19866     *
19867     * @param outLocation an array of two integers in which to hold the coordinates
19868     */
19869    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19870        getLocationInWindow(outLocation);
19871
19872        final AttachInfo info = mAttachInfo;
19873        if (info != null) {
19874            outLocation[0] += info.mWindowLeft;
19875            outLocation[1] += info.mWindowTop;
19876        }
19877    }
19878
19879    /**
19880     * <p>Computes the coordinates of this view in its window. The argument
19881     * must be an array of two integers. After the method returns, the array
19882     * contains the x and y location in that order.</p>
19883     *
19884     * @param outLocation an array of two integers in which to hold the coordinates
19885     */
19886    public void getLocationInWindow(@Size(2) int[] outLocation) {
19887        if (outLocation == null || outLocation.length < 2) {
19888            throw new IllegalArgumentException("outLocation must be an array of two integers");
19889        }
19890
19891        outLocation[0] = 0;
19892        outLocation[1] = 0;
19893
19894        transformFromViewToWindowSpace(outLocation);
19895    }
19896
19897    /** @hide */
19898    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19899        if (inOutLocation == null || inOutLocation.length < 2) {
19900            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19901        }
19902
19903        if (mAttachInfo == null) {
19904            // When the view is not attached to a window, this method does not make sense
19905            inOutLocation[0] = inOutLocation[1] = 0;
19906            return;
19907        }
19908
19909        float position[] = mAttachInfo.mTmpTransformLocation;
19910        position[0] = inOutLocation[0];
19911        position[1] = inOutLocation[1];
19912
19913        if (!hasIdentityMatrix()) {
19914            getMatrix().mapPoints(position);
19915        }
19916
19917        position[0] += mLeft;
19918        position[1] += mTop;
19919
19920        ViewParent viewParent = mParent;
19921        while (viewParent instanceof View) {
19922            final View view = (View) viewParent;
19923
19924            position[0] -= view.mScrollX;
19925            position[1] -= view.mScrollY;
19926
19927            if (!view.hasIdentityMatrix()) {
19928                view.getMatrix().mapPoints(position);
19929            }
19930
19931            position[0] += view.mLeft;
19932            position[1] += view.mTop;
19933
19934            viewParent = view.mParent;
19935         }
19936
19937        if (viewParent instanceof ViewRootImpl) {
19938            // *cough*
19939            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19940            position[1] -= vr.mCurScrollY;
19941        }
19942
19943        inOutLocation[0] = Math.round(position[0]);
19944        inOutLocation[1] = Math.round(position[1]);
19945    }
19946
19947    /**
19948     * {@hide}
19949     * @param id the id of the view to be found
19950     * @return the view of the specified id, null if cannot be found
19951     */
19952    protected View findViewTraversal(@IdRes int id) {
19953        if (id == mID) {
19954            return this;
19955        }
19956        return null;
19957    }
19958
19959    /**
19960     * {@hide}
19961     * @param tag the tag of the view to be found
19962     * @return the view of specified tag, null if cannot be found
19963     */
19964    protected View findViewWithTagTraversal(Object tag) {
19965        if (tag != null && tag.equals(mTag)) {
19966            return this;
19967        }
19968        return null;
19969    }
19970
19971    /**
19972     * {@hide}
19973     * @param predicate The predicate to evaluate.
19974     * @param childToSkip If not null, ignores this child during the recursive traversal.
19975     * @return The first view that matches the predicate or null.
19976     */
19977    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19978        if (predicate.apply(this)) {
19979            return this;
19980        }
19981        return null;
19982    }
19983
19984    /**
19985     * Look for a child view with the given id.  If this view has the given
19986     * id, return this view.
19987     *
19988     * @param id The id to search for.
19989     * @return The view that has the given id in the hierarchy or null
19990     */
19991    @Nullable
19992    public final View findViewById(@IdRes int id) {
19993        if (id < 0) {
19994            return null;
19995        }
19996        return findViewTraversal(id);
19997    }
19998
19999    /**
20000     * Finds a view by its unuque and stable accessibility id.
20001     *
20002     * @param accessibilityId The searched accessibility id.
20003     * @return The found view.
20004     */
20005    final View findViewByAccessibilityId(int accessibilityId) {
20006        if (accessibilityId < 0) {
20007            return null;
20008        }
20009        View view = findViewByAccessibilityIdTraversal(accessibilityId);
20010        if (view != null) {
20011            return view.includeForAccessibility() ? view : null;
20012        }
20013        return null;
20014    }
20015
20016    /**
20017     * Performs the traversal to find a view by its unuque and stable accessibility id.
20018     *
20019     * <strong>Note:</strong>This method does not stop at the root namespace
20020     * boundary since the user can touch the screen at an arbitrary location
20021     * potentially crossing the root namespace bounday which will send an
20022     * accessibility event to accessibility services and they should be able
20023     * to obtain the event source. Also accessibility ids are guaranteed to be
20024     * unique in the window.
20025     *
20026     * @param accessibilityId The accessibility id.
20027     * @return The found view.
20028     *
20029     * @hide
20030     */
20031    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
20032        if (getAccessibilityViewId() == accessibilityId) {
20033            return this;
20034        }
20035        return null;
20036    }
20037
20038    /**
20039     * Look for a child view with the given tag.  If this view has the given
20040     * tag, return this view.
20041     *
20042     * @param tag The tag to search for, using "tag.equals(getTag())".
20043     * @return The View that has the given tag in the hierarchy or null
20044     */
20045    public final View findViewWithTag(Object tag) {
20046        if (tag == null) {
20047            return null;
20048        }
20049        return findViewWithTagTraversal(tag);
20050    }
20051
20052    /**
20053     * {@hide}
20054     * Look for a child view that matches the specified predicate.
20055     * If this view matches the predicate, return this view.
20056     *
20057     * @param predicate The predicate to evaluate.
20058     * @return The first view that matches the predicate or null.
20059     */
20060    public final View findViewByPredicate(Predicate<View> predicate) {
20061        return findViewByPredicateTraversal(predicate, null);
20062    }
20063
20064    /**
20065     * {@hide}
20066     * Look for a child view that matches the specified predicate,
20067     * starting with the specified view and its descendents and then
20068     * recusively searching the ancestors and siblings of that view
20069     * until this view is reached.
20070     *
20071     * This method is useful in cases where the predicate does not match
20072     * a single unique view (perhaps multiple views use the same id)
20073     * and we are trying to find the view that is "closest" in scope to the
20074     * starting view.
20075     *
20076     * @param start The view to start from.
20077     * @param predicate The predicate to evaluate.
20078     * @return The first view that matches the predicate or null.
20079     */
20080    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
20081        View childToSkip = null;
20082        for (;;) {
20083            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
20084            if (view != null || start == this) {
20085                return view;
20086            }
20087
20088            ViewParent parent = start.getParent();
20089            if (parent == null || !(parent instanceof View)) {
20090                return null;
20091            }
20092
20093            childToSkip = start;
20094            start = (View) parent;
20095        }
20096    }
20097
20098    /**
20099     * Sets the identifier for this view. The identifier does not have to be
20100     * unique in this view's hierarchy. The identifier should be a positive
20101     * number.
20102     *
20103     * @see #NO_ID
20104     * @see #getId()
20105     * @see #findViewById(int)
20106     *
20107     * @param id a number used to identify the view
20108     *
20109     * @attr ref android.R.styleable#View_id
20110     */
20111    public void setId(@IdRes int id) {
20112        mID = id;
20113        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
20114            mID = generateViewId();
20115        }
20116    }
20117
20118    /**
20119     * {@hide}
20120     *
20121     * @param isRoot true if the view belongs to the root namespace, false
20122     *        otherwise
20123     */
20124    public void setIsRootNamespace(boolean isRoot) {
20125        if (isRoot) {
20126            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
20127        } else {
20128            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
20129        }
20130    }
20131
20132    /**
20133     * {@hide}
20134     *
20135     * @return true if the view belongs to the root namespace, false otherwise
20136     */
20137    public boolean isRootNamespace() {
20138        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
20139    }
20140
20141    /**
20142     * Returns this view's identifier.
20143     *
20144     * @return a positive integer used to identify the view or {@link #NO_ID}
20145     *         if the view has no ID
20146     *
20147     * @see #setId(int)
20148     * @see #findViewById(int)
20149     * @attr ref android.R.styleable#View_id
20150     */
20151    @IdRes
20152    @ViewDebug.CapturedViewProperty
20153    public int getId() {
20154        return mID;
20155    }
20156
20157    /**
20158     * Returns this view's tag.
20159     *
20160     * @return the Object stored in this view as a tag, or {@code null} if not
20161     *         set
20162     *
20163     * @see #setTag(Object)
20164     * @see #getTag(int)
20165     */
20166    @ViewDebug.ExportedProperty
20167    public Object getTag() {
20168        return mTag;
20169    }
20170
20171    /**
20172     * Sets the tag associated with this view. A tag can be used to mark
20173     * a view in its hierarchy and does not have to be unique within the
20174     * hierarchy. Tags can also be used to store data within a view without
20175     * resorting to another data structure.
20176     *
20177     * @param tag an Object to tag the view with
20178     *
20179     * @see #getTag()
20180     * @see #setTag(int, Object)
20181     */
20182    public void setTag(final Object tag) {
20183        mTag = tag;
20184    }
20185
20186    /**
20187     * Returns the tag associated with this view and the specified key.
20188     *
20189     * @param key The key identifying the tag
20190     *
20191     * @return the Object stored in this view as a tag, or {@code null} if not
20192     *         set
20193     *
20194     * @see #setTag(int, Object)
20195     * @see #getTag()
20196     */
20197    public Object getTag(int key) {
20198        if (mKeyedTags != null) return mKeyedTags.get(key);
20199        return null;
20200    }
20201
20202    /**
20203     * Sets a tag associated with this view and a key. A tag can be used
20204     * to mark a view in its hierarchy and does not have to be unique within
20205     * the hierarchy. Tags can also be used to store data within a view
20206     * without resorting to another data structure.
20207     *
20208     * The specified key should be an id declared in the resources of the
20209     * application to ensure it is unique (see the <a
20210     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
20211     * Keys identified as belonging to
20212     * the Android framework or not associated with any package will cause
20213     * an {@link IllegalArgumentException} to be thrown.
20214     *
20215     * @param key The key identifying the tag
20216     * @param tag An Object to tag the view with
20217     *
20218     * @throws IllegalArgumentException If they specified key is not valid
20219     *
20220     * @see #setTag(Object)
20221     * @see #getTag(int)
20222     */
20223    public void setTag(int key, final Object tag) {
20224        // If the package id is 0x00 or 0x01, it's either an undefined package
20225        // or a framework id
20226        if ((key >>> 24) < 2) {
20227            throw new IllegalArgumentException("The key must be an application-specific "
20228                    + "resource id.");
20229        }
20230
20231        setKeyedTag(key, tag);
20232    }
20233
20234    /**
20235     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
20236     * framework id.
20237     *
20238     * @hide
20239     */
20240    public void setTagInternal(int key, Object tag) {
20241        if ((key >>> 24) != 0x1) {
20242            throw new IllegalArgumentException("The key must be a framework-specific "
20243                    + "resource id.");
20244        }
20245
20246        setKeyedTag(key, tag);
20247    }
20248
20249    private void setKeyedTag(int key, Object tag) {
20250        if (mKeyedTags == null) {
20251            mKeyedTags = new SparseArray<Object>(2);
20252        }
20253
20254        mKeyedTags.put(key, tag);
20255    }
20256
20257    /**
20258     * Prints information about this view in the log output, with the tag
20259     * {@link #VIEW_LOG_TAG}.
20260     *
20261     * @hide
20262     */
20263    public void debug() {
20264        debug(0);
20265    }
20266
20267    /**
20268     * Prints information about this view in the log output, with the tag
20269     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
20270     * indentation defined by the <code>depth</code>.
20271     *
20272     * @param depth the indentation level
20273     *
20274     * @hide
20275     */
20276    protected void debug(int depth) {
20277        String output = debugIndent(depth - 1);
20278
20279        output += "+ " + this;
20280        int id = getId();
20281        if (id != -1) {
20282            output += " (id=" + id + ")";
20283        }
20284        Object tag = getTag();
20285        if (tag != null) {
20286            output += " (tag=" + tag + ")";
20287        }
20288        Log.d(VIEW_LOG_TAG, output);
20289
20290        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
20291            output = debugIndent(depth) + " FOCUSED";
20292            Log.d(VIEW_LOG_TAG, output);
20293        }
20294
20295        output = debugIndent(depth);
20296        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
20297                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
20298                + "} ";
20299        Log.d(VIEW_LOG_TAG, output);
20300
20301        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
20302                || mPaddingBottom != 0) {
20303            output = debugIndent(depth);
20304            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
20305                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
20306            Log.d(VIEW_LOG_TAG, output);
20307        }
20308
20309        output = debugIndent(depth);
20310        output += "mMeasureWidth=" + mMeasuredWidth +
20311                " mMeasureHeight=" + mMeasuredHeight;
20312        Log.d(VIEW_LOG_TAG, output);
20313
20314        output = debugIndent(depth);
20315        if (mLayoutParams == null) {
20316            output += "BAD! no layout params";
20317        } else {
20318            output = mLayoutParams.debug(output);
20319        }
20320        Log.d(VIEW_LOG_TAG, output);
20321
20322        output = debugIndent(depth);
20323        output += "flags={";
20324        output += View.printFlags(mViewFlags);
20325        output += "}";
20326        Log.d(VIEW_LOG_TAG, output);
20327
20328        output = debugIndent(depth);
20329        output += "privateFlags={";
20330        output += View.printPrivateFlags(mPrivateFlags);
20331        output += "}";
20332        Log.d(VIEW_LOG_TAG, output);
20333    }
20334
20335    /**
20336     * Creates a string of whitespaces used for indentation.
20337     *
20338     * @param depth the indentation level
20339     * @return a String containing (depth * 2 + 3) * 2 white spaces
20340     *
20341     * @hide
20342     */
20343    protected static String debugIndent(int depth) {
20344        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
20345        for (int i = 0; i < (depth * 2) + 3; i++) {
20346            spaces.append(' ').append(' ');
20347        }
20348        return spaces.toString();
20349    }
20350
20351    /**
20352     * <p>Return the offset of the widget's text baseline from the widget's top
20353     * boundary. If this widget does not support baseline alignment, this
20354     * method returns -1. </p>
20355     *
20356     * @return the offset of the baseline within the widget's bounds or -1
20357     *         if baseline alignment is not supported
20358     */
20359    @ViewDebug.ExportedProperty(category = "layout")
20360    public int getBaseline() {
20361        return -1;
20362    }
20363
20364    /**
20365     * Returns whether the view hierarchy is currently undergoing a layout pass. This
20366     * information is useful to avoid situations such as calling {@link #requestLayout()} during
20367     * a layout pass.
20368     *
20369     * @return whether the view hierarchy is currently undergoing a layout pass
20370     */
20371    public boolean isInLayout() {
20372        ViewRootImpl viewRoot = getViewRootImpl();
20373        return (viewRoot != null && viewRoot.isInLayout());
20374    }
20375
20376    /**
20377     * Call this when something has changed which has invalidated the
20378     * layout of this view. This will schedule a layout pass of the view
20379     * tree. This should not be called while the view hierarchy is currently in a layout
20380     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
20381     * end of the current layout pass (and then layout will run again) or after the current
20382     * frame is drawn and the next layout occurs.
20383     *
20384     * <p>Subclasses which override this method should call the superclass method to
20385     * handle possible request-during-layout errors correctly.</p>
20386     */
20387    @CallSuper
20388    public void requestLayout() {
20389        if (mMeasureCache != null) mMeasureCache.clear();
20390
20391        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
20392            // Only trigger request-during-layout logic if this is the view requesting it,
20393            // not the views in its parent hierarchy
20394            ViewRootImpl viewRoot = getViewRootImpl();
20395            if (viewRoot != null && viewRoot.isInLayout()) {
20396                if (!viewRoot.requestLayoutDuringLayout(this)) {
20397                    return;
20398                }
20399            }
20400            mAttachInfo.mViewRequestingLayout = this;
20401        }
20402
20403        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20404        mPrivateFlags |= PFLAG_INVALIDATED;
20405
20406        if (mParent != null && !mParent.isLayoutRequested()) {
20407            mParent.requestLayout();
20408        }
20409        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
20410            mAttachInfo.mViewRequestingLayout = null;
20411        }
20412    }
20413
20414    /**
20415     * Forces this view to be laid out during the next layout pass.
20416     * This method does not call requestLayout() or forceLayout()
20417     * on the parent.
20418     */
20419    public void forceLayout() {
20420        if (mMeasureCache != null) mMeasureCache.clear();
20421
20422        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20423        mPrivateFlags |= PFLAG_INVALIDATED;
20424    }
20425
20426    /**
20427     * <p>
20428     * This is called to find out how big a view should be. The parent
20429     * supplies constraint information in the width and height parameters.
20430     * </p>
20431     *
20432     * <p>
20433     * The actual measurement work of a view is performed in
20434     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
20435     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
20436     * </p>
20437     *
20438     *
20439     * @param widthMeasureSpec Horizontal space requirements as imposed by the
20440     *        parent
20441     * @param heightMeasureSpec Vertical space requirements as imposed by the
20442     *        parent
20443     *
20444     * @see #onMeasure(int, int)
20445     */
20446    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
20447        boolean optical = isLayoutModeOptical(this);
20448        if (optical != isLayoutModeOptical(mParent)) {
20449            Insets insets = getOpticalInsets();
20450            int oWidth  = insets.left + insets.right;
20451            int oHeight = insets.top  + insets.bottom;
20452            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
20453            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
20454        }
20455
20456        // Suppress sign extension for the low bytes
20457        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
20458        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
20459
20460        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20461
20462        // Optimize layout by avoiding an extra EXACTLY pass when the view is
20463        // already measured as the correct size. In API 23 and below, this
20464        // extra pass is required to make LinearLayout re-distribute weight.
20465        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
20466                || heightMeasureSpec != mOldHeightMeasureSpec;
20467        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
20468                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
20469        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
20470                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
20471        final boolean needsLayout = specChanged
20472                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
20473
20474        if (forceLayout || needsLayout) {
20475            // first clears the measured dimension flag
20476            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
20477
20478            resolveRtlPropertiesIfNeeded();
20479
20480            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
20481            if (cacheIndex < 0 || sIgnoreMeasureCache) {
20482                // measure ourselves, this should set the measured dimension flag back
20483                onMeasure(widthMeasureSpec, heightMeasureSpec);
20484                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20485            } else {
20486                long value = mMeasureCache.valueAt(cacheIndex);
20487                // Casting a long to int drops the high 32 bits, no mask needed
20488                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
20489                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20490            }
20491
20492            // flag not set, setMeasuredDimension() was not invoked, we raise
20493            // an exception to warn the developer
20494            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
20495                throw new IllegalStateException("View with id " + getId() + ": "
20496                        + getClass().getName() + "#onMeasure() did not set the"
20497                        + " measured dimension by calling"
20498                        + " setMeasuredDimension()");
20499            }
20500
20501            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
20502        }
20503
20504        mOldWidthMeasureSpec = widthMeasureSpec;
20505        mOldHeightMeasureSpec = heightMeasureSpec;
20506
20507        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
20508                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
20509    }
20510
20511    /**
20512     * <p>
20513     * Measure the view and its content to determine the measured width and the
20514     * measured height. This method is invoked by {@link #measure(int, int)} and
20515     * should be overridden by subclasses to provide accurate and efficient
20516     * measurement of their contents.
20517     * </p>
20518     *
20519     * <p>
20520     * <strong>CONTRACT:</strong> When overriding this method, you
20521     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
20522     * measured width and height of this view. Failure to do so will trigger an
20523     * <code>IllegalStateException</code>, thrown by
20524     * {@link #measure(int, int)}. Calling the superclass'
20525     * {@link #onMeasure(int, int)} is a valid use.
20526     * </p>
20527     *
20528     * <p>
20529     * The base class implementation of measure defaults to the background size,
20530     * unless a larger size is allowed by the MeasureSpec. Subclasses should
20531     * override {@link #onMeasure(int, int)} to provide better measurements of
20532     * their content.
20533     * </p>
20534     *
20535     * <p>
20536     * If this method is overridden, it is the subclass's responsibility to make
20537     * sure the measured height and width are at least the view's minimum height
20538     * and width ({@link #getSuggestedMinimumHeight()} and
20539     * {@link #getSuggestedMinimumWidth()}).
20540     * </p>
20541     *
20542     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
20543     *                         The requirements are encoded with
20544     *                         {@link android.view.View.MeasureSpec}.
20545     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
20546     *                         The requirements are encoded with
20547     *                         {@link android.view.View.MeasureSpec}.
20548     *
20549     * @see #getMeasuredWidth()
20550     * @see #getMeasuredHeight()
20551     * @see #setMeasuredDimension(int, int)
20552     * @see #getSuggestedMinimumHeight()
20553     * @see #getSuggestedMinimumWidth()
20554     * @see android.view.View.MeasureSpec#getMode(int)
20555     * @see android.view.View.MeasureSpec#getSize(int)
20556     */
20557    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
20558        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
20559                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
20560    }
20561
20562    /**
20563     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
20564     * measured width and measured height. Failing to do so will trigger an
20565     * exception at measurement time.</p>
20566     *
20567     * @param measuredWidth The measured width of this view.  May be a complex
20568     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20569     * {@link #MEASURED_STATE_TOO_SMALL}.
20570     * @param measuredHeight The measured height of this view.  May be a complex
20571     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20572     * {@link #MEASURED_STATE_TOO_SMALL}.
20573     */
20574    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
20575        boolean optical = isLayoutModeOptical(this);
20576        if (optical != isLayoutModeOptical(mParent)) {
20577            Insets insets = getOpticalInsets();
20578            int opticalWidth  = insets.left + insets.right;
20579            int opticalHeight = insets.top  + insets.bottom;
20580
20581            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
20582            measuredHeight += optical ? opticalHeight : -opticalHeight;
20583        }
20584        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
20585    }
20586
20587    /**
20588     * Sets the measured dimension without extra processing for things like optical bounds.
20589     * Useful for reapplying consistent values that have already been cooked with adjustments
20590     * for optical bounds, etc. such as those from the measurement cache.
20591     *
20592     * @param measuredWidth The measured width of this view.  May be a complex
20593     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20594     * {@link #MEASURED_STATE_TOO_SMALL}.
20595     * @param measuredHeight The measured height of this view.  May be a complex
20596     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20597     * {@link #MEASURED_STATE_TOO_SMALL}.
20598     */
20599    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
20600        mMeasuredWidth = measuredWidth;
20601        mMeasuredHeight = measuredHeight;
20602
20603        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
20604    }
20605
20606    /**
20607     * Merge two states as returned by {@link #getMeasuredState()}.
20608     * @param curState The current state as returned from a view or the result
20609     * of combining multiple views.
20610     * @param newState The new view state to combine.
20611     * @return Returns a new integer reflecting the combination of the two
20612     * states.
20613     */
20614    public static int combineMeasuredStates(int curState, int newState) {
20615        return curState | newState;
20616    }
20617
20618    /**
20619     * Version of {@link #resolveSizeAndState(int, int, int)}
20620     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
20621     */
20622    public static int resolveSize(int size, int measureSpec) {
20623        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
20624    }
20625
20626    /**
20627     * Utility to reconcile a desired size and state, with constraints imposed
20628     * by a MeasureSpec. Will take the desired size, unless a different size
20629     * is imposed by the constraints. The returned value is a compound integer,
20630     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20631     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20632     * resulting size is smaller than the size the view wants to be.
20633     *
20634     * @param size How big the view wants to be.
20635     * @param measureSpec Constraints imposed by the parent.
20636     * @param childMeasuredState Size information bit mask for the view's
20637     *                           children.
20638     * @return Size information bit mask as defined by
20639     *         {@link #MEASURED_SIZE_MASK} and
20640     *         {@link #MEASURED_STATE_TOO_SMALL}.
20641     */
20642    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20643        final int specMode = MeasureSpec.getMode(measureSpec);
20644        final int specSize = MeasureSpec.getSize(measureSpec);
20645        final int result;
20646        switch (specMode) {
20647            case MeasureSpec.AT_MOST:
20648                if (specSize < size) {
20649                    result = specSize | MEASURED_STATE_TOO_SMALL;
20650                } else {
20651                    result = size;
20652                }
20653                break;
20654            case MeasureSpec.EXACTLY:
20655                result = specSize;
20656                break;
20657            case MeasureSpec.UNSPECIFIED:
20658            default:
20659                result = size;
20660        }
20661        return result | (childMeasuredState & MEASURED_STATE_MASK);
20662    }
20663
20664    /**
20665     * Utility to return a default size. Uses the supplied size if the
20666     * MeasureSpec imposed no constraints. Will get larger if allowed
20667     * by the MeasureSpec.
20668     *
20669     * @param size Default size for this view
20670     * @param measureSpec Constraints imposed by the parent
20671     * @return The size this view should be.
20672     */
20673    public static int getDefaultSize(int size, int measureSpec) {
20674        int result = size;
20675        int specMode = MeasureSpec.getMode(measureSpec);
20676        int specSize = MeasureSpec.getSize(measureSpec);
20677
20678        switch (specMode) {
20679        case MeasureSpec.UNSPECIFIED:
20680            result = size;
20681            break;
20682        case MeasureSpec.AT_MOST:
20683        case MeasureSpec.EXACTLY:
20684            result = specSize;
20685            break;
20686        }
20687        return result;
20688    }
20689
20690    /**
20691     * Returns the suggested minimum height that the view should use. This
20692     * returns the maximum of the view's minimum height
20693     * and the background's minimum height
20694     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
20695     * <p>
20696     * When being used in {@link #onMeasure(int, int)}, the caller should still
20697     * ensure the returned height is within the requirements of the parent.
20698     *
20699     * @return The suggested minimum height of the view.
20700     */
20701    protected int getSuggestedMinimumHeight() {
20702        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
20703
20704    }
20705
20706    /**
20707     * Returns the suggested minimum width that the view should use. This
20708     * returns the maximum of the view's minimum width
20709     * and the background's minimum width
20710     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
20711     * <p>
20712     * When being used in {@link #onMeasure(int, int)}, the caller should still
20713     * ensure the returned width is within the requirements of the parent.
20714     *
20715     * @return The suggested minimum width of the view.
20716     */
20717    protected int getSuggestedMinimumWidth() {
20718        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
20719    }
20720
20721    /**
20722     * Returns the minimum height of the view.
20723     *
20724     * @return the minimum height the view will try to be, in pixels
20725     *
20726     * @see #setMinimumHeight(int)
20727     *
20728     * @attr ref android.R.styleable#View_minHeight
20729     */
20730    public int getMinimumHeight() {
20731        return mMinHeight;
20732    }
20733
20734    /**
20735     * Sets the minimum height of the view. It is not guaranteed the view will
20736     * be able to achieve this minimum height (for example, if its parent layout
20737     * constrains it with less available height).
20738     *
20739     * @param minHeight The minimum height the view will try to be, in pixels
20740     *
20741     * @see #getMinimumHeight()
20742     *
20743     * @attr ref android.R.styleable#View_minHeight
20744     */
20745    @RemotableViewMethod
20746    public void setMinimumHeight(int minHeight) {
20747        mMinHeight = minHeight;
20748        requestLayout();
20749    }
20750
20751    /**
20752     * Returns the minimum width of the view.
20753     *
20754     * @return the minimum width the view will try to be, in pixels
20755     *
20756     * @see #setMinimumWidth(int)
20757     *
20758     * @attr ref android.R.styleable#View_minWidth
20759     */
20760    public int getMinimumWidth() {
20761        return mMinWidth;
20762    }
20763
20764    /**
20765     * Sets the minimum width of the view. It is not guaranteed the view will
20766     * be able to achieve this minimum width (for example, if its parent layout
20767     * constrains it with less available width).
20768     *
20769     * @param minWidth The minimum width the view will try to be, in pixels
20770     *
20771     * @see #getMinimumWidth()
20772     *
20773     * @attr ref android.R.styleable#View_minWidth
20774     */
20775    public void setMinimumWidth(int minWidth) {
20776        mMinWidth = minWidth;
20777        requestLayout();
20778
20779    }
20780
20781    /**
20782     * Get the animation currently associated with this view.
20783     *
20784     * @return The animation that is currently playing or
20785     *         scheduled to play for this view.
20786     */
20787    public Animation getAnimation() {
20788        return mCurrentAnimation;
20789    }
20790
20791    /**
20792     * Start the specified animation now.
20793     *
20794     * @param animation the animation to start now
20795     */
20796    public void startAnimation(Animation animation) {
20797        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20798        setAnimation(animation);
20799        invalidateParentCaches();
20800        invalidate(true);
20801    }
20802
20803    /**
20804     * Cancels any animations for this view.
20805     */
20806    public void clearAnimation() {
20807        if (mCurrentAnimation != null) {
20808            mCurrentAnimation.detach();
20809        }
20810        mCurrentAnimation = null;
20811        invalidateParentIfNeeded();
20812    }
20813
20814    /**
20815     * Sets the next animation to play for this view.
20816     * If you want the animation to play immediately, use
20817     * {@link #startAnimation(android.view.animation.Animation)} instead.
20818     * This method provides allows fine-grained
20819     * control over the start time and invalidation, but you
20820     * must make sure that 1) the animation has a start time set, and
20821     * 2) the view's parent (which controls animations on its children)
20822     * will be invalidated when the animation is supposed to
20823     * start.
20824     *
20825     * @param animation The next animation, or null.
20826     */
20827    public void setAnimation(Animation animation) {
20828        mCurrentAnimation = animation;
20829
20830        if (animation != null) {
20831            // If the screen is off assume the animation start time is now instead of
20832            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20833            // would cause the animation to start when the screen turns back on
20834            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20835                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20836                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20837            }
20838            animation.reset();
20839        }
20840    }
20841
20842    /**
20843     * Invoked by a parent ViewGroup to notify the start of the animation
20844     * currently associated with this view. If you override this method,
20845     * always call super.onAnimationStart();
20846     *
20847     * @see #setAnimation(android.view.animation.Animation)
20848     * @see #getAnimation()
20849     */
20850    @CallSuper
20851    protected void onAnimationStart() {
20852        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20853    }
20854
20855    /**
20856     * Invoked by a parent ViewGroup to notify the end of the animation
20857     * currently associated with this view. If you override this method,
20858     * always call super.onAnimationEnd();
20859     *
20860     * @see #setAnimation(android.view.animation.Animation)
20861     * @see #getAnimation()
20862     */
20863    @CallSuper
20864    protected void onAnimationEnd() {
20865        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20866    }
20867
20868    /**
20869     * Invoked if there is a Transform that involves alpha. Subclass that can
20870     * draw themselves with the specified alpha should return true, and then
20871     * respect that alpha when their onDraw() is called. If this returns false
20872     * then the view may be redirected to draw into an offscreen buffer to
20873     * fulfill the request, which will look fine, but may be slower than if the
20874     * subclass handles it internally. The default implementation returns false.
20875     *
20876     * @param alpha The alpha (0..255) to apply to the view's drawing
20877     * @return true if the view can draw with the specified alpha.
20878     */
20879    protected boolean onSetAlpha(int alpha) {
20880        return false;
20881    }
20882
20883    /**
20884     * This is used by the RootView to perform an optimization when
20885     * the view hierarchy contains one or several SurfaceView.
20886     * SurfaceView is always considered transparent, but its children are not,
20887     * therefore all View objects remove themselves from the global transparent
20888     * region (passed as a parameter to this function).
20889     *
20890     * @param region The transparent region for this ViewAncestor (window).
20891     *
20892     * @return Returns true if the effective visibility of the view at this
20893     * point is opaque, regardless of the transparent region; returns false
20894     * if it is possible for underlying windows to be seen behind the view.
20895     *
20896     * {@hide}
20897     */
20898    public boolean gatherTransparentRegion(Region region) {
20899        final AttachInfo attachInfo = mAttachInfo;
20900        if (region != null && attachInfo != null) {
20901            final int pflags = mPrivateFlags;
20902            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20903                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20904                // remove it from the transparent region.
20905                final int[] location = attachInfo.mTransparentLocation;
20906                getLocationInWindow(location);
20907                // When a view has Z value, then it will be better to leave some area below the view
20908                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
20909                // the bottom part needs more offset than the left, top and right parts due to the
20910                // spot light effects.
20911                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
20912                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
20913                        location[0] + mRight - mLeft + shadowOffset,
20914                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
20915            } else {
20916                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20917                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20918                    // the background drawable's non-transparent parts from this transparent region.
20919                    applyDrawableToTransparentRegion(mBackground, region);
20920                }
20921                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20922                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20923                    // Similarly, we remove the foreground drawable's non-transparent parts.
20924                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20925                }
20926            }
20927        }
20928        return true;
20929    }
20930
20931    /**
20932     * Play a sound effect for this view.
20933     *
20934     * <p>The framework will play sound effects for some built in actions, such as
20935     * clicking, but you may wish to play these effects in your widget,
20936     * for instance, for internal navigation.
20937     *
20938     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20939     * {@link #isSoundEffectsEnabled()} is true.
20940     *
20941     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20942     */
20943    public void playSoundEffect(int soundConstant) {
20944        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20945            return;
20946        }
20947        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20948    }
20949
20950    /**
20951     * BZZZTT!!1!
20952     *
20953     * <p>Provide haptic feedback to the user for this view.
20954     *
20955     * <p>The framework will provide haptic feedback for some built in actions,
20956     * such as long presses, but you may wish to provide feedback for your
20957     * own widget.
20958     *
20959     * <p>The feedback will only be performed if
20960     * {@link #isHapticFeedbackEnabled()} is true.
20961     *
20962     * @param feedbackConstant One of the constants defined in
20963     * {@link HapticFeedbackConstants}
20964     */
20965    public boolean performHapticFeedback(int feedbackConstant) {
20966        return performHapticFeedback(feedbackConstant, 0);
20967    }
20968
20969    /**
20970     * BZZZTT!!1!
20971     *
20972     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20973     *
20974     * @param feedbackConstant One of the constants defined in
20975     * {@link HapticFeedbackConstants}
20976     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20977     */
20978    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20979        if (mAttachInfo == null) {
20980            return false;
20981        }
20982        //noinspection SimplifiableIfStatement
20983        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20984                && !isHapticFeedbackEnabled()) {
20985            return false;
20986        }
20987        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20988                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20989    }
20990
20991    /**
20992     * Request that the visibility of the status bar or other screen/window
20993     * decorations be changed.
20994     *
20995     * <p>This method is used to put the over device UI into temporary modes
20996     * where the user's attention is focused more on the application content,
20997     * by dimming or hiding surrounding system affordances.  This is typically
20998     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20999     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
21000     * to be placed behind the action bar (and with these flags other system
21001     * affordances) so that smooth transitions between hiding and showing them
21002     * can be done.
21003     *
21004     * <p>Two representative examples of the use of system UI visibility is
21005     * implementing a content browsing application (like a magazine reader)
21006     * and a video playing application.
21007     *
21008     * <p>The first code shows a typical implementation of a View in a content
21009     * browsing application.  In this implementation, the application goes
21010     * into a content-oriented mode by hiding the status bar and action bar,
21011     * and putting the navigation elements into lights out mode.  The user can
21012     * then interact with content while in this mode.  Such an application should
21013     * provide an easy way for the user to toggle out of the mode (such as to
21014     * check information in the status bar or access notifications).  In the
21015     * implementation here, this is done simply by tapping on the content.
21016     *
21017     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
21018     *      content}
21019     *
21020     * <p>This second code sample shows a typical implementation of a View
21021     * in a video playing application.  In this situation, while the video is
21022     * playing the application would like to go into a complete full-screen mode,
21023     * to use as much of the display as possible for the video.  When in this state
21024     * the user can not interact with the application; the system intercepts
21025     * touching on the screen to pop the UI out of full screen mode.  See
21026     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
21027     *
21028     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
21029     *      content}
21030     *
21031     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21032     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21033     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21034     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21035     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21036     */
21037    public void setSystemUiVisibility(int visibility) {
21038        if (visibility != mSystemUiVisibility) {
21039            mSystemUiVisibility = visibility;
21040            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21041                mParent.recomputeViewAttributes(this);
21042            }
21043        }
21044    }
21045
21046    /**
21047     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
21048     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21049     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21050     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21051     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21052     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21053     */
21054    public int getSystemUiVisibility() {
21055        return mSystemUiVisibility;
21056    }
21057
21058    /**
21059     * Returns the current system UI visibility that is currently set for
21060     * the entire window.  This is the combination of the
21061     * {@link #setSystemUiVisibility(int)} values supplied by all of the
21062     * views in the window.
21063     */
21064    public int getWindowSystemUiVisibility() {
21065        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
21066    }
21067
21068    /**
21069     * Override to find out when the window's requested system UI visibility
21070     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
21071     * This is different from the callbacks received through
21072     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
21073     * in that this is only telling you about the local request of the window,
21074     * not the actual values applied by the system.
21075     */
21076    public void onWindowSystemUiVisibilityChanged(int visible) {
21077    }
21078
21079    /**
21080     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
21081     * the view hierarchy.
21082     */
21083    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
21084        onWindowSystemUiVisibilityChanged(visible);
21085    }
21086
21087    /**
21088     * Set a listener to receive callbacks when the visibility of the system bar changes.
21089     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
21090     */
21091    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
21092        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
21093        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21094            mParent.recomputeViewAttributes(this);
21095        }
21096    }
21097
21098    /**
21099     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
21100     * the view hierarchy.
21101     */
21102    public void dispatchSystemUiVisibilityChanged(int visibility) {
21103        ListenerInfo li = mListenerInfo;
21104        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
21105            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
21106                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
21107        }
21108    }
21109
21110    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
21111        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
21112        if (val != mSystemUiVisibility) {
21113            setSystemUiVisibility(val);
21114            return true;
21115        }
21116        return false;
21117    }
21118
21119    /** @hide */
21120    public void setDisabledSystemUiVisibility(int flags) {
21121        if (mAttachInfo != null) {
21122            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
21123                mAttachInfo.mDisabledSystemUiVisibility = flags;
21124                if (mParent != null) {
21125                    mParent.recomputeViewAttributes(this);
21126                }
21127            }
21128        }
21129    }
21130
21131    /**
21132     * Creates an image that the system displays during the drag and drop
21133     * operation. This is called a &quot;drag shadow&quot;. The default implementation
21134     * for a DragShadowBuilder based on a View returns an image that has exactly the same
21135     * appearance as the given View. The default also positions the center of the drag shadow
21136     * directly under the touch point. If no View is provided (the constructor with no parameters
21137     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
21138     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
21139     * default is an invisible drag shadow.
21140     * <p>
21141     * You are not required to use the View you provide to the constructor as the basis of the
21142     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
21143     * anything you want as the drag shadow.
21144     * </p>
21145     * <p>
21146     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
21147     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
21148     *  size and position of the drag shadow. It uses this data to construct a
21149     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
21150     *  so that your application can draw the shadow image in the Canvas.
21151     * </p>
21152     *
21153     * <div class="special reference">
21154     * <h3>Developer Guides</h3>
21155     * <p>For a guide to implementing drag and drop features, read the
21156     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
21157     * </div>
21158     */
21159    public static class DragShadowBuilder {
21160        private final WeakReference<View> mView;
21161
21162        /**
21163         * Constructs a shadow image builder based on a View. By default, the resulting drag
21164         * shadow will have the same appearance and dimensions as the View, with the touch point
21165         * over the center of the View.
21166         * @param view A View. Any View in scope can be used.
21167         */
21168        public DragShadowBuilder(View view) {
21169            mView = new WeakReference<View>(view);
21170        }
21171
21172        /**
21173         * Construct a shadow builder object with no associated View.  This
21174         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
21175         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
21176         * to supply the drag shadow's dimensions and appearance without
21177         * reference to any View object. If they are not overridden, then the result is an
21178         * invisible drag shadow.
21179         */
21180        public DragShadowBuilder() {
21181            mView = new WeakReference<View>(null);
21182        }
21183
21184        /**
21185         * Returns the View object that had been passed to the
21186         * {@link #View.DragShadowBuilder(View)}
21187         * constructor.  If that View parameter was {@code null} or if the
21188         * {@link #View.DragShadowBuilder()}
21189         * constructor was used to instantiate the builder object, this method will return
21190         * null.
21191         *
21192         * @return The View object associate with this builder object.
21193         */
21194        @SuppressWarnings({"JavadocReference"})
21195        final public View getView() {
21196            return mView.get();
21197        }
21198
21199        /**
21200         * Provides the metrics for the shadow image. These include the dimensions of
21201         * the shadow image, and the point within that shadow that should
21202         * be centered under the touch location while dragging.
21203         * <p>
21204         * The default implementation sets the dimensions of the shadow to be the
21205         * same as the dimensions of the View itself and centers the shadow under
21206         * the touch point.
21207         * </p>
21208         *
21209         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
21210         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
21211         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
21212         * image.
21213         *
21214         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
21215         * shadow image that should be underneath the touch point during the drag and drop
21216         * operation. Your application must set {@link android.graphics.Point#x} to the
21217         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
21218         */
21219        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
21220            final View view = mView.get();
21221            if (view != null) {
21222                outShadowSize.set(view.getWidth(), view.getHeight());
21223                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
21224            } else {
21225                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
21226            }
21227        }
21228
21229        /**
21230         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
21231         * based on the dimensions it received from the
21232         * {@link #onProvideShadowMetrics(Point, Point)} callback.
21233         *
21234         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
21235         */
21236        public void onDrawShadow(Canvas canvas) {
21237            final View view = mView.get();
21238            if (view != null) {
21239                view.draw(canvas);
21240            } else {
21241                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
21242            }
21243        }
21244    }
21245
21246    /**
21247     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
21248     * startDragAndDrop()} for newer platform versions.
21249     */
21250    @Deprecated
21251    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
21252                                   Object myLocalState, int flags) {
21253        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
21254    }
21255
21256    /**
21257     * Starts a drag and drop operation. When your application calls this method, it passes a
21258     * {@link android.view.View.DragShadowBuilder} object to the system. The
21259     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
21260     * to get metrics for the drag shadow, and then calls the object's
21261     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
21262     * <p>
21263     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
21264     *  drag events to all the View objects in your application that are currently visible. It does
21265     *  this either by calling the View object's drag listener (an implementation of
21266     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
21267     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
21268     *  Both are passed a {@link android.view.DragEvent} object that has a
21269     *  {@link android.view.DragEvent#getAction()} value of
21270     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
21271     * </p>
21272     * <p>
21273     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
21274     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
21275     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
21276     * to the View the user selected for dragging.
21277     * </p>
21278     * @param data A {@link android.content.ClipData} object pointing to the data to be
21279     * transferred by the drag and drop operation.
21280     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21281     * drag shadow.
21282     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
21283     * drop operation. When dispatching drag events to views in the same activity this object
21284     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
21285     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
21286     * will return null).
21287     * <p>
21288     * myLocalState is a lightweight mechanism for the sending information from the dragged View
21289     * to the target Views. For example, it can contain flags that differentiate between a
21290     * a copy operation and a move operation.
21291     * </p>
21292     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
21293     * flags, or any combination of the following:
21294     *     <ul>
21295     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
21296     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
21297     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
21298     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
21299     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
21300     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
21301     *     </ul>
21302     * @return {@code true} if the method completes successfully, or
21303     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
21304     * do a drag, and so no drag operation is in progress.
21305     */
21306    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
21307            Object myLocalState, int flags) {
21308        if (ViewDebug.DEBUG_DRAG) {
21309            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
21310        }
21311        if (mAttachInfo == null) {
21312            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
21313            return false;
21314        }
21315
21316        if (data != null) {
21317            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
21318        }
21319
21320        boolean okay = false;
21321
21322        Point shadowSize = new Point();
21323        Point shadowTouchPoint = new Point();
21324        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
21325
21326        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
21327                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
21328            throw new IllegalStateException("Drag shadow dimensions must not be negative");
21329        }
21330
21331        if (ViewDebug.DEBUG_DRAG) {
21332            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
21333                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
21334        }
21335        if (mAttachInfo.mDragSurface != null) {
21336            mAttachInfo.mDragSurface.release();
21337        }
21338        mAttachInfo.mDragSurface = new Surface();
21339        try {
21340            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
21341                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
21342            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
21343                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
21344            if (mAttachInfo.mDragToken != null) {
21345                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21346                try {
21347                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21348                    shadowBuilder.onDrawShadow(canvas);
21349                } finally {
21350                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21351                }
21352
21353                final ViewRootImpl root = getViewRootImpl();
21354
21355                // Cache the local state object for delivery with DragEvents
21356                root.setLocalDragState(myLocalState);
21357
21358                // repurpose 'shadowSize' for the last touch point
21359                root.getLastTouchPoint(shadowSize);
21360
21361                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
21362                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
21363                        shadowTouchPoint.x, shadowTouchPoint.y, data);
21364                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
21365            }
21366        } catch (Exception e) {
21367            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
21368            mAttachInfo.mDragSurface.destroy();
21369            mAttachInfo.mDragSurface = null;
21370        }
21371
21372        return okay;
21373    }
21374
21375    /**
21376     * Cancels an ongoing drag and drop operation.
21377     * <p>
21378     * A {@link android.view.DragEvent} object with
21379     * {@link android.view.DragEvent#getAction()} value of
21380     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
21381     * {@link android.view.DragEvent#getResult()} value of {@code false}
21382     * will be sent to every
21383     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
21384     * even if they are not currently visible.
21385     * </p>
21386     * <p>
21387     * This method can be called on any View in the same window as the View on which
21388     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
21389     * was called.
21390     * </p>
21391     */
21392    public final void cancelDragAndDrop() {
21393        if (ViewDebug.DEBUG_DRAG) {
21394            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
21395        }
21396        if (mAttachInfo == null) {
21397            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
21398            return;
21399        }
21400        if (mAttachInfo.mDragToken != null) {
21401            try {
21402                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
21403            } catch (Exception e) {
21404                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
21405            }
21406            mAttachInfo.mDragToken = null;
21407        } else {
21408            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
21409        }
21410    }
21411
21412    /**
21413     * Updates the drag shadow for the ongoing drag and drop operation.
21414     *
21415     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21416     * new drag shadow.
21417     */
21418    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
21419        if (ViewDebug.DEBUG_DRAG) {
21420            Log.d(VIEW_LOG_TAG, "updateDragShadow");
21421        }
21422        if (mAttachInfo == null) {
21423            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
21424            return;
21425        }
21426        if (mAttachInfo.mDragToken != null) {
21427            try {
21428                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21429                try {
21430                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21431                    shadowBuilder.onDrawShadow(canvas);
21432                } finally {
21433                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21434                }
21435            } catch (Exception e) {
21436                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
21437            }
21438        } else {
21439            Log.e(VIEW_LOG_TAG, "No active drag");
21440        }
21441    }
21442
21443    /**
21444     * Starts a move from {startX, startY}, the amount of the movement will be the offset
21445     * between {startX, startY} and the new cursor positon.
21446     * @param startX horizontal coordinate where the move started.
21447     * @param startY vertical coordinate where the move started.
21448     * @return whether moving was started successfully.
21449     * @hide
21450     */
21451    public final boolean startMovingTask(float startX, float startY) {
21452        if (ViewDebug.DEBUG_POSITIONING) {
21453            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
21454        }
21455        try {
21456            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
21457        } catch (RemoteException e) {
21458            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
21459        }
21460        return false;
21461    }
21462
21463    /**
21464     * Handles drag events sent by the system following a call to
21465     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
21466     * startDragAndDrop()}.
21467     *<p>
21468     * When the system calls this method, it passes a
21469     * {@link android.view.DragEvent} object. A call to
21470     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
21471     * in DragEvent. The method uses these to determine what is happening in the drag and drop
21472     * operation.
21473     * @param event The {@link android.view.DragEvent} sent by the system.
21474     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
21475     * in DragEvent, indicating the type of drag event represented by this object.
21476     * @return {@code true} if the method was successful, otherwise {@code false}.
21477     * <p>
21478     *  The method should return {@code true} in response to an action type of
21479     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
21480     *  operation.
21481     * </p>
21482     * <p>
21483     *  The method should also return {@code true} in response to an action type of
21484     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
21485     *  {@code false} if it didn't.
21486     * </p>
21487     * <p>
21488     *  For all other events, the return value is ignored.
21489     * </p>
21490     */
21491    public boolean onDragEvent(DragEvent event) {
21492        return false;
21493    }
21494
21495    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
21496    boolean dispatchDragEnterExitInPreN(DragEvent event) {
21497        return callDragEventHandler(event);
21498    }
21499
21500    /**
21501     * Detects if this View is enabled and has a drag event listener.
21502     * If both are true, then it calls the drag event listener with the
21503     * {@link android.view.DragEvent} it received. If the drag event listener returns
21504     * {@code true}, then dispatchDragEvent() returns {@code true}.
21505     * <p>
21506     * For all other cases, the method calls the
21507     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
21508     * method and returns its result.
21509     * </p>
21510     * <p>
21511     * This ensures that a drag event is always consumed, even if the View does not have a drag
21512     * event listener. However, if the View has a listener and the listener returns true, then
21513     * onDragEvent() is not called.
21514     * </p>
21515     */
21516    public boolean dispatchDragEvent(DragEvent event) {
21517        event.mEventHandlerWasCalled = true;
21518        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
21519            event.mAction == DragEvent.ACTION_DROP) {
21520            // About to deliver an event with coordinates to this view. Notify that now this view
21521            // has drag focus. This will send exit/enter events as needed.
21522            getViewRootImpl().setDragFocus(this, event);
21523        }
21524        return callDragEventHandler(event);
21525    }
21526
21527    final boolean callDragEventHandler(DragEvent event) {
21528        final boolean result;
21529
21530        ListenerInfo li = mListenerInfo;
21531        //noinspection SimplifiableIfStatement
21532        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
21533                && li.mOnDragListener.onDrag(this, event)) {
21534            result = true;
21535        } else {
21536            result = onDragEvent(event);
21537        }
21538
21539        switch (event.mAction) {
21540            case DragEvent.ACTION_DRAG_ENTERED: {
21541                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
21542                refreshDrawableState();
21543            } break;
21544            case DragEvent.ACTION_DRAG_EXITED: {
21545                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
21546                refreshDrawableState();
21547            } break;
21548            case DragEvent.ACTION_DRAG_ENDED: {
21549                mPrivateFlags2 &= ~View.DRAG_MASK;
21550                refreshDrawableState();
21551            } break;
21552        }
21553
21554        return result;
21555    }
21556
21557    boolean canAcceptDrag() {
21558        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
21559    }
21560
21561    /**
21562     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
21563     * it is ever exposed at all.
21564     * @hide
21565     */
21566    public void onCloseSystemDialogs(String reason) {
21567    }
21568
21569    /**
21570     * Given a Drawable whose bounds have been set to draw into this view,
21571     * update a Region being computed for
21572     * {@link #gatherTransparentRegion(android.graphics.Region)} so
21573     * that any non-transparent parts of the Drawable are removed from the
21574     * given transparent region.
21575     *
21576     * @param dr The Drawable whose transparency is to be applied to the region.
21577     * @param region A Region holding the current transparency information,
21578     * where any parts of the region that are set are considered to be
21579     * transparent.  On return, this region will be modified to have the
21580     * transparency information reduced by the corresponding parts of the
21581     * Drawable that are not transparent.
21582     * {@hide}
21583     */
21584    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
21585        if (DBG) {
21586            Log.i("View", "Getting transparent region for: " + this);
21587        }
21588        final Region r = dr.getTransparentRegion();
21589        final Rect db = dr.getBounds();
21590        final AttachInfo attachInfo = mAttachInfo;
21591        if (r != null && attachInfo != null) {
21592            final int w = getRight()-getLeft();
21593            final int h = getBottom()-getTop();
21594            if (db.left > 0) {
21595                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
21596                r.op(0, 0, db.left, h, Region.Op.UNION);
21597            }
21598            if (db.right < w) {
21599                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
21600                r.op(db.right, 0, w, h, Region.Op.UNION);
21601            }
21602            if (db.top > 0) {
21603                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
21604                r.op(0, 0, w, db.top, Region.Op.UNION);
21605            }
21606            if (db.bottom < h) {
21607                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
21608                r.op(0, db.bottom, w, h, Region.Op.UNION);
21609            }
21610            final int[] location = attachInfo.mTransparentLocation;
21611            getLocationInWindow(location);
21612            r.translate(location[0], location[1]);
21613            region.op(r, Region.Op.INTERSECT);
21614        } else {
21615            region.op(db, Region.Op.DIFFERENCE);
21616        }
21617    }
21618
21619    private void checkForLongClick(int delayOffset, float x, float y) {
21620        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
21621            mHasPerformedLongPress = false;
21622
21623            if (mPendingCheckForLongPress == null) {
21624                mPendingCheckForLongPress = new CheckForLongPress();
21625            }
21626            mPendingCheckForLongPress.setAnchor(x, y);
21627            mPendingCheckForLongPress.rememberWindowAttachCount();
21628            mPendingCheckForLongPress.rememberPressedState();
21629            postDelayed(mPendingCheckForLongPress,
21630                    ViewConfiguration.getLongPressTimeout() - delayOffset);
21631        }
21632    }
21633
21634    /**
21635     * Inflate a view from an XML resource.  This convenience method wraps the {@link
21636     * LayoutInflater} class, which provides a full range of options for view inflation.
21637     *
21638     * @param context The Context object for your activity or application.
21639     * @param resource The resource ID to inflate
21640     * @param root A view group that will be the parent.  Used to properly inflate the
21641     * layout_* parameters.
21642     * @see LayoutInflater
21643     */
21644    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
21645        LayoutInflater factory = LayoutInflater.from(context);
21646        return factory.inflate(resource, root);
21647    }
21648
21649    /**
21650     * Scroll the view with standard behavior for scrolling beyond the normal
21651     * content boundaries. Views that call this method should override
21652     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
21653     * results of an over-scroll operation.
21654     *
21655     * Views can use this method to handle any touch or fling-based scrolling.
21656     *
21657     * @param deltaX Change in X in pixels
21658     * @param deltaY Change in Y in pixels
21659     * @param scrollX Current X scroll value in pixels before applying deltaX
21660     * @param scrollY Current Y scroll value in pixels before applying deltaY
21661     * @param scrollRangeX Maximum content scroll range along the X axis
21662     * @param scrollRangeY Maximum content scroll range along the Y axis
21663     * @param maxOverScrollX Number of pixels to overscroll by in either direction
21664     *          along the X axis.
21665     * @param maxOverScrollY Number of pixels to overscroll by in either direction
21666     *          along the Y axis.
21667     * @param isTouchEvent true if this scroll operation is the result of a touch event.
21668     * @return true if scrolling was clamped to an over-scroll boundary along either
21669     *          axis, false otherwise.
21670     */
21671    @SuppressWarnings({"UnusedParameters"})
21672    protected boolean overScrollBy(int deltaX, int deltaY,
21673            int scrollX, int scrollY,
21674            int scrollRangeX, int scrollRangeY,
21675            int maxOverScrollX, int maxOverScrollY,
21676            boolean isTouchEvent) {
21677        final int overScrollMode = mOverScrollMode;
21678        final boolean canScrollHorizontal =
21679                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21680        final boolean canScrollVertical =
21681                computeVerticalScrollRange() > computeVerticalScrollExtent();
21682        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21683                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21684        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21685                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21686
21687        int newScrollX = scrollX + deltaX;
21688        if (!overScrollHorizontal) {
21689            maxOverScrollX = 0;
21690        }
21691
21692        int newScrollY = scrollY + deltaY;
21693        if (!overScrollVertical) {
21694            maxOverScrollY = 0;
21695        }
21696
21697        // Clamp values if at the limits and record
21698        final int left = -maxOverScrollX;
21699        final int right = maxOverScrollX + scrollRangeX;
21700        final int top = -maxOverScrollY;
21701        final int bottom = maxOverScrollY + scrollRangeY;
21702
21703        boolean clampedX = false;
21704        if (newScrollX > right) {
21705            newScrollX = right;
21706            clampedX = true;
21707        } else if (newScrollX < left) {
21708            newScrollX = left;
21709            clampedX = true;
21710        }
21711
21712        boolean clampedY = false;
21713        if (newScrollY > bottom) {
21714            newScrollY = bottom;
21715            clampedY = true;
21716        } else if (newScrollY < top) {
21717            newScrollY = top;
21718            clampedY = true;
21719        }
21720
21721        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
21722
21723        return clampedX || clampedY;
21724    }
21725
21726    /**
21727     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
21728     * respond to the results of an over-scroll operation.
21729     *
21730     * @param scrollX New X scroll value in pixels
21731     * @param scrollY New Y scroll value in pixels
21732     * @param clampedX True if scrollX was clamped to an over-scroll boundary
21733     * @param clampedY True if scrollY was clamped to an over-scroll boundary
21734     */
21735    protected void onOverScrolled(int scrollX, int scrollY,
21736            boolean clampedX, boolean clampedY) {
21737        // Intentionally empty.
21738    }
21739
21740    /**
21741     * Returns the over-scroll mode for this view. The result will be
21742     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21743     * (allow over-scrolling only if the view content is larger than the container),
21744     * or {@link #OVER_SCROLL_NEVER}.
21745     *
21746     * @return This view's over-scroll mode.
21747     */
21748    public int getOverScrollMode() {
21749        return mOverScrollMode;
21750    }
21751
21752    /**
21753     * Set the over-scroll mode for this view. Valid over-scroll modes are
21754     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21755     * (allow over-scrolling only if the view content is larger than the container),
21756     * or {@link #OVER_SCROLL_NEVER}.
21757     *
21758     * Setting the over-scroll mode of a view will have an effect only if the
21759     * view is capable of scrolling.
21760     *
21761     * @param overScrollMode The new over-scroll mode for this view.
21762     */
21763    public void setOverScrollMode(int overScrollMode) {
21764        if (overScrollMode != OVER_SCROLL_ALWAYS &&
21765                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
21766                overScrollMode != OVER_SCROLL_NEVER) {
21767            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
21768        }
21769        mOverScrollMode = overScrollMode;
21770    }
21771
21772    /**
21773     * Enable or disable nested scrolling for this view.
21774     *
21775     * <p>If this property is set to true the view will be permitted to initiate nested
21776     * scrolling operations with a compatible parent view in the current hierarchy. If this
21777     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
21778     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
21779     * the nested scroll.</p>
21780     *
21781     * @param enabled true to enable nested scrolling, false to disable
21782     *
21783     * @see #isNestedScrollingEnabled()
21784     */
21785    public void setNestedScrollingEnabled(boolean enabled) {
21786        if (enabled) {
21787            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
21788        } else {
21789            stopNestedScroll();
21790            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
21791        }
21792    }
21793
21794    /**
21795     * Returns true if nested scrolling is enabled for this view.
21796     *
21797     * <p>If nested scrolling is enabled and this View class implementation supports it,
21798     * this view will act as a nested scrolling child view when applicable, forwarding data
21799     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21800     * parent.</p>
21801     *
21802     * @return true if nested scrolling is enabled
21803     *
21804     * @see #setNestedScrollingEnabled(boolean)
21805     */
21806    public boolean isNestedScrollingEnabled() {
21807        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21808                PFLAG3_NESTED_SCROLLING_ENABLED;
21809    }
21810
21811    /**
21812     * Begin a nestable scroll operation along the given axes.
21813     *
21814     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21815     *
21816     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21817     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21818     * In the case of touch scrolling the nested scroll will be terminated automatically in
21819     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21820     * In the event of programmatic scrolling the caller must explicitly call
21821     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21822     *
21823     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21824     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21825     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21826     *
21827     * <p>At each incremental step of the scroll the caller should invoke
21828     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21829     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21830     * parent at least partially consumed the scroll and the caller should adjust the amount it
21831     * scrolls by.</p>
21832     *
21833     * <p>After applying the remainder of the scroll delta the caller should invoke
21834     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21835     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21836     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21837     * </p>
21838     *
21839     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21840     *             {@link #SCROLL_AXIS_VERTICAL}.
21841     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21842     *         the current gesture.
21843     *
21844     * @see #stopNestedScroll()
21845     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21846     * @see #dispatchNestedScroll(int, int, int, int, int[])
21847     */
21848    public boolean startNestedScroll(int axes) {
21849        if (hasNestedScrollingParent()) {
21850            // Already in progress
21851            return true;
21852        }
21853        if (isNestedScrollingEnabled()) {
21854            ViewParent p = getParent();
21855            View child = this;
21856            while (p != null) {
21857                try {
21858                    if (p.onStartNestedScroll(child, this, axes)) {
21859                        mNestedScrollingParent = p;
21860                        p.onNestedScrollAccepted(child, this, axes);
21861                        return true;
21862                    }
21863                } catch (AbstractMethodError e) {
21864                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21865                            "method onStartNestedScroll", e);
21866                    // Allow the search upward to continue
21867                }
21868                if (p instanceof View) {
21869                    child = (View) p;
21870                }
21871                p = p.getParent();
21872            }
21873        }
21874        return false;
21875    }
21876
21877    /**
21878     * Stop a nested scroll in progress.
21879     *
21880     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21881     *
21882     * @see #startNestedScroll(int)
21883     */
21884    public void stopNestedScroll() {
21885        if (mNestedScrollingParent != null) {
21886            mNestedScrollingParent.onStopNestedScroll(this);
21887            mNestedScrollingParent = null;
21888        }
21889    }
21890
21891    /**
21892     * Returns true if this view has a nested scrolling parent.
21893     *
21894     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21895     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21896     *
21897     * @return whether this view has a nested scrolling parent
21898     */
21899    public boolean hasNestedScrollingParent() {
21900        return mNestedScrollingParent != null;
21901    }
21902
21903    /**
21904     * Dispatch one step of a nested scroll in progress.
21905     *
21906     * <p>Implementations of views that support nested scrolling should call this to report
21907     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21908     * is not currently in progress or nested scrolling is not
21909     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21910     *
21911     * <p>Compatible View implementations should also call
21912     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21913     * consuming a component of the scroll event themselves.</p>
21914     *
21915     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21916     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21917     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21918     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21919     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21920     *                       in local view coordinates of this view from before this operation
21921     *                       to after it completes. View implementations may use this to adjust
21922     *                       expected input coordinate tracking.
21923     * @return true if the event was dispatched, false if it could not be dispatched.
21924     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21925     */
21926    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21927            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21928        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21929            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21930                int startX = 0;
21931                int startY = 0;
21932                if (offsetInWindow != null) {
21933                    getLocationInWindow(offsetInWindow);
21934                    startX = offsetInWindow[0];
21935                    startY = offsetInWindow[1];
21936                }
21937
21938                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21939                        dxUnconsumed, dyUnconsumed);
21940
21941                if (offsetInWindow != null) {
21942                    getLocationInWindow(offsetInWindow);
21943                    offsetInWindow[0] -= startX;
21944                    offsetInWindow[1] -= startY;
21945                }
21946                return true;
21947            } else if (offsetInWindow != null) {
21948                // No motion, no dispatch. Keep offsetInWindow up to date.
21949                offsetInWindow[0] = 0;
21950                offsetInWindow[1] = 0;
21951            }
21952        }
21953        return false;
21954    }
21955
21956    /**
21957     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21958     *
21959     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21960     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21961     * scrolling operation to consume some or all of the scroll operation before the child view
21962     * consumes it.</p>
21963     *
21964     * @param dx Horizontal scroll distance in pixels
21965     * @param dy Vertical scroll distance in pixels
21966     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21967     *                 and consumed[1] the consumed dy.
21968     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21969     *                       in local view coordinates of this view from before this operation
21970     *                       to after it completes. View implementations may use this to adjust
21971     *                       expected input coordinate tracking.
21972     * @return true if the parent consumed some or all of the scroll delta
21973     * @see #dispatchNestedScroll(int, int, int, int, int[])
21974     */
21975    public boolean dispatchNestedPreScroll(int dx, int dy,
21976            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21977        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21978            if (dx != 0 || dy != 0) {
21979                int startX = 0;
21980                int startY = 0;
21981                if (offsetInWindow != null) {
21982                    getLocationInWindow(offsetInWindow);
21983                    startX = offsetInWindow[0];
21984                    startY = offsetInWindow[1];
21985                }
21986
21987                if (consumed == null) {
21988                    if (mTempNestedScrollConsumed == null) {
21989                        mTempNestedScrollConsumed = new int[2];
21990                    }
21991                    consumed = mTempNestedScrollConsumed;
21992                }
21993                consumed[0] = 0;
21994                consumed[1] = 0;
21995                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21996
21997                if (offsetInWindow != null) {
21998                    getLocationInWindow(offsetInWindow);
21999                    offsetInWindow[0] -= startX;
22000                    offsetInWindow[1] -= startY;
22001                }
22002                return consumed[0] != 0 || consumed[1] != 0;
22003            } else if (offsetInWindow != null) {
22004                offsetInWindow[0] = 0;
22005                offsetInWindow[1] = 0;
22006            }
22007        }
22008        return false;
22009    }
22010
22011    /**
22012     * Dispatch a fling to a nested scrolling parent.
22013     *
22014     * <p>This method should be used to indicate that a nested scrolling child has detected
22015     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
22016     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
22017     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
22018     * along a scrollable axis.</p>
22019     *
22020     * <p>If a nested scrolling child view would normally fling but it is at the edge of
22021     * its own content, it can use this method to delegate the fling to its nested scrolling
22022     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
22023     *
22024     * @param velocityX Horizontal fling velocity in pixels per second
22025     * @param velocityY Vertical fling velocity in pixels per second
22026     * @param consumed true if the child consumed the fling, false otherwise
22027     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
22028     */
22029    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
22030        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22031            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
22032        }
22033        return false;
22034    }
22035
22036    /**
22037     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
22038     *
22039     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
22040     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
22041     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
22042     * before the child view consumes it. If this method returns <code>true</code>, a nested
22043     * parent view consumed the fling and this view should not scroll as a result.</p>
22044     *
22045     * <p>For a better user experience, only one view in a nested scrolling chain should consume
22046     * the fling at a time. If a parent view consumed the fling this method will return false.
22047     * Custom view implementations should account for this in two ways:</p>
22048     *
22049     * <ul>
22050     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
22051     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
22052     *     position regardless.</li>
22053     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
22054     *     even to settle back to a valid idle position.</li>
22055     * </ul>
22056     *
22057     * <p>Views should also not offer fling velocities to nested parent views along an axis
22058     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
22059     * should not offer a horizontal fling velocity to its parents since scrolling along that
22060     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
22061     *
22062     * @param velocityX Horizontal fling velocity in pixels per second
22063     * @param velocityY Vertical fling velocity in pixels per second
22064     * @return true if a nested scrolling parent consumed the fling
22065     */
22066    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
22067        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22068            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
22069        }
22070        return false;
22071    }
22072
22073    /**
22074     * Gets a scale factor that determines the distance the view should scroll
22075     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
22076     * @return The vertical scroll scale factor.
22077     * @hide
22078     */
22079    protected float getVerticalScrollFactor() {
22080        if (mVerticalScrollFactor == 0) {
22081            TypedValue outValue = new TypedValue();
22082            if (!mContext.getTheme().resolveAttribute(
22083                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
22084                throw new IllegalStateException(
22085                        "Expected theme to define listPreferredItemHeight.");
22086            }
22087            mVerticalScrollFactor = outValue.getDimension(
22088                    mContext.getResources().getDisplayMetrics());
22089        }
22090        return mVerticalScrollFactor;
22091    }
22092
22093    /**
22094     * Gets a scale factor that determines the distance the view should scroll
22095     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
22096     * @return The horizontal scroll scale factor.
22097     * @hide
22098     */
22099    protected float getHorizontalScrollFactor() {
22100        // TODO: Should use something else.
22101        return getVerticalScrollFactor();
22102    }
22103
22104    /**
22105     * Return the value specifying the text direction or policy that was set with
22106     * {@link #setTextDirection(int)}.
22107     *
22108     * @return the defined text direction. It can be one of:
22109     *
22110     * {@link #TEXT_DIRECTION_INHERIT},
22111     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22112     * {@link #TEXT_DIRECTION_ANY_RTL},
22113     * {@link #TEXT_DIRECTION_LTR},
22114     * {@link #TEXT_DIRECTION_RTL},
22115     * {@link #TEXT_DIRECTION_LOCALE},
22116     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22117     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22118     *
22119     * @attr ref android.R.styleable#View_textDirection
22120     *
22121     * @hide
22122     */
22123    @ViewDebug.ExportedProperty(category = "text", mapping = {
22124            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22125            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22126            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22127            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22128            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22129            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22130            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22131            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22132    })
22133    public int getRawTextDirection() {
22134        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
22135    }
22136
22137    /**
22138     * Set the text direction.
22139     *
22140     * @param textDirection the direction to set. Should be one of:
22141     *
22142     * {@link #TEXT_DIRECTION_INHERIT},
22143     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22144     * {@link #TEXT_DIRECTION_ANY_RTL},
22145     * {@link #TEXT_DIRECTION_LTR},
22146     * {@link #TEXT_DIRECTION_RTL},
22147     * {@link #TEXT_DIRECTION_LOCALE}
22148     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22149     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
22150     *
22151     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
22152     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
22153     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
22154     *
22155     * @attr ref android.R.styleable#View_textDirection
22156     */
22157    public void setTextDirection(int textDirection) {
22158        if (getRawTextDirection() != textDirection) {
22159            // Reset the current text direction and the resolved one
22160            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
22161            resetResolvedTextDirection();
22162            // Set the new text direction
22163            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
22164            // Do resolution
22165            resolveTextDirection();
22166            // Notify change
22167            onRtlPropertiesChanged(getLayoutDirection());
22168            // Refresh
22169            requestLayout();
22170            invalidate(true);
22171        }
22172    }
22173
22174    /**
22175     * Return the resolved text direction.
22176     *
22177     * @return the resolved text direction. Returns one of:
22178     *
22179     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22180     * {@link #TEXT_DIRECTION_ANY_RTL},
22181     * {@link #TEXT_DIRECTION_LTR},
22182     * {@link #TEXT_DIRECTION_RTL},
22183     * {@link #TEXT_DIRECTION_LOCALE},
22184     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22185     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22186     *
22187     * @attr ref android.R.styleable#View_textDirection
22188     */
22189    @ViewDebug.ExportedProperty(category = "text", mapping = {
22190            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22191            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22192            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22193            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22194            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22195            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22196            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22197            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22198    })
22199    public int getTextDirection() {
22200        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
22201    }
22202
22203    /**
22204     * Resolve the text direction.
22205     *
22206     * @return true if resolution has been done, false otherwise.
22207     *
22208     * @hide
22209     */
22210    public boolean resolveTextDirection() {
22211        // Reset any previous text direction resolution
22212        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22213
22214        if (hasRtlSupport()) {
22215            // Set resolved text direction flag depending on text direction flag
22216            final int textDirection = getRawTextDirection();
22217            switch(textDirection) {
22218                case TEXT_DIRECTION_INHERIT:
22219                    if (!canResolveTextDirection()) {
22220                        // We cannot do the resolution if there is no parent, so use the default one
22221                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22222                        // Resolution will need to happen again later
22223                        return false;
22224                    }
22225
22226                    // Parent has not yet resolved, so we still return the default
22227                    try {
22228                        if (!mParent.isTextDirectionResolved()) {
22229                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22230                            // Resolution will need to happen again later
22231                            return false;
22232                        }
22233                    } catch (AbstractMethodError e) {
22234                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22235                                " does not fully implement ViewParent", e);
22236                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
22237                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22238                        return true;
22239                    }
22240
22241                    // Set current resolved direction to the same value as the parent's one
22242                    int parentResolvedDirection;
22243                    try {
22244                        parentResolvedDirection = mParent.getTextDirection();
22245                    } catch (AbstractMethodError e) {
22246                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22247                                " does not fully implement ViewParent", e);
22248                        parentResolvedDirection = TEXT_DIRECTION_LTR;
22249                    }
22250                    switch (parentResolvedDirection) {
22251                        case TEXT_DIRECTION_FIRST_STRONG:
22252                        case TEXT_DIRECTION_ANY_RTL:
22253                        case TEXT_DIRECTION_LTR:
22254                        case TEXT_DIRECTION_RTL:
22255                        case TEXT_DIRECTION_LOCALE:
22256                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
22257                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
22258                            mPrivateFlags2 |=
22259                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22260                            break;
22261                        default:
22262                            // Default resolved direction is "first strong" heuristic
22263                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22264                    }
22265                    break;
22266                case TEXT_DIRECTION_FIRST_STRONG:
22267                case TEXT_DIRECTION_ANY_RTL:
22268                case TEXT_DIRECTION_LTR:
22269                case TEXT_DIRECTION_RTL:
22270                case TEXT_DIRECTION_LOCALE:
22271                case TEXT_DIRECTION_FIRST_STRONG_LTR:
22272                case TEXT_DIRECTION_FIRST_STRONG_RTL:
22273                    // Resolved direction is the same as text direction
22274                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22275                    break;
22276                default:
22277                    // Default resolved direction is "first strong" heuristic
22278                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22279            }
22280        } else {
22281            // Default resolved direction is "first strong" heuristic
22282            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22283        }
22284
22285        // Set to resolved
22286        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
22287        return true;
22288    }
22289
22290    /**
22291     * Check if text direction resolution can be done.
22292     *
22293     * @return true if text direction resolution can be done otherwise return false.
22294     */
22295    public boolean canResolveTextDirection() {
22296        switch (getRawTextDirection()) {
22297            case TEXT_DIRECTION_INHERIT:
22298                if (mParent != null) {
22299                    try {
22300                        return mParent.canResolveTextDirection();
22301                    } catch (AbstractMethodError e) {
22302                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22303                                " does not fully implement ViewParent", e);
22304                    }
22305                }
22306                return false;
22307
22308            default:
22309                return true;
22310        }
22311    }
22312
22313    /**
22314     * Reset resolved text direction. Text direction will be resolved during a call to
22315     * {@link #onMeasure(int, int)}.
22316     *
22317     * @hide
22318     */
22319    public void resetResolvedTextDirection() {
22320        // Reset any previous text direction resolution
22321        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22322        // Set to default value
22323        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22324    }
22325
22326    /**
22327     * @return true if text direction is inherited.
22328     *
22329     * @hide
22330     */
22331    public boolean isTextDirectionInherited() {
22332        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
22333    }
22334
22335    /**
22336     * @return true if text direction is resolved.
22337     */
22338    public boolean isTextDirectionResolved() {
22339        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
22340    }
22341
22342    /**
22343     * Return the value specifying the text alignment or policy that was set with
22344     * {@link #setTextAlignment(int)}.
22345     *
22346     * @return the defined text alignment. It can be one of:
22347     *
22348     * {@link #TEXT_ALIGNMENT_INHERIT},
22349     * {@link #TEXT_ALIGNMENT_GRAVITY},
22350     * {@link #TEXT_ALIGNMENT_CENTER},
22351     * {@link #TEXT_ALIGNMENT_TEXT_START},
22352     * {@link #TEXT_ALIGNMENT_TEXT_END},
22353     * {@link #TEXT_ALIGNMENT_VIEW_START},
22354     * {@link #TEXT_ALIGNMENT_VIEW_END}
22355     *
22356     * @attr ref android.R.styleable#View_textAlignment
22357     *
22358     * @hide
22359     */
22360    @ViewDebug.ExportedProperty(category = "text", mapping = {
22361            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22362            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22363            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22364            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22365            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22366            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22367            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22368    })
22369    @TextAlignment
22370    public int getRawTextAlignment() {
22371        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
22372    }
22373
22374    /**
22375     * Set the text alignment.
22376     *
22377     * @param textAlignment The text alignment to set. Should be one of
22378     *
22379     * {@link #TEXT_ALIGNMENT_INHERIT},
22380     * {@link #TEXT_ALIGNMENT_GRAVITY},
22381     * {@link #TEXT_ALIGNMENT_CENTER},
22382     * {@link #TEXT_ALIGNMENT_TEXT_START},
22383     * {@link #TEXT_ALIGNMENT_TEXT_END},
22384     * {@link #TEXT_ALIGNMENT_VIEW_START},
22385     * {@link #TEXT_ALIGNMENT_VIEW_END}
22386     *
22387     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
22388     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
22389     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
22390     *
22391     * @attr ref android.R.styleable#View_textAlignment
22392     */
22393    public void setTextAlignment(@TextAlignment int textAlignment) {
22394        if (textAlignment != getRawTextAlignment()) {
22395            // Reset the current and resolved text alignment
22396            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
22397            resetResolvedTextAlignment();
22398            // Set the new text alignment
22399            mPrivateFlags2 |=
22400                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
22401            // Do resolution
22402            resolveTextAlignment();
22403            // Notify change
22404            onRtlPropertiesChanged(getLayoutDirection());
22405            // Refresh
22406            requestLayout();
22407            invalidate(true);
22408        }
22409    }
22410
22411    /**
22412     * Return the resolved text alignment.
22413     *
22414     * @return the resolved text alignment. Returns one of:
22415     *
22416     * {@link #TEXT_ALIGNMENT_GRAVITY},
22417     * {@link #TEXT_ALIGNMENT_CENTER},
22418     * {@link #TEXT_ALIGNMENT_TEXT_START},
22419     * {@link #TEXT_ALIGNMENT_TEXT_END},
22420     * {@link #TEXT_ALIGNMENT_VIEW_START},
22421     * {@link #TEXT_ALIGNMENT_VIEW_END}
22422     *
22423     * @attr ref android.R.styleable#View_textAlignment
22424     */
22425    @ViewDebug.ExportedProperty(category = "text", mapping = {
22426            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22427            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22428            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22429            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22430            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22431            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22432            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22433    })
22434    @TextAlignment
22435    public int getTextAlignment() {
22436        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
22437                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
22438    }
22439
22440    /**
22441     * Resolve the text alignment.
22442     *
22443     * @return true if resolution has been done, false otherwise.
22444     *
22445     * @hide
22446     */
22447    public boolean resolveTextAlignment() {
22448        // Reset any previous text alignment resolution
22449        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22450
22451        if (hasRtlSupport()) {
22452            // Set resolved text alignment flag depending on text alignment flag
22453            final int textAlignment = getRawTextAlignment();
22454            switch (textAlignment) {
22455                case TEXT_ALIGNMENT_INHERIT:
22456                    // Check if we can resolve the text alignment
22457                    if (!canResolveTextAlignment()) {
22458                        // We cannot do the resolution if there is no parent so use the default
22459                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22460                        // Resolution will need to happen again later
22461                        return false;
22462                    }
22463
22464                    // Parent has not yet resolved, so we still return the default
22465                    try {
22466                        if (!mParent.isTextAlignmentResolved()) {
22467                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22468                            // Resolution will need to happen again later
22469                            return false;
22470                        }
22471                    } catch (AbstractMethodError e) {
22472                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22473                                " does not fully implement ViewParent", e);
22474                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
22475                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22476                        return true;
22477                    }
22478
22479                    int parentResolvedTextAlignment;
22480                    try {
22481                        parentResolvedTextAlignment = mParent.getTextAlignment();
22482                    } catch (AbstractMethodError e) {
22483                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22484                                " does not fully implement ViewParent", e);
22485                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
22486                    }
22487                    switch (parentResolvedTextAlignment) {
22488                        case TEXT_ALIGNMENT_GRAVITY:
22489                        case TEXT_ALIGNMENT_TEXT_START:
22490                        case TEXT_ALIGNMENT_TEXT_END:
22491                        case TEXT_ALIGNMENT_CENTER:
22492                        case TEXT_ALIGNMENT_VIEW_START:
22493                        case TEXT_ALIGNMENT_VIEW_END:
22494                            // Resolved text alignment is the same as the parent resolved
22495                            // text alignment
22496                            mPrivateFlags2 |=
22497                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22498                            break;
22499                        default:
22500                            // Use default resolved text alignment
22501                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22502                    }
22503                    break;
22504                case TEXT_ALIGNMENT_GRAVITY:
22505                case TEXT_ALIGNMENT_TEXT_START:
22506                case TEXT_ALIGNMENT_TEXT_END:
22507                case TEXT_ALIGNMENT_CENTER:
22508                case TEXT_ALIGNMENT_VIEW_START:
22509                case TEXT_ALIGNMENT_VIEW_END:
22510                    // Resolved text alignment is the same as text alignment
22511                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22512                    break;
22513                default:
22514                    // Use default resolved text alignment
22515                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22516            }
22517        } else {
22518            // Use default resolved text alignment
22519            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22520        }
22521
22522        // Set the resolved
22523        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22524        return true;
22525    }
22526
22527    /**
22528     * Check if text alignment resolution can be done.
22529     *
22530     * @return true if text alignment resolution can be done otherwise return false.
22531     */
22532    public boolean canResolveTextAlignment() {
22533        switch (getRawTextAlignment()) {
22534            case TEXT_DIRECTION_INHERIT:
22535                if (mParent != null) {
22536                    try {
22537                        return mParent.canResolveTextAlignment();
22538                    } catch (AbstractMethodError e) {
22539                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22540                                " does not fully implement ViewParent", e);
22541                    }
22542                }
22543                return false;
22544
22545            default:
22546                return true;
22547        }
22548    }
22549
22550    /**
22551     * Reset resolved text alignment. Text alignment will be resolved during a call to
22552     * {@link #onMeasure(int, int)}.
22553     *
22554     * @hide
22555     */
22556    public void resetResolvedTextAlignment() {
22557        // Reset any previous text alignment resolution
22558        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22559        // Set to default
22560        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22561    }
22562
22563    /**
22564     * @return true if text alignment is inherited.
22565     *
22566     * @hide
22567     */
22568    public boolean isTextAlignmentInherited() {
22569        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
22570    }
22571
22572    /**
22573     * @return true if text alignment is resolved.
22574     */
22575    public boolean isTextAlignmentResolved() {
22576        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22577    }
22578
22579    /**
22580     * Generate a value suitable for use in {@link #setId(int)}.
22581     * This value will not collide with ID values generated at build time by aapt for R.id.
22582     *
22583     * @return a generated ID value
22584     */
22585    public static int generateViewId() {
22586        for (;;) {
22587            final int result = sNextGeneratedId.get();
22588            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
22589            int newValue = result + 1;
22590            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
22591            if (sNextGeneratedId.compareAndSet(result, newValue)) {
22592                return result;
22593            }
22594        }
22595    }
22596
22597    private static boolean isViewIdGenerated(int id) {
22598        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
22599    }
22600
22601    /**
22602     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
22603     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
22604     *                           a normal View or a ViewGroup with
22605     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
22606     * @hide
22607     */
22608    public void captureTransitioningViews(List<View> transitioningViews) {
22609        if (getVisibility() == View.VISIBLE) {
22610            transitioningViews.add(this);
22611        }
22612    }
22613
22614    /**
22615     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
22616     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
22617     * @hide
22618     */
22619    public void findNamedViews(Map<String, View> namedElements) {
22620        if (getVisibility() == VISIBLE || mGhostView != null) {
22621            String transitionName = getTransitionName();
22622            if (transitionName != null) {
22623                namedElements.put(transitionName, this);
22624            }
22625        }
22626    }
22627
22628    /**
22629     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
22630     * The default implementation does not care the location or event types, but some subclasses
22631     * may use it (such as WebViews).
22632     * @param event The MotionEvent from a mouse
22633     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
22634     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
22635     * @see PointerIcon
22636     */
22637    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
22638        final float x = event.getX(pointerIndex);
22639        final float y = event.getY(pointerIndex);
22640        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
22641            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
22642        }
22643        return mPointerIcon;
22644    }
22645
22646    /**
22647     * Set the pointer icon for the current view.
22648     * Passing {@code null} will restore the pointer icon to its default value.
22649     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
22650     */
22651    public void setPointerIcon(PointerIcon pointerIcon) {
22652        mPointerIcon = pointerIcon;
22653        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
22654            return;
22655        }
22656        try {
22657            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
22658        } catch (RemoteException e) {
22659        }
22660    }
22661
22662    /**
22663     * Gets the pointer icon for the current view.
22664     */
22665    public PointerIcon getPointerIcon() {
22666        return mPointerIcon;
22667    }
22668
22669    //
22670    // Properties
22671    //
22672    /**
22673     * A Property wrapper around the <code>alpha</code> functionality handled by the
22674     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
22675     */
22676    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
22677        @Override
22678        public void setValue(View object, float value) {
22679            object.setAlpha(value);
22680        }
22681
22682        @Override
22683        public Float get(View object) {
22684            return object.getAlpha();
22685        }
22686    };
22687
22688    /**
22689     * A Property wrapper around the <code>translationX</code> functionality handled by the
22690     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
22691     */
22692    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
22693        @Override
22694        public void setValue(View object, float value) {
22695            object.setTranslationX(value);
22696        }
22697
22698                @Override
22699        public Float get(View object) {
22700            return object.getTranslationX();
22701        }
22702    };
22703
22704    /**
22705     * A Property wrapper around the <code>translationY</code> functionality handled by the
22706     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
22707     */
22708    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
22709        @Override
22710        public void setValue(View object, float value) {
22711            object.setTranslationY(value);
22712        }
22713
22714        @Override
22715        public Float get(View object) {
22716            return object.getTranslationY();
22717        }
22718    };
22719
22720    /**
22721     * A Property wrapper around the <code>translationZ</code> functionality handled by the
22722     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
22723     */
22724    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
22725        @Override
22726        public void setValue(View object, float value) {
22727            object.setTranslationZ(value);
22728        }
22729
22730        @Override
22731        public Float get(View object) {
22732            return object.getTranslationZ();
22733        }
22734    };
22735
22736    /**
22737     * A Property wrapper around the <code>x</code> functionality handled by the
22738     * {@link View#setX(float)} and {@link View#getX()} methods.
22739     */
22740    public static final Property<View, Float> X = new FloatProperty<View>("x") {
22741        @Override
22742        public void setValue(View object, float value) {
22743            object.setX(value);
22744        }
22745
22746        @Override
22747        public Float get(View object) {
22748            return object.getX();
22749        }
22750    };
22751
22752    /**
22753     * A Property wrapper around the <code>y</code> functionality handled by the
22754     * {@link View#setY(float)} and {@link View#getY()} methods.
22755     */
22756    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
22757        @Override
22758        public void setValue(View object, float value) {
22759            object.setY(value);
22760        }
22761
22762        @Override
22763        public Float get(View object) {
22764            return object.getY();
22765        }
22766    };
22767
22768    /**
22769     * A Property wrapper around the <code>z</code> functionality handled by the
22770     * {@link View#setZ(float)} and {@link View#getZ()} methods.
22771     */
22772    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
22773        @Override
22774        public void setValue(View object, float value) {
22775            object.setZ(value);
22776        }
22777
22778        @Override
22779        public Float get(View object) {
22780            return object.getZ();
22781        }
22782    };
22783
22784    /**
22785     * A Property wrapper around the <code>rotation</code> functionality handled by the
22786     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
22787     */
22788    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
22789        @Override
22790        public void setValue(View object, float value) {
22791            object.setRotation(value);
22792        }
22793
22794        @Override
22795        public Float get(View object) {
22796            return object.getRotation();
22797        }
22798    };
22799
22800    /**
22801     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22802     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22803     */
22804    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22805        @Override
22806        public void setValue(View object, float value) {
22807            object.setRotationX(value);
22808        }
22809
22810        @Override
22811        public Float get(View object) {
22812            return object.getRotationX();
22813        }
22814    };
22815
22816    /**
22817     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22818     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22819     */
22820    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22821        @Override
22822        public void setValue(View object, float value) {
22823            object.setRotationY(value);
22824        }
22825
22826        @Override
22827        public Float get(View object) {
22828            return object.getRotationY();
22829        }
22830    };
22831
22832    /**
22833     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22834     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22835     */
22836    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22837        @Override
22838        public void setValue(View object, float value) {
22839            object.setScaleX(value);
22840        }
22841
22842        @Override
22843        public Float get(View object) {
22844            return object.getScaleX();
22845        }
22846    };
22847
22848    /**
22849     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22850     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22851     */
22852    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22853        @Override
22854        public void setValue(View object, float value) {
22855            object.setScaleY(value);
22856        }
22857
22858        @Override
22859        public Float get(View object) {
22860            return object.getScaleY();
22861        }
22862    };
22863
22864    /**
22865     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22866     * Each MeasureSpec represents a requirement for either the width or the height.
22867     * A MeasureSpec is comprised of a size and a mode. There are three possible
22868     * modes:
22869     * <dl>
22870     * <dt>UNSPECIFIED</dt>
22871     * <dd>
22872     * The parent has not imposed any constraint on the child. It can be whatever size
22873     * it wants.
22874     * </dd>
22875     *
22876     * <dt>EXACTLY</dt>
22877     * <dd>
22878     * The parent has determined an exact size for the child. The child is going to be
22879     * given those bounds regardless of how big it wants to be.
22880     * </dd>
22881     *
22882     * <dt>AT_MOST</dt>
22883     * <dd>
22884     * The child can be as large as it wants up to the specified size.
22885     * </dd>
22886     * </dl>
22887     *
22888     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22889     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22890     */
22891    public static class MeasureSpec {
22892        private static final int MODE_SHIFT = 30;
22893        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22894
22895        /** @hide */
22896        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22897        @Retention(RetentionPolicy.SOURCE)
22898        public @interface MeasureSpecMode {}
22899
22900        /**
22901         * Measure specification mode: The parent has not imposed any constraint
22902         * on the child. It can be whatever size it wants.
22903         */
22904        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22905
22906        /**
22907         * Measure specification mode: The parent has determined an exact size
22908         * for the child. The child is going to be given those bounds regardless
22909         * of how big it wants to be.
22910         */
22911        public static final int EXACTLY     = 1 << MODE_SHIFT;
22912
22913        /**
22914         * Measure specification mode: The child can be as large as it wants up
22915         * to the specified size.
22916         */
22917        public static final int AT_MOST     = 2 << MODE_SHIFT;
22918
22919        /**
22920         * Creates a measure specification based on the supplied size and mode.
22921         *
22922         * The mode must always be one of the following:
22923         * <ul>
22924         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22925         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22926         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22927         * </ul>
22928         *
22929         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22930         * implementation was such that the order of arguments did not matter
22931         * and overflow in either value could impact the resulting MeasureSpec.
22932         * {@link android.widget.RelativeLayout} was affected by this bug.
22933         * Apps targeting API levels greater than 17 will get the fixed, more strict
22934         * behavior.</p>
22935         *
22936         * @param size the size of the measure specification
22937         * @param mode the mode of the measure specification
22938         * @return the measure specification based on size and mode
22939         */
22940        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22941                                          @MeasureSpecMode int mode) {
22942            if (sUseBrokenMakeMeasureSpec) {
22943                return size + mode;
22944            } else {
22945                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22946            }
22947        }
22948
22949        /**
22950         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22951         * will automatically get a size of 0. Older apps expect this.
22952         *
22953         * @hide internal use only for compatibility with system widgets and older apps
22954         */
22955        public static int makeSafeMeasureSpec(int size, int mode) {
22956            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22957                return 0;
22958            }
22959            return makeMeasureSpec(size, mode);
22960        }
22961
22962        /**
22963         * Extracts the mode from the supplied measure specification.
22964         *
22965         * @param measureSpec the measure specification to extract the mode from
22966         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22967         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22968         *         {@link android.view.View.MeasureSpec#EXACTLY}
22969         */
22970        @MeasureSpecMode
22971        public static int getMode(int measureSpec) {
22972            //noinspection ResourceType
22973            return (measureSpec & MODE_MASK);
22974        }
22975
22976        /**
22977         * Extracts the size from the supplied measure specification.
22978         *
22979         * @param measureSpec the measure specification to extract the size from
22980         * @return the size in pixels defined in the supplied measure specification
22981         */
22982        public static int getSize(int measureSpec) {
22983            return (measureSpec & ~MODE_MASK);
22984        }
22985
22986        static int adjust(int measureSpec, int delta) {
22987            final int mode = getMode(measureSpec);
22988            int size = getSize(measureSpec);
22989            if (mode == UNSPECIFIED) {
22990                // No need to adjust size for UNSPECIFIED mode.
22991                return makeMeasureSpec(size, UNSPECIFIED);
22992            }
22993            size += delta;
22994            if (size < 0) {
22995                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22996                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22997                size = 0;
22998            }
22999            return makeMeasureSpec(size, mode);
23000        }
23001
23002        /**
23003         * Returns a String representation of the specified measure
23004         * specification.
23005         *
23006         * @param measureSpec the measure specification to convert to a String
23007         * @return a String with the following format: "MeasureSpec: MODE SIZE"
23008         */
23009        public static String toString(int measureSpec) {
23010            int mode = getMode(measureSpec);
23011            int size = getSize(measureSpec);
23012
23013            StringBuilder sb = new StringBuilder("MeasureSpec: ");
23014
23015            if (mode == UNSPECIFIED)
23016                sb.append("UNSPECIFIED ");
23017            else if (mode == EXACTLY)
23018                sb.append("EXACTLY ");
23019            else if (mode == AT_MOST)
23020                sb.append("AT_MOST ");
23021            else
23022                sb.append(mode).append(" ");
23023
23024            sb.append(size);
23025            return sb.toString();
23026        }
23027    }
23028
23029    private final class CheckForLongPress implements Runnable {
23030        private int mOriginalWindowAttachCount;
23031        private float mX;
23032        private float mY;
23033        private boolean mOriginalPressedState;
23034
23035        @Override
23036        public void run() {
23037            if ((mOriginalPressedState == isPressed()) && (mParent != null)
23038                    && mOriginalWindowAttachCount == mWindowAttachCount) {
23039                if (performLongClick(mX, mY)) {
23040                    mHasPerformedLongPress = true;
23041                }
23042            }
23043        }
23044
23045        public void setAnchor(float x, float y) {
23046            mX = x;
23047            mY = y;
23048        }
23049
23050        public void rememberWindowAttachCount() {
23051            mOriginalWindowAttachCount = mWindowAttachCount;
23052        }
23053
23054        public void rememberPressedState() {
23055            mOriginalPressedState = isPressed();
23056        }
23057    }
23058
23059    private final class CheckForTap implements Runnable {
23060        public float x;
23061        public float y;
23062
23063        @Override
23064        public void run() {
23065            mPrivateFlags &= ~PFLAG_PREPRESSED;
23066            setPressed(true, x, y);
23067            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
23068        }
23069    }
23070
23071    private final class PerformClick implements Runnable {
23072        @Override
23073        public void run() {
23074            performClick();
23075        }
23076    }
23077
23078    /**
23079     * This method returns a ViewPropertyAnimator object, which can be used to animate
23080     * specific properties on this View.
23081     *
23082     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
23083     */
23084    public ViewPropertyAnimator animate() {
23085        if (mAnimator == null) {
23086            mAnimator = new ViewPropertyAnimator(this);
23087        }
23088        return mAnimator;
23089    }
23090
23091    /**
23092     * Sets the name of the View to be used to identify Views in Transitions.
23093     * Names should be unique in the View hierarchy.
23094     *
23095     * @param transitionName The name of the View to uniquely identify it for Transitions.
23096     */
23097    public final void setTransitionName(String transitionName) {
23098        mTransitionName = transitionName;
23099    }
23100
23101    /**
23102     * Returns the name of the View to be used to identify Views in Transitions.
23103     * Names should be unique in the View hierarchy.
23104     *
23105     * <p>This returns null if the View has not been given a name.</p>
23106     *
23107     * @return The name used of the View to be used to identify Views in Transitions or null
23108     * if no name has been given.
23109     */
23110    @ViewDebug.ExportedProperty
23111    public String getTransitionName() {
23112        return mTransitionName;
23113    }
23114
23115    /**
23116     * @hide
23117     */
23118    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
23119        // Do nothing.
23120    }
23121
23122    /**
23123     * Interface definition for a callback to be invoked when a hardware key event is
23124     * dispatched to this view. The callback will be invoked before the key event is
23125     * given to the view. This is only useful for hardware keyboards; a software input
23126     * method has no obligation to trigger this listener.
23127     */
23128    public interface OnKeyListener {
23129        /**
23130         * Called when a hardware key is dispatched to a view. This allows listeners to
23131         * get a chance to respond before the target view.
23132         * <p>Key presses in software keyboards will generally NOT trigger this method,
23133         * although some may elect to do so in some situations. Do not assume a
23134         * software input method has to be key-based; even if it is, it may use key presses
23135         * in a different way than you expect, so there is no way to reliably catch soft
23136         * input key presses.
23137         *
23138         * @param v The view the key has been dispatched to.
23139         * @param keyCode The code for the physical key that was pressed
23140         * @param event The KeyEvent object containing full information about
23141         *        the event.
23142         * @return True if the listener has consumed the event, false otherwise.
23143         */
23144        boolean onKey(View v, int keyCode, KeyEvent event);
23145    }
23146
23147    /**
23148     * Interface definition for a callback to be invoked when a touch event is
23149     * dispatched to this view. The callback will be invoked before the touch
23150     * event is given to the view.
23151     */
23152    public interface OnTouchListener {
23153        /**
23154         * Called when a touch event is dispatched to a view. This allows listeners to
23155         * get a chance to respond before the target view.
23156         *
23157         * @param v The view the touch event has been dispatched to.
23158         * @param event The MotionEvent object containing full information about
23159         *        the event.
23160         * @return True if the listener has consumed the event, false otherwise.
23161         */
23162        boolean onTouch(View v, MotionEvent event);
23163    }
23164
23165    /**
23166     * Interface definition for a callback to be invoked when a hover event is
23167     * dispatched to this view. The callback will be invoked before the hover
23168     * event is given to the view.
23169     */
23170    public interface OnHoverListener {
23171        /**
23172         * Called when a hover event is dispatched to a view. This allows listeners to
23173         * get a chance to respond before the target view.
23174         *
23175         * @param v The view the hover event has been dispatched to.
23176         * @param event The MotionEvent object containing full information about
23177         *        the event.
23178         * @return True if the listener has consumed the event, false otherwise.
23179         */
23180        boolean onHover(View v, MotionEvent event);
23181    }
23182
23183    /**
23184     * Interface definition for a callback to be invoked when a generic motion event is
23185     * dispatched to this view. The callback will be invoked before the generic motion
23186     * event is given to the view.
23187     */
23188    public interface OnGenericMotionListener {
23189        /**
23190         * Called when a generic motion event is dispatched to a view. This allows listeners to
23191         * get a chance to respond before the target view.
23192         *
23193         * @param v The view the generic motion event has been dispatched to.
23194         * @param event The MotionEvent object containing full information about
23195         *        the event.
23196         * @return True if the listener has consumed the event, false otherwise.
23197         */
23198        boolean onGenericMotion(View v, MotionEvent event);
23199    }
23200
23201    /**
23202     * Interface definition for a callback to be invoked when a view has been clicked and held.
23203     */
23204    public interface OnLongClickListener {
23205        /**
23206         * Called when a view has been clicked and held.
23207         *
23208         * @param v The view that was clicked and held.
23209         *
23210         * @return true if the callback consumed the long click, false otherwise.
23211         */
23212        boolean onLongClick(View v);
23213    }
23214
23215    /**
23216     * Interface definition for a callback to be invoked when a drag is being dispatched
23217     * to this view.  The callback will be invoked before the hosting view's own
23218     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
23219     * onDrag(event) behavior, it should return 'false' from this callback.
23220     *
23221     * <div class="special reference">
23222     * <h3>Developer Guides</h3>
23223     * <p>For a guide to implementing drag and drop features, read the
23224     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
23225     * </div>
23226     */
23227    public interface OnDragListener {
23228        /**
23229         * Called when a drag event is dispatched to a view. This allows listeners
23230         * to get a chance to override base View behavior.
23231         *
23232         * @param v The View that received the drag event.
23233         * @param event The {@link android.view.DragEvent} object for the drag event.
23234         * @return {@code true} if the drag event was handled successfully, or {@code false}
23235         * if the drag event was not handled. Note that {@code false} will trigger the View
23236         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
23237         */
23238        boolean onDrag(View v, DragEvent event);
23239    }
23240
23241    /**
23242     * Interface definition for a callback to be invoked when the focus state of
23243     * a view changed.
23244     */
23245    public interface OnFocusChangeListener {
23246        /**
23247         * Called when the focus state of a view has changed.
23248         *
23249         * @param v The view whose state has changed.
23250         * @param hasFocus The new focus state of v.
23251         */
23252        void onFocusChange(View v, boolean hasFocus);
23253    }
23254
23255    /**
23256     * Interface definition for a callback to be invoked when a view is clicked.
23257     */
23258    public interface OnClickListener {
23259        /**
23260         * Called when a view has been clicked.
23261         *
23262         * @param v The view that was clicked.
23263         */
23264        void onClick(View v);
23265    }
23266
23267    /**
23268     * Interface definition for a callback to be invoked when a view is context clicked.
23269     */
23270    public interface OnContextClickListener {
23271        /**
23272         * Called when a view is context clicked.
23273         *
23274         * @param v The view that has been context clicked.
23275         * @return true if the callback consumed the context click, false otherwise.
23276         */
23277        boolean onContextClick(View v);
23278    }
23279
23280    /**
23281     * Interface definition for a callback to be invoked when the context menu
23282     * for this view is being built.
23283     */
23284    public interface OnCreateContextMenuListener {
23285        /**
23286         * Called when the context menu for this view is being built. It is not
23287         * safe to hold onto the menu after this method returns.
23288         *
23289         * @param menu The context menu that is being built
23290         * @param v The view for which the context menu is being built
23291         * @param menuInfo Extra information about the item for which the
23292         *            context menu should be shown. This information will vary
23293         *            depending on the class of v.
23294         */
23295        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
23296    }
23297
23298    /**
23299     * Interface definition for a callback to be invoked when the status bar changes
23300     * visibility.  This reports <strong>global</strong> changes to the system UI
23301     * state, not what the application is requesting.
23302     *
23303     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
23304     */
23305    public interface OnSystemUiVisibilityChangeListener {
23306        /**
23307         * Called when the status bar changes visibility because of a call to
23308         * {@link View#setSystemUiVisibility(int)}.
23309         *
23310         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23311         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
23312         * This tells you the <strong>global</strong> state of these UI visibility
23313         * flags, not what your app is currently applying.
23314         */
23315        public void onSystemUiVisibilityChange(int visibility);
23316    }
23317
23318    /**
23319     * Interface definition for a callback to be invoked when this view is attached
23320     * or detached from its window.
23321     */
23322    public interface OnAttachStateChangeListener {
23323        /**
23324         * Called when the view is attached to a window.
23325         * @param v The view that was attached
23326         */
23327        public void onViewAttachedToWindow(View v);
23328        /**
23329         * Called when the view is detached from a window.
23330         * @param v The view that was detached
23331         */
23332        public void onViewDetachedFromWindow(View v);
23333    }
23334
23335    /**
23336     * Listener for applying window insets on a view in a custom way.
23337     *
23338     * <p>Apps may choose to implement this interface if they want to apply custom policy
23339     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
23340     * is set, its
23341     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
23342     * method will be called instead of the View's own
23343     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
23344     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
23345     * the View's normal behavior as part of its own.</p>
23346     */
23347    public interface OnApplyWindowInsetsListener {
23348        /**
23349         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
23350         * on a View, this listener method will be called instead of the view's own
23351         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
23352         *
23353         * @param v The view applying window insets
23354         * @param insets The insets to apply
23355         * @return The insets supplied, minus any insets that were consumed
23356         */
23357        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
23358    }
23359
23360    private final class UnsetPressedState implements Runnable {
23361        @Override
23362        public void run() {
23363            setPressed(false);
23364        }
23365    }
23366
23367    /**
23368     * Base class for derived classes that want to save and restore their own
23369     * state in {@link android.view.View#onSaveInstanceState()}.
23370     */
23371    public static class BaseSavedState extends AbsSavedState {
23372        String mStartActivityRequestWhoSaved;
23373
23374        /**
23375         * Constructor used when reading from a parcel. Reads the state of the superclass.
23376         *
23377         * @param source parcel to read from
23378         */
23379        public BaseSavedState(Parcel source) {
23380            this(source, null);
23381        }
23382
23383        /**
23384         * Constructor used when reading from a parcel using a given class loader.
23385         * Reads the state of the superclass.
23386         *
23387         * @param source parcel to read from
23388         * @param loader ClassLoader to use for reading
23389         */
23390        public BaseSavedState(Parcel source, ClassLoader loader) {
23391            super(source, loader);
23392            mStartActivityRequestWhoSaved = source.readString();
23393        }
23394
23395        /**
23396         * Constructor called by derived classes when creating their SavedState objects
23397         *
23398         * @param superState The state of the superclass of this view
23399         */
23400        public BaseSavedState(Parcelable superState) {
23401            super(superState);
23402        }
23403
23404        @Override
23405        public void writeToParcel(Parcel out, int flags) {
23406            super.writeToParcel(out, flags);
23407            out.writeString(mStartActivityRequestWhoSaved);
23408        }
23409
23410        public static final Parcelable.Creator<BaseSavedState> CREATOR
23411                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
23412            @Override
23413            public BaseSavedState createFromParcel(Parcel in) {
23414                return new BaseSavedState(in);
23415            }
23416
23417            @Override
23418            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
23419                return new BaseSavedState(in, loader);
23420            }
23421
23422            @Override
23423            public BaseSavedState[] newArray(int size) {
23424                return new BaseSavedState[size];
23425            }
23426        };
23427    }
23428
23429    /**
23430     * A set of information given to a view when it is attached to its parent
23431     * window.
23432     */
23433    final static class AttachInfo {
23434        interface Callbacks {
23435            void playSoundEffect(int effectId);
23436            boolean performHapticFeedback(int effectId, boolean always);
23437        }
23438
23439        /**
23440         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
23441         * to a Handler. This class contains the target (View) to invalidate and
23442         * the coordinates of the dirty rectangle.
23443         *
23444         * For performance purposes, this class also implements a pool of up to
23445         * POOL_LIMIT objects that get reused. This reduces memory allocations
23446         * whenever possible.
23447         */
23448        static class InvalidateInfo {
23449            private static final int POOL_LIMIT = 10;
23450
23451            private static final SynchronizedPool<InvalidateInfo> sPool =
23452                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
23453
23454            View target;
23455
23456            int left;
23457            int top;
23458            int right;
23459            int bottom;
23460
23461            public static InvalidateInfo obtain() {
23462                InvalidateInfo instance = sPool.acquire();
23463                return (instance != null) ? instance : new InvalidateInfo();
23464            }
23465
23466            public void recycle() {
23467                target = null;
23468                sPool.release(this);
23469            }
23470        }
23471
23472        final IWindowSession mSession;
23473
23474        final IWindow mWindow;
23475
23476        final IBinder mWindowToken;
23477
23478        final Display mDisplay;
23479
23480        final Callbacks mRootCallbacks;
23481
23482        IWindowId mIWindowId;
23483        WindowId mWindowId;
23484
23485        /**
23486         * The top view of the hierarchy.
23487         */
23488        View mRootView;
23489
23490        IBinder mPanelParentWindowToken;
23491
23492        boolean mHardwareAccelerated;
23493        boolean mHardwareAccelerationRequested;
23494        ThreadedRenderer mThreadedRenderer;
23495        List<RenderNode> mPendingAnimatingRenderNodes;
23496
23497        /**
23498         * The state of the display to which the window is attached, as reported
23499         * by {@link Display#getState()}.  Note that the display state constants
23500         * declared by {@link Display} do not exactly line up with the screen state
23501         * constants declared by {@link View} (there are more display states than
23502         * screen states).
23503         */
23504        int mDisplayState = Display.STATE_UNKNOWN;
23505
23506        /**
23507         * Scale factor used by the compatibility mode
23508         */
23509        float mApplicationScale;
23510
23511        /**
23512         * Indicates whether the application is in compatibility mode
23513         */
23514        boolean mScalingRequired;
23515
23516        /**
23517         * Left position of this view's window
23518         */
23519        int mWindowLeft;
23520
23521        /**
23522         * Top position of this view's window
23523         */
23524        int mWindowTop;
23525
23526        /**
23527         * Indicates whether views need to use 32-bit drawing caches
23528         */
23529        boolean mUse32BitDrawingCache;
23530
23531        /**
23532         * For windows that are full-screen but using insets to layout inside
23533         * of the screen areas, these are the current insets to appear inside
23534         * the overscan area of the display.
23535         */
23536        final Rect mOverscanInsets = new Rect();
23537
23538        /**
23539         * For windows that are full-screen but using insets to layout inside
23540         * of the screen decorations, these are the current insets for the
23541         * content of the window.
23542         */
23543        final Rect mContentInsets = new Rect();
23544
23545        /**
23546         * For windows that are full-screen but using insets to layout inside
23547         * of the screen decorations, these are the current insets for the
23548         * actual visible parts of the window.
23549         */
23550        final Rect mVisibleInsets = new Rect();
23551
23552        /**
23553         * For windows that are full-screen but using insets to layout inside
23554         * of the screen decorations, these are the current insets for the
23555         * stable system windows.
23556         */
23557        final Rect mStableInsets = new Rect();
23558
23559        /**
23560         * For windows that include areas that are not covered by real surface these are the outsets
23561         * for real surface.
23562         */
23563        final Rect mOutsets = new Rect();
23564
23565        /**
23566         * In multi-window we force show the navigation bar. Because we don't want that the surface
23567         * size changes in this mode, we instead have a flag whether the navigation bar size should
23568         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
23569         */
23570        boolean mAlwaysConsumeNavBar;
23571
23572        /**
23573         * The internal insets given by this window.  This value is
23574         * supplied by the client (through
23575         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
23576         * be given to the window manager when changed to be used in laying
23577         * out windows behind it.
23578         */
23579        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
23580                = new ViewTreeObserver.InternalInsetsInfo();
23581
23582        /**
23583         * Set to true when mGivenInternalInsets is non-empty.
23584         */
23585        boolean mHasNonEmptyGivenInternalInsets;
23586
23587        /**
23588         * All views in the window's hierarchy that serve as scroll containers,
23589         * used to determine if the window can be resized or must be panned
23590         * to adjust for a soft input area.
23591         */
23592        final ArrayList<View> mScrollContainers = new ArrayList<View>();
23593
23594        final KeyEvent.DispatcherState mKeyDispatchState
23595                = new KeyEvent.DispatcherState();
23596
23597        /**
23598         * Indicates whether the view's window currently has the focus.
23599         */
23600        boolean mHasWindowFocus;
23601
23602        /**
23603         * The current visibility of the window.
23604         */
23605        int mWindowVisibility;
23606
23607        /**
23608         * Indicates the time at which drawing started to occur.
23609         */
23610        long mDrawingTime;
23611
23612        /**
23613         * Indicates whether or not ignoring the DIRTY_MASK flags.
23614         */
23615        boolean mIgnoreDirtyState;
23616
23617        /**
23618         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
23619         * to avoid clearing that flag prematurely.
23620         */
23621        boolean mSetIgnoreDirtyState = false;
23622
23623        /**
23624         * Indicates whether the view's window is currently in touch mode.
23625         */
23626        boolean mInTouchMode;
23627
23628        /**
23629         * Indicates whether the view has requested unbuffered input dispatching for the current
23630         * event stream.
23631         */
23632        boolean mUnbufferedDispatchRequested;
23633
23634        /**
23635         * Indicates that ViewAncestor should trigger a global layout change
23636         * the next time it performs a traversal
23637         */
23638        boolean mRecomputeGlobalAttributes;
23639
23640        /**
23641         * Always report new attributes at next traversal.
23642         */
23643        boolean mForceReportNewAttributes;
23644
23645        /**
23646         * Set during a traveral if any views want to keep the screen on.
23647         */
23648        boolean mKeepScreenOn;
23649
23650        /**
23651         * Set during a traveral if the light center needs to be updated.
23652         */
23653        boolean mNeedsUpdateLightCenter;
23654
23655        /**
23656         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
23657         */
23658        int mSystemUiVisibility;
23659
23660        /**
23661         * Hack to force certain system UI visibility flags to be cleared.
23662         */
23663        int mDisabledSystemUiVisibility;
23664
23665        /**
23666         * Last global system UI visibility reported by the window manager.
23667         */
23668        int mGlobalSystemUiVisibility = -1;
23669
23670        /**
23671         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
23672         * attached.
23673         */
23674        boolean mHasSystemUiListeners;
23675
23676        /**
23677         * Set if the window has requested to extend into the overscan region
23678         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
23679         */
23680        boolean mOverscanRequested;
23681
23682        /**
23683         * Set if the visibility of any views has changed.
23684         */
23685        boolean mViewVisibilityChanged;
23686
23687        /**
23688         * Set to true if a view has been scrolled.
23689         */
23690        boolean mViewScrollChanged;
23691
23692        /**
23693         * Set to true if high contrast mode enabled
23694         */
23695        boolean mHighContrastText;
23696
23697        /**
23698         * Set to true if a pointer event is currently being handled.
23699         */
23700        boolean mHandlingPointerEvent;
23701
23702        /**
23703         * Global to the view hierarchy used as a temporary for dealing with
23704         * x/y points in the transparent region computations.
23705         */
23706        final int[] mTransparentLocation = new int[2];
23707
23708        /**
23709         * Global to the view hierarchy used as a temporary for dealing with
23710         * x/y points in the ViewGroup.invalidateChild implementation.
23711         */
23712        final int[] mInvalidateChildLocation = new int[2];
23713
23714        /**
23715         * Global to the view hierarchy used as a temporary for dealing with
23716         * computing absolute on-screen location.
23717         */
23718        final int[] mTmpLocation = new int[2];
23719
23720        /**
23721         * Global to the view hierarchy used as a temporary for dealing with
23722         * x/y location when view is transformed.
23723         */
23724        final float[] mTmpTransformLocation = new float[2];
23725
23726        /**
23727         * The view tree observer used to dispatch global events like
23728         * layout, pre-draw, touch mode change, etc.
23729         */
23730        final ViewTreeObserver mTreeObserver;
23731
23732        /**
23733         * A Canvas used by the view hierarchy to perform bitmap caching.
23734         */
23735        Canvas mCanvas;
23736
23737        /**
23738         * The view root impl.
23739         */
23740        final ViewRootImpl mViewRootImpl;
23741
23742        /**
23743         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
23744         * handler can be used to pump events in the UI events queue.
23745         */
23746        final Handler mHandler;
23747
23748        /**
23749         * Temporary for use in computing invalidate rectangles while
23750         * calling up the hierarchy.
23751         */
23752        final Rect mTmpInvalRect = new Rect();
23753
23754        /**
23755         * Temporary for use in computing hit areas with transformed views
23756         */
23757        final RectF mTmpTransformRect = new RectF();
23758
23759        /**
23760         * Temporary for use in computing hit areas with transformed views
23761         */
23762        final RectF mTmpTransformRect1 = new RectF();
23763
23764        /**
23765         * Temporary list of rectanges.
23766         */
23767        final List<RectF> mTmpRectList = new ArrayList<>();
23768
23769        /**
23770         * Temporary for use in transforming invalidation rect
23771         */
23772        final Matrix mTmpMatrix = new Matrix();
23773
23774        /**
23775         * Temporary for use in transforming invalidation rect
23776         */
23777        final Transformation mTmpTransformation = new Transformation();
23778
23779        /**
23780         * Temporary for use in querying outlines from OutlineProviders
23781         */
23782        final Outline mTmpOutline = new Outline();
23783
23784        /**
23785         * Temporary list for use in collecting focusable descendents of a view.
23786         */
23787        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
23788
23789        /**
23790         * The id of the window for accessibility purposes.
23791         */
23792        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
23793
23794        /**
23795         * Flags related to accessibility processing.
23796         *
23797         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
23798         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
23799         */
23800        int mAccessibilityFetchFlags;
23801
23802        /**
23803         * The drawable for highlighting accessibility focus.
23804         */
23805        Drawable mAccessibilityFocusDrawable;
23806
23807        /**
23808         * Show where the margins, bounds and layout bounds are for each view.
23809         */
23810        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23811
23812        /**
23813         * Point used to compute visible regions.
23814         */
23815        final Point mPoint = new Point();
23816
23817        /**
23818         * Used to track which View originated a requestLayout() call, used when
23819         * requestLayout() is called during layout.
23820         */
23821        View mViewRequestingLayout;
23822
23823        /**
23824         * Used to track views that need (at least) a partial relayout at their current size
23825         * during the next traversal.
23826         */
23827        List<View> mPartialLayoutViews = new ArrayList<>();
23828
23829        /**
23830         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23831         * modification. Lazily assigned during ViewRootImpl layout.
23832         */
23833        List<View> mEmptyPartialLayoutViews;
23834
23835        /**
23836         * Used to track the identity of the current drag operation.
23837         */
23838        IBinder mDragToken;
23839
23840        /**
23841         * The drag shadow surface for the current drag operation.
23842         */
23843        public Surface mDragSurface;
23844
23845
23846        /**
23847         * The view that currently has a tooltip displayed.
23848         */
23849        View mTooltipHost;
23850
23851        /**
23852         * Creates a new set of attachment information with the specified
23853         * events handler and thread.
23854         *
23855         * @param handler the events handler the view must use
23856         */
23857        AttachInfo(IWindowSession session, IWindow window, Display display,
23858                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
23859                Context context) {
23860            mSession = session;
23861            mWindow = window;
23862            mWindowToken = window.asBinder();
23863            mDisplay = display;
23864            mViewRootImpl = viewRootImpl;
23865            mHandler = handler;
23866            mRootCallbacks = effectPlayer;
23867            mTreeObserver = new ViewTreeObserver(context);
23868        }
23869    }
23870
23871    /**
23872     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23873     * is supported. This avoids keeping too many unused fields in most
23874     * instances of View.</p>
23875     */
23876    private static class ScrollabilityCache implements Runnable {
23877
23878        /**
23879         * Scrollbars are not visible
23880         */
23881        public static final int OFF = 0;
23882
23883        /**
23884         * Scrollbars are visible
23885         */
23886        public static final int ON = 1;
23887
23888        /**
23889         * Scrollbars are fading away
23890         */
23891        public static final int FADING = 2;
23892
23893        public boolean fadeScrollBars;
23894
23895        public int fadingEdgeLength;
23896        public int scrollBarDefaultDelayBeforeFade;
23897        public int scrollBarFadeDuration;
23898
23899        public int scrollBarSize;
23900        public ScrollBarDrawable scrollBar;
23901        public float[] interpolatorValues;
23902        public View host;
23903
23904        public final Paint paint;
23905        public final Matrix matrix;
23906        public Shader shader;
23907
23908        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23909
23910        private static final float[] OPAQUE = { 255 };
23911        private static final float[] TRANSPARENT = { 0.0f };
23912
23913        /**
23914         * When fading should start. This time moves into the future every time
23915         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23916         */
23917        public long fadeStartTime;
23918
23919
23920        /**
23921         * The current state of the scrollbars: ON, OFF, or FADING
23922         */
23923        public int state = OFF;
23924
23925        private int mLastColor;
23926
23927        public final Rect mScrollBarBounds = new Rect();
23928
23929        public static final int NOT_DRAGGING = 0;
23930        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23931        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23932        public int mScrollBarDraggingState = NOT_DRAGGING;
23933
23934        public float mScrollBarDraggingPos = 0;
23935
23936        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23937            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23938            scrollBarSize = configuration.getScaledScrollBarSize();
23939            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23940            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23941
23942            paint = new Paint();
23943            matrix = new Matrix();
23944            // use use a height of 1, and then wack the matrix each time we
23945            // actually use it.
23946            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23947            paint.setShader(shader);
23948            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23949
23950            this.host = host;
23951        }
23952
23953        public void setFadeColor(int color) {
23954            if (color != mLastColor) {
23955                mLastColor = color;
23956
23957                if (color != 0) {
23958                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23959                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23960                    paint.setShader(shader);
23961                    // Restore the default transfer mode (src_over)
23962                    paint.setXfermode(null);
23963                } else {
23964                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23965                    paint.setShader(shader);
23966                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23967                }
23968            }
23969        }
23970
23971        public void run() {
23972            long now = AnimationUtils.currentAnimationTimeMillis();
23973            if (now >= fadeStartTime) {
23974
23975                // the animation fades the scrollbars out by changing
23976                // the opacity (alpha) from fully opaque to fully
23977                // transparent
23978                int nextFrame = (int) now;
23979                int framesCount = 0;
23980
23981                Interpolator interpolator = scrollBarInterpolator;
23982
23983                // Start opaque
23984                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23985
23986                // End transparent
23987                nextFrame += scrollBarFadeDuration;
23988                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23989
23990                state = FADING;
23991
23992                // Kick off the fade animation
23993                host.invalidate(true);
23994            }
23995        }
23996    }
23997
23998    /**
23999     * Resuable callback for sending
24000     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
24001     */
24002    private class SendViewScrolledAccessibilityEvent implements Runnable {
24003        public volatile boolean mIsPending;
24004
24005        public void run() {
24006            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
24007            mIsPending = false;
24008        }
24009    }
24010
24011    /**
24012     * <p>
24013     * This class represents a delegate that can be registered in a {@link View}
24014     * to enhance accessibility support via composition rather via inheritance.
24015     * It is specifically targeted to widget developers that extend basic View
24016     * classes i.e. classes in package android.view, that would like their
24017     * applications to be backwards compatible.
24018     * </p>
24019     * <div class="special reference">
24020     * <h3>Developer Guides</h3>
24021     * <p>For more information about making applications accessible, read the
24022     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
24023     * developer guide.</p>
24024     * </div>
24025     * <p>
24026     * A scenario in which a developer would like to use an accessibility delegate
24027     * is overriding a method introduced in a later API version than the minimal API
24028     * version supported by the application. For example, the method
24029     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
24030     * in API version 4 when the accessibility APIs were first introduced. If a
24031     * developer would like his application to run on API version 4 devices (assuming
24032     * all other APIs used by the application are version 4 or lower) and take advantage
24033     * of this method, instead of overriding the method which would break the application's
24034     * backwards compatibility, he can override the corresponding method in this
24035     * delegate and register the delegate in the target View if the API version of
24036     * the system is high enough, i.e. the API version is the same as or higher than the API
24037     * version that introduced
24038     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
24039     * </p>
24040     * <p>
24041     * Here is an example implementation:
24042     * </p>
24043     * <code><pre><p>
24044     * if (Build.VERSION.SDK_INT >= 14) {
24045     *     // If the API version is equal of higher than the version in
24046     *     // which onInitializeAccessibilityNodeInfo was introduced we
24047     *     // register a delegate with a customized implementation.
24048     *     View view = findViewById(R.id.view_id);
24049     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
24050     *         public void onInitializeAccessibilityNodeInfo(View host,
24051     *                 AccessibilityNodeInfo info) {
24052     *             // Let the default implementation populate the info.
24053     *             super.onInitializeAccessibilityNodeInfo(host, info);
24054     *             // Set some other information.
24055     *             info.setEnabled(host.isEnabled());
24056     *         }
24057     *     });
24058     * }
24059     * </code></pre></p>
24060     * <p>
24061     * This delegate contains methods that correspond to the accessibility methods
24062     * in View. If a delegate has been specified the implementation in View hands
24063     * off handling to the corresponding method in this delegate. The default
24064     * implementation the delegate methods behaves exactly as the corresponding
24065     * method in View for the case of no accessibility delegate been set. Hence,
24066     * to customize the behavior of a View method, clients can override only the
24067     * corresponding delegate method without altering the behavior of the rest
24068     * accessibility related methods of the host view.
24069     * </p>
24070     * <p>
24071     * <strong>Note:</strong> On platform versions prior to
24072     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
24073     * views in the {@code android.widget.*} package are called <i>before</i>
24074     * host methods. This prevents certain properties such as class name from
24075     * being modified by overriding
24076     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
24077     * as any changes will be overwritten by the host class.
24078     * <p>
24079     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
24080     * methods are called <i>after</i> host methods, which all properties to be
24081     * modified without being overwritten by the host class.
24082     */
24083    public static class AccessibilityDelegate {
24084
24085        /**
24086         * Sends an accessibility event of the given type. If accessibility is not
24087         * enabled this method has no effect.
24088         * <p>
24089         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
24090         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
24091         * been set.
24092         * </p>
24093         *
24094         * @param host The View hosting the delegate.
24095         * @param eventType The type of the event to send.
24096         *
24097         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
24098         */
24099        public void sendAccessibilityEvent(View host, int eventType) {
24100            host.sendAccessibilityEventInternal(eventType);
24101        }
24102
24103        /**
24104         * Performs the specified accessibility action on the view. For
24105         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
24106         * <p>
24107         * The default implementation behaves as
24108         * {@link View#performAccessibilityAction(int, Bundle)
24109         *  View#performAccessibilityAction(int, Bundle)} for the case of
24110         *  no accessibility delegate been set.
24111         * </p>
24112         *
24113         * @param action The action to perform.
24114         * @return Whether the action was performed.
24115         *
24116         * @see View#performAccessibilityAction(int, Bundle)
24117         *      View#performAccessibilityAction(int, Bundle)
24118         */
24119        public boolean performAccessibilityAction(View host, int action, Bundle args) {
24120            return host.performAccessibilityActionInternal(action, args);
24121        }
24122
24123        /**
24124         * Sends an accessibility event. This method behaves exactly as
24125         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
24126         * empty {@link AccessibilityEvent} and does not perform a check whether
24127         * accessibility is enabled.
24128         * <p>
24129         * The default implementation behaves as
24130         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24131         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
24132         * the case of no accessibility delegate been set.
24133         * </p>
24134         *
24135         * @param host The View hosting the delegate.
24136         * @param event The event to send.
24137         *
24138         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24139         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24140         */
24141        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
24142            host.sendAccessibilityEventUncheckedInternal(event);
24143        }
24144
24145        /**
24146         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
24147         * to its children for adding their text content to the event.
24148         * <p>
24149         * The default implementation behaves as
24150         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24151         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
24152         * the case of no accessibility delegate been set.
24153         * </p>
24154         *
24155         * @param host The View hosting the delegate.
24156         * @param event The event.
24157         * @return True if the event population was completed.
24158         *
24159         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24160         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24161         */
24162        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24163            return host.dispatchPopulateAccessibilityEventInternal(event);
24164        }
24165
24166        /**
24167         * Gives a chance to the host View to populate the accessibility event with its
24168         * text content.
24169         * <p>
24170         * The default implementation behaves as
24171         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
24172         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
24173         * the case of no accessibility delegate been set.
24174         * </p>
24175         *
24176         * @param host The View hosting the delegate.
24177         * @param event The accessibility event which to populate.
24178         *
24179         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
24180         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
24181         */
24182        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24183            host.onPopulateAccessibilityEventInternal(event);
24184        }
24185
24186        /**
24187         * Initializes an {@link AccessibilityEvent} with information about the
24188         * the host View which is the event source.
24189         * <p>
24190         * The default implementation behaves as
24191         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
24192         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
24193         * the case of no accessibility delegate been set.
24194         * </p>
24195         *
24196         * @param host The View hosting the delegate.
24197         * @param event The event to initialize.
24198         *
24199         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
24200         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
24201         */
24202        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
24203            host.onInitializeAccessibilityEventInternal(event);
24204        }
24205
24206        /**
24207         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
24208         * <p>
24209         * The default implementation behaves as
24210         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24211         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
24212         * the case of no accessibility delegate been set.
24213         * </p>
24214         *
24215         * @param host The View hosting the delegate.
24216         * @param info The instance to initialize.
24217         *
24218         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24219         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24220         */
24221        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
24222            host.onInitializeAccessibilityNodeInfoInternal(info);
24223        }
24224
24225        /**
24226         * Called when a child of the host View has requested sending an
24227         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
24228         * to augment the event.
24229         * <p>
24230         * The default implementation behaves as
24231         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24232         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
24233         * the case of no accessibility delegate been set.
24234         * </p>
24235         *
24236         * @param host The View hosting the delegate.
24237         * @param child The child which requests sending the event.
24238         * @param event The event to be sent.
24239         * @return True if the event should be sent
24240         *
24241         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24242         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24243         */
24244        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
24245                AccessibilityEvent event) {
24246            return host.onRequestSendAccessibilityEventInternal(child, event);
24247        }
24248
24249        /**
24250         * Gets the provider for managing a virtual view hierarchy rooted at this View
24251         * and reported to {@link android.accessibilityservice.AccessibilityService}s
24252         * that explore the window content.
24253         * <p>
24254         * The default implementation behaves as
24255         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
24256         * the case of no accessibility delegate been set.
24257         * </p>
24258         *
24259         * @return The provider.
24260         *
24261         * @see AccessibilityNodeProvider
24262         */
24263        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
24264            return null;
24265        }
24266
24267        /**
24268         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
24269         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
24270         * This method is responsible for obtaining an accessibility node info from a
24271         * pool of reusable instances and calling
24272         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
24273         * view to initialize the former.
24274         * <p>
24275         * <strong>Note:</strong> The client is responsible for recycling the obtained
24276         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
24277         * creation.
24278         * </p>
24279         * <p>
24280         * The default implementation behaves as
24281         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
24282         * the case of no accessibility delegate been set.
24283         * </p>
24284         * @return A populated {@link AccessibilityNodeInfo}.
24285         *
24286         * @see AccessibilityNodeInfo
24287         *
24288         * @hide
24289         */
24290        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
24291            return host.createAccessibilityNodeInfoInternal();
24292        }
24293    }
24294
24295    private class MatchIdPredicate implements Predicate<View> {
24296        public int mId;
24297
24298        @Override
24299        public boolean apply(View view) {
24300            return (view.mID == mId);
24301        }
24302    }
24303
24304    private class MatchLabelForPredicate implements Predicate<View> {
24305        private int mLabeledId;
24306
24307        @Override
24308        public boolean apply(View view) {
24309            return (view.mLabelForId == mLabeledId);
24310        }
24311    }
24312
24313    private class SendViewStateChangedAccessibilityEvent implements Runnable {
24314        private int mChangeTypes = 0;
24315        private boolean mPosted;
24316        private boolean mPostedWithDelay;
24317        private long mLastEventTimeMillis;
24318
24319        @Override
24320        public void run() {
24321            mPosted = false;
24322            mPostedWithDelay = false;
24323            mLastEventTimeMillis = SystemClock.uptimeMillis();
24324            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
24325                final AccessibilityEvent event = AccessibilityEvent.obtain();
24326                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
24327                event.setContentChangeTypes(mChangeTypes);
24328                sendAccessibilityEventUnchecked(event);
24329            }
24330            mChangeTypes = 0;
24331        }
24332
24333        public void runOrPost(int changeType) {
24334            mChangeTypes |= changeType;
24335
24336            // If this is a live region or the child of a live region, collect
24337            // all events from this frame and send them on the next frame.
24338            if (inLiveRegion()) {
24339                // If we're already posted with a delay, remove that.
24340                if (mPostedWithDelay) {
24341                    removeCallbacks(this);
24342                    mPostedWithDelay = false;
24343                }
24344                // Only post if we're not already posted.
24345                if (!mPosted) {
24346                    post(this);
24347                    mPosted = true;
24348                }
24349                return;
24350            }
24351
24352            if (mPosted) {
24353                return;
24354            }
24355
24356            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
24357            final long minEventIntevalMillis =
24358                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
24359            if (timeSinceLastMillis >= minEventIntevalMillis) {
24360                removeCallbacks(this);
24361                run();
24362            } else {
24363                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
24364                mPostedWithDelay = true;
24365            }
24366        }
24367    }
24368
24369    private boolean inLiveRegion() {
24370        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24371            return true;
24372        }
24373
24374        ViewParent parent = getParent();
24375        while (parent instanceof View) {
24376            if (((View) parent).getAccessibilityLiveRegion()
24377                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24378                return true;
24379            }
24380            parent = parent.getParent();
24381        }
24382
24383        return false;
24384    }
24385
24386    /**
24387     * Dump all private flags in readable format, useful for documentation and
24388     * sanity checking.
24389     */
24390    private static void dumpFlags() {
24391        final HashMap<String, String> found = Maps.newHashMap();
24392        try {
24393            for (Field field : View.class.getDeclaredFields()) {
24394                final int modifiers = field.getModifiers();
24395                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
24396                    if (field.getType().equals(int.class)) {
24397                        final int value = field.getInt(null);
24398                        dumpFlag(found, field.getName(), value);
24399                    } else if (field.getType().equals(int[].class)) {
24400                        final int[] values = (int[]) field.get(null);
24401                        for (int i = 0; i < values.length; i++) {
24402                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
24403                        }
24404                    }
24405                }
24406            }
24407        } catch (IllegalAccessException e) {
24408            throw new RuntimeException(e);
24409        }
24410
24411        final ArrayList<String> keys = Lists.newArrayList();
24412        keys.addAll(found.keySet());
24413        Collections.sort(keys);
24414        for (String key : keys) {
24415            Log.d(VIEW_LOG_TAG, found.get(key));
24416        }
24417    }
24418
24419    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
24420        // Sort flags by prefix, then by bits, always keeping unique keys
24421        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
24422        final int prefix = name.indexOf('_');
24423        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
24424        final String output = bits + " " + name;
24425        found.put(key, output);
24426    }
24427
24428    /** {@hide} */
24429    public void encode(@NonNull ViewHierarchyEncoder stream) {
24430        stream.beginObject(this);
24431        encodeProperties(stream);
24432        stream.endObject();
24433    }
24434
24435    /** {@hide} */
24436    @CallSuper
24437    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
24438        Object resolveId = ViewDebug.resolveId(getContext(), mID);
24439        if (resolveId instanceof String) {
24440            stream.addProperty("id", (String) resolveId);
24441        } else {
24442            stream.addProperty("id", mID);
24443        }
24444
24445        stream.addProperty("misc:transformation.alpha",
24446                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
24447        stream.addProperty("misc:transitionName", getTransitionName());
24448
24449        // layout
24450        stream.addProperty("layout:left", mLeft);
24451        stream.addProperty("layout:right", mRight);
24452        stream.addProperty("layout:top", mTop);
24453        stream.addProperty("layout:bottom", mBottom);
24454        stream.addProperty("layout:width", getWidth());
24455        stream.addProperty("layout:height", getHeight());
24456        stream.addProperty("layout:layoutDirection", getLayoutDirection());
24457        stream.addProperty("layout:layoutRtl", isLayoutRtl());
24458        stream.addProperty("layout:hasTransientState", hasTransientState());
24459        stream.addProperty("layout:baseline", getBaseline());
24460
24461        // layout params
24462        ViewGroup.LayoutParams layoutParams = getLayoutParams();
24463        if (layoutParams != null) {
24464            stream.addPropertyKey("layoutParams");
24465            layoutParams.encode(stream);
24466        }
24467
24468        // scrolling
24469        stream.addProperty("scrolling:scrollX", mScrollX);
24470        stream.addProperty("scrolling:scrollY", mScrollY);
24471
24472        // padding
24473        stream.addProperty("padding:paddingLeft", mPaddingLeft);
24474        stream.addProperty("padding:paddingRight", mPaddingRight);
24475        stream.addProperty("padding:paddingTop", mPaddingTop);
24476        stream.addProperty("padding:paddingBottom", mPaddingBottom);
24477        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
24478        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
24479        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
24480        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
24481        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
24482
24483        // measurement
24484        stream.addProperty("measurement:minHeight", mMinHeight);
24485        stream.addProperty("measurement:minWidth", mMinWidth);
24486        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
24487        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
24488
24489        // drawing
24490        stream.addProperty("drawing:elevation", getElevation());
24491        stream.addProperty("drawing:translationX", getTranslationX());
24492        stream.addProperty("drawing:translationY", getTranslationY());
24493        stream.addProperty("drawing:translationZ", getTranslationZ());
24494        stream.addProperty("drawing:rotation", getRotation());
24495        stream.addProperty("drawing:rotationX", getRotationX());
24496        stream.addProperty("drawing:rotationY", getRotationY());
24497        stream.addProperty("drawing:scaleX", getScaleX());
24498        stream.addProperty("drawing:scaleY", getScaleY());
24499        stream.addProperty("drawing:pivotX", getPivotX());
24500        stream.addProperty("drawing:pivotY", getPivotY());
24501        stream.addProperty("drawing:opaque", isOpaque());
24502        stream.addProperty("drawing:alpha", getAlpha());
24503        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
24504        stream.addProperty("drawing:shadow", hasShadow());
24505        stream.addProperty("drawing:solidColor", getSolidColor());
24506        stream.addProperty("drawing:layerType", mLayerType);
24507        stream.addProperty("drawing:willNotDraw", willNotDraw());
24508        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
24509        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
24510        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
24511        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
24512
24513        // focus
24514        stream.addProperty("focus:hasFocus", hasFocus());
24515        stream.addProperty("focus:isFocused", isFocused());
24516        stream.addProperty("focus:isFocusable", isFocusable());
24517        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
24518
24519        stream.addProperty("misc:clickable", isClickable());
24520        stream.addProperty("misc:pressed", isPressed());
24521        stream.addProperty("misc:selected", isSelected());
24522        stream.addProperty("misc:touchMode", isInTouchMode());
24523        stream.addProperty("misc:hovered", isHovered());
24524        stream.addProperty("misc:activated", isActivated());
24525
24526        stream.addProperty("misc:visibility", getVisibility());
24527        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
24528        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
24529
24530        stream.addProperty("misc:enabled", isEnabled());
24531        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
24532        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
24533
24534        // theme attributes
24535        Resources.Theme theme = getContext().getTheme();
24536        if (theme != null) {
24537            stream.addPropertyKey("theme");
24538            theme.encode(stream);
24539        }
24540
24541        // view attribute information
24542        int n = mAttributes != null ? mAttributes.length : 0;
24543        stream.addProperty("meta:__attrCount__", n/2);
24544        for (int i = 0; i < n; i += 2) {
24545            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
24546        }
24547
24548        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
24549
24550        // text
24551        stream.addProperty("text:textDirection", getTextDirection());
24552        stream.addProperty("text:textAlignment", getTextAlignment());
24553
24554        // accessibility
24555        CharSequence contentDescription = getContentDescription();
24556        stream.addProperty("accessibility:contentDescription",
24557                contentDescription == null ? "" : contentDescription.toString());
24558        stream.addProperty("accessibility:labelFor", getLabelFor());
24559        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
24560    }
24561
24562    /**
24563     * Determine if this view is rendered on a round wearable device and is the main view
24564     * on the screen.
24565     */
24566    private boolean shouldDrawRoundScrollbar() {
24567        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
24568            return false;
24569        }
24570
24571        final View rootView = getRootView();
24572        final WindowInsets insets = getRootWindowInsets();
24573
24574        int height = getHeight();
24575        int width = getWidth();
24576        int displayHeight = rootView.getHeight();
24577        int displayWidth = rootView.getWidth();
24578
24579        if (height != displayHeight || width != displayWidth) {
24580            return false;
24581        }
24582
24583        getLocationOnScreen(mAttachInfo.mTmpLocation);
24584        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
24585                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
24586    }
24587
24588    /**
24589     * Sets the tooltip text which will be displayed in a small popup next to the view.
24590     * <p>
24591     * The tooltip will be displayed:
24592     * <li>On long click, unless is not handled otherwise (by OnLongClickListener or a context
24593     * menu). </li>
24594     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
24595     *
24596     * @param tooltipText the tooltip text, or null if no tooltip is required
24597     */
24598    public final void setTooltipText(@Nullable CharSequence tooltipText) {
24599        if (TextUtils.isEmpty(tooltipText)) {
24600            setFlags(0, TOOLTIP);
24601            hideTooltip();
24602            mTooltipInfo = null;
24603        } else {
24604            setFlags(TOOLTIP, TOOLTIP);
24605            if (mTooltipInfo == null) {
24606                mTooltipInfo = new TooltipInfo();
24607                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
24608                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
24609            }
24610            mTooltipInfo.mTooltipText = tooltipText;
24611            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
24612                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText);
24613            }
24614        }
24615    }
24616
24617    /**
24618     * To be removed once the support library has stopped using it.
24619     *
24620     * @deprecated use {@link #setTooltipText} instead
24621     */
24622    @Deprecated
24623    public final void setTooltip(@Nullable CharSequence tooltipText) {
24624        setTooltipText(tooltipText);
24625    }
24626
24627    /**
24628     * Returns the view's tooltip text.
24629     *
24630     * @return the tooltip text
24631     */
24632    @Nullable
24633    public final CharSequence getTooltipText() {
24634        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
24635    }
24636
24637    /**
24638     * To be removed once the support library has stopped using it.
24639     *
24640     * @deprecated use {@link #getTooltipText} instead
24641     */
24642    @Deprecated
24643    @Nullable
24644    public final CharSequence getTooltip() {
24645        return getTooltipText();
24646    }
24647
24648    private boolean showTooltip(int x, int y, boolean fromLongClick) {
24649        if (mAttachInfo == null) {
24650            return false;
24651        }
24652        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
24653            return false;
24654        }
24655        final CharSequence tooltipText = getTooltipText();
24656        if (TextUtils.isEmpty(tooltipText)) {
24657            return false;
24658        }
24659        hideTooltip();
24660        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
24661        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
24662        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
24663        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, tooltipText);
24664        mAttachInfo.mTooltipHost = this;
24665        return true;
24666    }
24667
24668    void hideTooltip() {
24669        if (mTooltipInfo == null) {
24670            return;
24671        }
24672        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24673        if (mTooltipInfo.mTooltipPopup == null) {
24674            return;
24675        }
24676        mTooltipInfo.mTooltipPopup.hide();
24677        mTooltipInfo.mTooltipPopup = null;
24678        mTooltipInfo.mTooltipFromLongClick = false;
24679        if (mAttachInfo != null) {
24680            mAttachInfo.mTooltipHost = null;
24681        }
24682    }
24683
24684    private boolean showLongClickTooltip(int x, int y) {
24685        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24686        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24687        return showTooltip(x, y, true);
24688    }
24689
24690    private void showHoverTooltip() {
24691        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
24692    }
24693
24694    boolean dispatchTooltipHoverEvent(MotionEvent event) {
24695        if (mTooltipInfo == null) {
24696            return false;
24697        }
24698        switch(event.getAction()) {
24699            case MotionEvent.ACTION_HOVER_MOVE:
24700                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
24701                    break;
24702                }
24703                if (!mTooltipInfo.mTooltipFromLongClick) {
24704                    if (mTooltipInfo.mTooltipPopup == null) {
24705                        // Schedule showing the tooltip after a timeout.
24706                        mTooltipInfo.mAnchorX = (int) event.getX();
24707                        mTooltipInfo.mAnchorY = (int) event.getY();
24708                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24709                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
24710                                ViewConfiguration.getHoverTooltipShowTimeout());
24711                    }
24712
24713                    // Hide hover-triggered tooltip after a period of inactivity.
24714                    // Match the timeout used by NativeInputManager to hide the mouse pointer
24715                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
24716                    final int timeout;
24717                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
24718                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
24719                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
24720                    } else {
24721                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
24722                    }
24723                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24724                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
24725                }
24726                return true;
24727
24728            case MotionEvent.ACTION_HOVER_EXIT:
24729                if (!mTooltipInfo.mTooltipFromLongClick) {
24730                    hideTooltip();
24731                }
24732                break;
24733        }
24734        return false;
24735    }
24736
24737    void handleTooltipKey(KeyEvent event) {
24738        switch (event.getAction()) {
24739            case KeyEvent.ACTION_DOWN:
24740                if (event.getRepeatCount() == 0) {
24741                    hideTooltip();
24742                }
24743                break;
24744
24745            case KeyEvent.ACTION_UP:
24746                handleTooltipUp();
24747                break;
24748        }
24749    }
24750
24751    private void handleTooltipUp() {
24752        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24753            return;
24754        }
24755        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24756        postDelayed(mTooltipInfo.mHideTooltipRunnable,
24757                ViewConfiguration.getLongPressTooltipHideTimeout());
24758    }
24759
24760    private int getFocusableAttribute(TypedArray attributes) {
24761        TypedValue val = new TypedValue();
24762        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
24763            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
24764                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
24765            } else {
24766                return val.data;
24767            }
24768        } else {
24769            return FOCUSABLE_AUTO;
24770        }
24771    }
24772
24773    /**
24774     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
24775     * is not showing.
24776     * @hide
24777     */
24778    @TestApi
24779    public View getTooltipView() {
24780        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24781            return null;
24782        }
24783        return mTooltipInfo.mTooltipPopup.getContentView();
24784    }
24785}
24786