View.java revision 2b004b3abaa8b4eb4b51c6e78840ff793d1ea9e8
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
20import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
21import static android.os.Build.VERSION_CODES.KITKAT;
22import static android.os.Build.VERSION_CODES.M;
23import static android.os.Build.VERSION_CODES.N;
24
25import static java.lang.Math.max;
26
27import android.animation.AnimatorInflater;
28import android.animation.StateListAnimator;
29import android.annotation.CallSuper;
30import android.annotation.ColorInt;
31import android.annotation.DrawableRes;
32import android.annotation.FloatRange;
33import android.annotation.IdRes;
34import android.annotation.IntDef;
35import android.annotation.IntRange;
36import android.annotation.LayoutRes;
37import android.annotation.NonNull;
38import android.annotation.Nullable;
39import android.annotation.Size;
40import android.annotation.TestApi;
41import android.annotation.UiThread;
42import android.app.Application.OnProvideAssistDataListener;
43import android.content.ClipData;
44import android.content.Context;
45import android.content.ContextWrapper;
46import android.content.Intent;
47import android.content.res.ColorStateList;
48import android.content.res.Configuration;
49import android.content.res.Resources;
50import android.content.res.TypedArray;
51import android.graphics.Bitmap;
52import android.graphics.Canvas;
53import android.graphics.Color;
54import android.graphics.Insets;
55import android.graphics.Interpolator;
56import android.graphics.LinearGradient;
57import android.graphics.Matrix;
58import android.graphics.Outline;
59import android.graphics.Paint;
60import android.graphics.PixelFormat;
61import android.graphics.Point;
62import android.graphics.PorterDuff;
63import android.graphics.PorterDuffXfermode;
64import android.graphics.Rect;
65import android.graphics.RectF;
66import android.graphics.Region;
67import android.graphics.Shader;
68import android.graphics.drawable.ColorDrawable;
69import android.graphics.drawable.Drawable;
70import android.hardware.display.DisplayManagerGlobal;
71import android.os.Build.VERSION_CODES;
72import android.os.Bundle;
73import android.os.Handler;
74import android.os.IBinder;
75import android.os.Parcel;
76import android.os.Parcelable;
77import android.os.RemoteException;
78import android.os.SystemClock;
79import android.os.SystemProperties;
80import android.os.Trace;
81import android.text.TextUtils;
82import android.util.AttributeSet;
83import android.util.FloatProperty;
84import android.util.LayoutDirection;
85import android.util.Log;
86import android.util.LongSparseLongArray;
87import android.util.Pools.SynchronizedPool;
88import android.util.Property;
89import android.util.SparseArray;
90import android.util.StateSet;
91import android.util.SuperNotCalledException;
92import android.util.TypedValue;
93import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
94import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
95import android.view.AccessibilityIterators.TextSegmentIterator;
96import android.view.AccessibilityIterators.WordTextSegmentIterator;
97import android.view.ContextMenu.ContextMenuInfo;
98import android.view.accessibility.AccessibilityEvent;
99import android.view.accessibility.AccessibilityEventSource;
100import android.view.accessibility.AccessibilityManager;
101import android.view.accessibility.AccessibilityNodeInfo;
102import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
103import android.view.accessibility.AccessibilityNodeProvider;
104import android.view.animation.Animation;
105import android.view.animation.AnimationUtils;
106import android.view.animation.Transformation;
107import android.view.autofill.AutoFillManager;
108import android.view.autofill.AutoFillType;
109import android.view.autofill.AutoFillValue;
110import android.view.autofill.VirtualViewDelegate;
111import android.view.inputmethod.EditorInfo;
112import android.view.inputmethod.InputConnection;
113import android.view.inputmethod.InputMethodManager;
114import android.widget.Checkable;
115import android.widget.FrameLayout;
116import android.widget.ScrollBarDrawable;
117
118import com.android.internal.R;
119import com.android.internal.util.Predicate;
120import com.android.internal.view.TooltipPopup;
121import com.android.internal.view.menu.MenuBuilder;
122import com.android.internal.widget.ScrollBarUtils;
123
124import com.google.android.collect.Lists;
125import com.google.android.collect.Maps;
126
127import java.lang.annotation.Retention;
128import java.lang.annotation.RetentionPolicy;
129import java.lang.ref.WeakReference;
130import java.lang.reflect.Field;
131import java.lang.reflect.InvocationTargetException;
132import java.lang.reflect.Method;
133import java.lang.reflect.Modifier;
134import java.util.ArrayList;
135import java.util.Arrays;
136import java.util.Collection;
137import java.util.Collections;
138import java.util.HashMap;
139import java.util.List;
140import java.util.Locale;
141import java.util.Map;
142import java.util.concurrent.CopyOnWriteArrayList;
143import java.util.concurrent.atomic.AtomicInteger;
144
145/**
146 * <p>
147 * This class represents the basic building block for user interface components. A View
148 * occupies a rectangular area on the screen and is responsible for drawing and
149 * event handling. View is the base class for <em>widgets</em>, which are
150 * used to create interactive UI components (buttons, text fields, etc.). The
151 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
152 * are invisible containers that hold other Views (or other ViewGroups) and define
153 * their layout properties.
154 * </p>
155 *
156 * <div class="special reference">
157 * <h3>Developer Guides</h3>
158 * <p>For information about using this class to develop your application's user interface,
159 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
160 * </div>
161 *
162 * <a name="Using"></a>
163 * <h3>Using Views</h3>
164 * <p>
165 * All of the views in a window are arranged in a single tree. You can add views
166 * either from code or by specifying a tree of views in one or more XML layout
167 * files. There are many specialized subclasses of views that act as controls or
168 * are capable of displaying text, images, or other content.
169 * </p>
170 * <p>
171 * Once you have created a tree of views, there are typically a few types of
172 * common operations you may wish to perform:
173 * <ul>
174 * <li><strong>Set properties:</strong> for example setting the text of a
175 * {@link android.widget.TextView}. The available properties and the methods
176 * that set them will vary among the different subclasses of views. Note that
177 * properties that are known at build time can be set in the XML layout
178 * files.</li>
179 * <li><strong>Set focus:</strong> The framework will handle moving focus in
180 * response to user input. To force focus to a specific view, call
181 * {@link #requestFocus}.</li>
182 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
183 * that will be notified when something interesting happens to the view. For
184 * example, all views will let you set a listener to be notified when the view
185 * gains or loses focus. You can register such a listener using
186 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
187 * Other view subclasses offer more specialized listeners. For example, a Button
188 * exposes a listener to notify clients when the button is clicked.</li>
189 * <li><strong>Set visibility:</strong> You can hide or show views using
190 * {@link #setVisibility(int)}.</li>
191 * </ul>
192 * </p>
193 * <p><em>
194 * Note: The Android framework is responsible for measuring, laying out and
195 * drawing views. You should not call methods that perform these actions on
196 * views yourself unless you are actually implementing a
197 * {@link android.view.ViewGroup}.
198 * </em></p>
199 *
200 * <a name="Lifecycle"></a>
201 * <h3>Implementing a Custom View</h3>
202 *
203 * <p>
204 * To implement a custom view, you will usually begin by providing overrides for
205 * some of the standard methods that the framework calls on all views. You do
206 * not need to override all of these methods. In fact, you can start by just
207 * overriding {@link #onDraw(android.graphics.Canvas)}.
208 * <table border="2" width="85%" align="center" cellpadding="5">
209 *     <thead>
210 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
211 *     </thead>
212 *
213 *     <tbody>
214 *     <tr>
215 *         <td rowspan="2">Creation</td>
216 *         <td>Constructors</td>
217 *         <td>There is a form of the constructor that are called when the view
218 *         is created from code and a form that is called when the view is
219 *         inflated from a layout file. The second form should parse and apply
220 *         any attributes defined in the layout file.
221 *         </td>
222 *     </tr>
223 *     <tr>
224 *         <td><code>{@link #onFinishInflate()}</code></td>
225 *         <td>Called after a view and all of its children has been inflated
226 *         from XML.</td>
227 *     </tr>
228 *
229 *     <tr>
230 *         <td rowspan="3">Layout</td>
231 *         <td><code>{@link #onMeasure(int, int)}</code></td>
232 *         <td>Called to determine the size requirements for this view and all
233 *         of its children.
234 *         </td>
235 *     </tr>
236 *     <tr>
237 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
238 *         <td>Called when this view should assign a size and position to all
239 *         of its children.
240 *         </td>
241 *     </tr>
242 *     <tr>
243 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
244 *         <td>Called when the size of this view has changed.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td>Drawing</td>
250 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
251 *         <td>Called when the view should render its content.
252 *         </td>
253 *     </tr>
254 *
255 *     <tr>
256 *         <td rowspan="4">Event processing</td>
257 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
258 *         <td>Called when a new hardware key event occurs.
259 *         </td>
260 *     </tr>
261 *     <tr>
262 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
263 *         <td>Called when a hardware key up event occurs.
264 *         </td>
265 *     </tr>
266 *     <tr>
267 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
268 *         <td>Called when a trackball motion event occurs.
269 *         </td>
270 *     </tr>
271 *     <tr>
272 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
273 *         <td>Called when a touch screen motion event occurs.
274 *         </td>
275 *     </tr>
276 *
277 *     <tr>
278 *         <td rowspan="2">Focus</td>
279 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
280 *         <td>Called when the view gains or loses focus.
281 *         </td>
282 *     </tr>
283 *
284 *     <tr>
285 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
286 *         <td>Called when the window containing the view gains or loses focus.
287 *         </td>
288 *     </tr>
289 *
290 *     <tr>
291 *         <td rowspan="3">Attaching</td>
292 *         <td><code>{@link #onAttachedToWindow()}</code></td>
293 *         <td>Called when the view is attached to a window.
294 *         </td>
295 *     </tr>
296 *
297 *     <tr>
298 *         <td><code>{@link #onDetachedFromWindow}</code></td>
299 *         <td>Called when the view is detached from its window.
300 *         </td>
301 *     </tr>
302 *
303 *     <tr>
304 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
305 *         <td>Called when the visibility of the window containing the view
306 *         has changed.
307 *         </td>
308 *     </tr>
309 *     </tbody>
310 *
311 * </table>
312 * </p>
313 *
314 * <a name="IDs"></a>
315 * <h3>IDs</h3>
316 * Views may have an integer id associated with them. These ids are typically
317 * assigned in the layout XML files, and are used to find specific views within
318 * the view tree. A common pattern is to:
319 * <ul>
320 * <li>Define a Button in the layout file and assign it a unique ID.
321 * <pre>
322 * &lt;Button
323 *     android:id="@+id/my_button"
324 *     android:layout_width="wrap_content"
325 *     android:layout_height="wrap_content"
326 *     android:text="@string/my_button_text"/&gt;
327 * </pre></li>
328 * <li>From the onCreate method of an Activity, find the Button
329 * <pre class="prettyprint">
330 *      Button myButton = (Button) findViewById(R.id.my_button);
331 * </pre></li>
332 * </ul>
333 * <p>
334 * View IDs need not be unique throughout the tree, but it is good practice to
335 * ensure that they are at least unique within the part of the tree you are
336 * searching.
337 * </p>
338 *
339 * <a name="Position"></a>
340 * <h3>Position</h3>
341 * <p>
342 * The geometry of a view is that of a rectangle. A view has a location,
343 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
344 * two dimensions, expressed as a width and a height. The unit for location
345 * and dimensions is the pixel.
346 * </p>
347 *
348 * <p>
349 * It is possible to retrieve the location of a view by invoking the methods
350 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
351 * coordinate of the rectangle representing the view. The latter returns the
352 * top, or Y, coordinate of the rectangle representing the view. These methods
353 * both return the location of the view relative to its parent. For instance,
354 * when getLeft() returns 20, that means the view is located 20 pixels to the
355 * right of the left edge of its direct parent.
356 * </p>
357 *
358 * <p>
359 * In addition, several convenience methods are offered to avoid unnecessary
360 * computations, namely {@link #getRight()} and {@link #getBottom()}.
361 * These methods return the coordinates of the right and bottom edges of the
362 * rectangle representing the view. For instance, calling {@link #getRight()}
363 * is similar to the following computation: <code>getLeft() + getWidth()</code>
364 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
365 * </p>
366 *
367 * <a name="SizePaddingMargins"></a>
368 * <h3>Size, padding and margins</h3>
369 * <p>
370 * The size of a view is expressed with a width and a height. A view actually
371 * possess two pairs of width and height values.
372 * </p>
373 *
374 * <p>
375 * The first pair is known as <em>measured width</em> and
376 * <em>measured height</em>. These dimensions define how big a view wants to be
377 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
378 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
379 * and {@link #getMeasuredHeight()}.
380 * </p>
381 *
382 * <p>
383 * The second pair is simply known as <em>width</em> and <em>height</em>, or
384 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
385 * dimensions define the actual size of the view on screen, at drawing time and
386 * after layout. These values may, but do not have to, be different from the
387 * measured width and height. The width and height can be obtained by calling
388 * {@link #getWidth()} and {@link #getHeight()}.
389 * </p>
390 *
391 * <p>
392 * To measure its dimensions, a view takes into account its padding. The padding
393 * is expressed in pixels for the left, top, right and bottom parts of the view.
394 * Padding can be used to offset the content of the view by a specific amount of
395 * pixels. For instance, a left padding of 2 will push the view's content by
396 * 2 pixels to the right of the left edge. Padding can be set using the
397 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
398 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
399 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
400 * {@link #getPaddingEnd()}.
401 * </p>
402 *
403 * <p>
404 * Even though a view can define a padding, it does not provide any support for
405 * margins. However, view groups provide such a support. Refer to
406 * {@link android.view.ViewGroup} and
407 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
408 * </p>
409 *
410 * <a name="Layout"></a>
411 * <h3>Layout</h3>
412 * <p>
413 * Layout is a two pass process: a measure pass and a layout pass. The measuring
414 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
415 * of the view tree. Each view pushes dimension specifications down the tree
416 * during the recursion. At the end of the measure pass, every view has stored
417 * its measurements. The second pass happens in
418 * {@link #layout(int,int,int,int)} and is also top-down. During
419 * this pass each parent is responsible for positioning all of its children
420 * using the sizes computed in the measure pass.
421 * </p>
422 *
423 * <p>
424 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
425 * {@link #getMeasuredHeight()} values must be set, along with those for all of
426 * that view's descendants. A view's measured width and measured height values
427 * must respect the constraints imposed by the view's parents. This guarantees
428 * that at the end of the measure pass, all parents accept all of their
429 * children's measurements. A parent view may call measure() more than once on
430 * its children. For example, the parent may measure each child once with
431 * unspecified dimensions to find out how big they want to be, then call
432 * measure() on them again with actual numbers if the sum of all the children's
433 * unconstrained sizes is too big or too small.
434 * </p>
435 *
436 * <p>
437 * The measure pass uses two classes to communicate dimensions. The
438 * {@link MeasureSpec} class is used by views to tell their parents how they
439 * want to be measured and positioned. The base LayoutParams class just
440 * describes how big the view wants to be for both width and height. For each
441 * dimension, it can specify one of:
442 * <ul>
443 * <li> an exact number
444 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
445 * (minus padding)
446 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
447 * enclose its content (plus padding).
448 * </ul>
449 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
450 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
451 * an X and Y value.
452 * </p>
453 *
454 * <p>
455 * MeasureSpecs are used to push requirements down the tree from parent to
456 * child. A MeasureSpec can be in one of three modes:
457 * <ul>
458 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
459 * of a child view. For example, a LinearLayout may call measure() on its child
460 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
461 * tall the child view wants to be given a width of 240 pixels.
462 * <li>EXACTLY: This is used by the parent to impose an exact size on the
463 * child. The child must use this size, and guarantee that all of its
464 * descendants will fit within this size.
465 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
466 * child. The child must guarantee that it and all of its descendants will fit
467 * within this size.
468 * </ul>
469 * </p>
470 *
471 * <p>
472 * To initiate a layout, call {@link #requestLayout}. This method is typically
473 * called by a view on itself when it believes that is can no longer fit within
474 * its current bounds.
475 * </p>
476 *
477 * <a name="Drawing"></a>
478 * <h3>Drawing</h3>
479 * <p>
480 * Drawing is handled by walking the tree and recording the drawing commands of
481 * any View that needs to update. After this, the drawing commands of the
482 * entire tree are issued to screen, clipped to the newly damaged area.
483 * </p>
484 *
485 * <p>
486 * The tree is largely recorded and drawn in order, with parents drawn before
487 * (i.e., behind) their children, with siblings drawn in the order they appear
488 * in the tree. If you set a background drawable for a View, then the View will
489 * draw it before calling back to its <code>onDraw()</code> method. The child
490 * drawing order can be overridden with
491 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
492 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
493 * </p>
494 *
495 * <p>
496 * To force a view to draw, call {@link #invalidate()}.
497 * </p>
498 *
499 * <a name="EventHandlingThreading"></a>
500 * <h3>Event Handling and Threading</h3>
501 * <p>
502 * The basic cycle of a view is as follows:
503 * <ol>
504 * <li>An event comes in and is dispatched to the appropriate view. The view
505 * handles the event and notifies any listeners.</li>
506 * <li>If in the course of processing the event, the view's bounds may need
507 * to be changed, the view will call {@link #requestLayout()}.</li>
508 * <li>Similarly, if in the course of processing the event the view's appearance
509 * may need to be changed, the view will call {@link #invalidate()}.</li>
510 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
511 * the framework will take care of measuring, laying out, and drawing the tree
512 * as appropriate.</li>
513 * </ol>
514 * </p>
515 *
516 * <p><em>Note: The entire view tree is single threaded. You must always be on
517 * the UI thread when calling any method on any view.</em>
518 * If you are doing work on other threads and want to update the state of a view
519 * from that thread, you should use a {@link Handler}.
520 * </p>
521 *
522 * <a name="FocusHandling"></a>
523 * <h3>Focus Handling</h3>
524 * <p>
525 * The framework will handle routine focus movement in response to user input.
526 * This includes changing the focus as views are removed or hidden, or as new
527 * views become available. Views indicate their willingness to take focus
528 * through the {@link #isFocusable} method. To change whether a view can take
529 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
530 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
531 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
532 * </p>
533 * <p>
534 * Focus movement is based on an algorithm which finds the nearest neighbor in a
535 * given direction. In rare cases, the default algorithm may not match the
536 * intended behavior of the developer. In these situations, you can provide
537 * explicit overrides by using these XML attributes in the layout file:
538 * <pre>
539 * nextFocusDown
540 * nextFocusLeft
541 * nextFocusRight
542 * nextFocusUp
543 * </pre>
544 * </p>
545 *
546 *
547 * <p>
548 * To get a particular view to take focus, call {@link #requestFocus()}.
549 * </p>
550 *
551 * <a name="TouchMode"></a>
552 * <h3>Touch Mode</h3>
553 * <p>
554 * When a user is navigating a user interface via directional keys such as a D-pad, it is
555 * necessary to give focus to actionable items such as buttons so the user can see
556 * what will take input.  If the device has touch capabilities, however, and the user
557 * begins interacting with the interface by touching it, it is no longer necessary to
558 * always highlight, or give focus to, a particular view.  This motivates a mode
559 * for interaction named 'touch mode'.
560 * </p>
561 * <p>
562 * For a touch capable device, once the user touches the screen, the device
563 * will enter touch mode.  From this point onward, only views for which
564 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
565 * Other views that are touchable, like buttons, will not take focus when touched; they will
566 * only fire the on click listeners.
567 * </p>
568 * <p>
569 * Any time a user hits a directional key, such as a D-pad direction, the view device will
570 * exit touch mode, and find a view to take focus, so that the user may resume interacting
571 * with the user interface without touching the screen again.
572 * </p>
573 * <p>
574 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
575 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
576 * </p>
577 *
578 * <a name="Scrolling"></a>
579 * <h3>Scrolling</h3>
580 * <p>
581 * The framework provides basic support for views that wish to internally
582 * scroll their content. This includes keeping track of the X and Y scroll
583 * offset as well as mechanisms for drawing scrollbars. See
584 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
585 * {@link #awakenScrollBars()} for more details.
586 * </p>
587 *
588 * <a name="Tags"></a>
589 * <h3>Tags</h3>
590 * <p>
591 * Unlike IDs, tags are not used to identify views. Tags are essentially an
592 * extra piece of information that can be associated with a view. They are most
593 * often used as a convenience to store data related to views in the views
594 * themselves rather than by putting them in a separate structure.
595 * </p>
596 * <p>
597 * Tags may be specified with character sequence values in layout XML as either
598 * a single tag using the {@link android.R.styleable#View_tag android:tag}
599 * attribute or multiple tags using the {@code <tag>} child element:
600 * <pre>
601 *     &ltView ...
602 *           android:tag="@string/mytag_value" /&gt;
603 *     &ltView ...&gt;
604 *         &lttag android:id="@+id/mytag"
605 *              android:value="@string/mytag_value" /&gt;
606 *     &lt/View>
607 * </pre>
608 * </p>
609 * <p>
610 * Tags may also be specified with arbitrary objects from code using
611 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
612 * </p>
613 *
614 * <a name="Themes"></a>
615 * <h3>Themes</h3>
616 * <p>
617 * By default, Views are created using the theme of the Context object supplied
618 * to their constructor; however, a different theme may be specified by using
619 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
620 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
621 * code.
622 * </p>
623 * <p>
624 * When the {@link android.R.styleable#View_theme android:theme} attribute is
625 * used in XML, the specified theme is applied on top of the inflation
626 * context's theme (see {@link LayoutInflater}) and used for the view itself as
627 * well as any child elements.
628 * </p>
629 * <p>
630 * In the following example, both views will be created using the Material dark
631 * color scheme; however, because an overlay theme is used which only defines a
632 * subset of attributes, the value of
633 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
634 * the inflation context's theme (e.g. the Activity theme) will be preserved.
635 * <pre>
636 *     &ltLinearLayout
637 *             ...
638 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
639 *         &ltView ...&gt;
640 *     &lt/LinearLayout&gt;
641 * </pre>
642 * </p>
643 *
644 * <a name="Properties"></a>
645 * <h3>Properties</h3>
646 * <p>
647 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
648 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
649 * available both in the {@link Property} form as well as in similarly-named setter/getter
650 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
651 * be used to set persistent state associated with these rendering-related properties on the view.
652 * The properties and methods can also be used in conjunction with
653 * {@link android.animation.Animator Animator}-based animations, described more in the
654 * <a href="#Animation">Animation</a> section.
655 * </p>
656 *
657 * <a name="Animation"></a>
658 * <h3>Animation</h3>
659 * <p>
660 * Starting with Android 3.0, the preferred way of animating views is to use the
661 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
662 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
663 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
664 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
665 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
666 * makes animating these View properties particularly easy and efficient.
667 * </p>
668 * <p>
669 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
670 * You can attach an {@link Animation} object to a view using
671 * {@link #setAnimation(Animation)} or
672 * {@link #startAnimation(Animation)}. The animation can alter the scale,
673 * rotation, translation and alpha of a view over time. If the animation is
674 * attached to a view that has children, the animation will affect the entire
675 * subtree rooted by that node. When an animation is started, the framework will
676 * take care of redrawing the appropriate views until the animation completes.
677 * </p>
678 *
679 * <a name="Security"></a>
680 * <h3>Security</h3>
681 * <p>
682 * Sometimes it is essential that an application be able to verify that an action
683 * is being performed with the full knowledge and consent of the user, such as
684 * granting a permission request, making a purchase or clicking on an advertisement.
685 * Unfortunately, a malicious application could try to spoof the user into
686 * performing these actions, unaware, by concealing the intended purpose of the view.
687 * As a remedy, the framework offers a touch filtering mechanism that can be used to
688 * improve the security of views that provide access to sensitive functionality.
689 * </p><p>
690 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
691 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
692 * will discard touches that are received whenever the view's window is obscured by
693 * another visible window.  As a result, the view will not receive touches whenever a
694 * toast, dialog or other window appears above the view's window.
695 * </p><p>
696 * For more fine-grained control over security, consider overriding the
697 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
698 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
699 * </p>
700 *
701 * @attr ref android.R.styleable#View_alpha
702 * @attr ref android.R.styleable#View_background
703 * @attr ref android.R.styleable#View_clickable
704 * @attr ref android.R.styleable#View_contentDescription
705 * @attr ref android.R.styleable#View_drawingCacheQuality
706 * @attr ref android.R.styleable#View_duplicateParentState
707 * @attr ref android.R.styleable#View_id
708 * @attr ref android.R.styleable#View_requiresFadingEdge
709 * @attr ref android.R.styleable#View_fadeScrollbars
710 * @attr ref android.R.styleable#View_fadingEdgeLength
711 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
712 * @attr ref android.R.styleable#View_fitsSystemWindows
713 * @attr ref android.R.styleable#View_isScrollContainer
714 * @attr ref android.R.styleable#View_focusable
715 * @attr ref android.R.styleable#View_focusableInTouchMode
716 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
717 * @attr ref android.R.styleable#View_keepScreenOn
718 * @attr ref android.R.styleable#View_layerType
719 * @attr ref android.R.styleable#View_layoutDirection
720 * @attr ref android.R.styleable#View_longClickable
721 * @attr ref android.R.styleable#View_minHeight
722 * @attr ref android.R.styleable#View_minWidth
723 * @attr ref android.R.styleable#View_nextFocusDown
724 * @attr ref android.R.styleable#View_nextFocusLeft
725 * @attr ref android.R.styleable#View_nextFocusRight
726 * @attr ref android.R.styleable#View_nextFocusUp
727 * @attr ref android.R.styleable#View_onClick
728 * @attr ref android.R.styleable#View_padding
729 * @attr ref android.R.styleable#View_paddingBottom
730 * @attr ref android.R.styleable#View_paddingLeft
731 * @attr ref android.R.styleable#View_paddingRight
732 * @attr ref android.R.styleable#View_paddingTop
733 * @attr ref android.R.styleable#View_paddingStart
734 * @attr ref android.R.styleable#View_paddingEnd
735 * @attr ref android.R.styleable#View_saveEnabled
736 * @attr ref android.R.styleable#View_rotation
737 * @attr ref android.R.styleable#View_rotationX
738 * @attr ref android.R.styleable#View_rotationY
739 * @attr ref android.R.styleable#View_scaleX
740 * @attr ref android.R.styleable#View_scaleY
741 * @attr ref android.R.styleable#View_scrollX
742 * @attr ref android.R.styleable#View_scrollY
743 * @attr ref android.R.styleable#View_scrollbarSize
744 * @attr ref android.R.styleable#View_scrollbarStyle
745 * @attr ref android.R.styleable#View_scrollbars
746 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
747 * @attr ref android.R.styleable#View_scrollbarFadeDuration
748 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
749 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
750 * @attr ref android.R.styleable#View_scrollbarThumbVertical
751 * @attr ref android.R.styleable#View_scrollbarTrackVertical
752 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
753 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
754 * @attr ref android.R.styleable#View_stateListAnimator
755 * @attr ref android.R.styleable#View_transitionName
756 * @attr ref android.R.styleable#View_soundEffectsEnabled
757 * @attr ref android.R.styleable#View_tag
758 * @attr ref android.R.styleable#View_textAlignment
759 * @attr ref android.R.styleable#View_textDirection
760 * @attr ref android.R.styleable#View_transformPivotX
761 * @attr ref android.R.styleable#View_transformPivotY
762 * @attr ref android.R.styleable#View_translationX
763 * @attr ref android.R.styleable#View_translationY
764 * @attr ref android.R.styleable#View_translationZ
765 * @attr ref android.R.styleable#View_visibility
766 * @attr ref android.R.styleable#View_theme
767 *
768 * @see android.view.ViewGroup
769 */
770@UiThread
771public class View implements Drawable.Callback, KeyEvent.Callback,
772        AccessibilityEventSource {
773    private static final boolean DBG = false;
774
775    /** @hide */
776    public static boolean DEBUG_DRAW = false;
777
778    /**
779     * The logging tag used by this class with android.util.Log.
780     */
781    protected static final String VIEW_LOG_TAG = "View";
782
783    /**
784     * When set to true, apps will draw debugging information about their layouts.
785     *
786     * @hide
787     */
788    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
789
790    /**
791     * When set to true, this view will save its attribute data.
792     *
793     * @hide
794     */
795    public static boolean mDebugViewAttributes = false;
796
797    /**
798     * Used to mark a View that has no ID.
799     */
800    public static final int NO_ID = -1;
801
802    /**
803     * Signals that compatibility booleans have been initialized according to
804     * target SDK versions.
805     */
806    private static boolean sCompatibilityDone = false;
807
808    /**
809     * Use the old (broken) way of building MeasureSpecs.
810     */
811    private static boolean sUseBrokenMakeMeasureSpec = false;
812
813    /**
814     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
815     */
816    static boolean sUseZeroUnspecifiedMeasureSpec = false;
817
818    /**
819     * Ignore any optimizations using the measure cache.
820     */
821    private static boolean sIgnoreMeasureCache = false;
822
823    /**
824     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
825     */
826    private static boolean sAlwaysRemeasureExactly = false;
827
828    /**
829     * Relax constraints around whether setLayoutParams() must be called after
830     * modifying the layout params.
831     */
832    private static boolean sLayoutParamsAlwaysChanged = false;
833
834    /**
835     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
836     * without throwing
837     */
838    static boolean sTextureViewIgnoresDrawableSetters = false;
839
840    /**
841     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
842     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
843     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
844     * check is implemented for backwards compatibility.
845     *
846     * {@hide}
847     */
848    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
849
850    /**
851     * Prior to N, when drag enters into child of a view that has already received an
852     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
853     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
854     * false from its event handler for these events.
855     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
856     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
857     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
858     */
859    static boolean sCascadedDragDrop;
860
861    /** @hide */
862    @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO})
863    @Retention(RetentionPolicy.SOURCE)
864    public @interface Focusable {}
865
866    /**
867     * This view does not want keystrokes.
868     * <p>
869     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
870     * android:focusable}.
871     */
872    public static final int NOT_FOCUSABLE = 0x00000000;
873
874    /**
875     * This view wants keystrokes.
876     * <p>
877     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
878     * android:focusable}.
879     */
880    public static final int FOCUSABLE = 0x00000001;
881
882    /**
883     * This view determines focusability automatically. This is the default.
884     * <p>
885     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
886     * android:focusable}.
887     */
888    public static final int FOCUSABLE_AUTO = 0x00000010;
889
890    /**
891     * Mask for use with setFlags indicating bits used for focus.
892     */
893    private static final int FOCUSABLE_MASK = 0x00000011;
894
895    /**
896     * This view will adjust its padding to fit sytem windows (e.g. status bar)
897     */
898    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
899
900    /** @hide */
901    @IntDef({VISIBLE, INVISIBLE, GONE})
902    @Retention(RetentionPolicy.SOURCE)
903    public @interface Visibility {}
904
905    /**
906     * This view is visible.
907     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
908     * android:visibility}.
909     */
910    public static final int VISIBLE = 0x00000000;
911
912    /**
913     * This view is invisible, but it still takes up space for layout purposes.
914     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
915     * android:visibility}.
916     */
917    public static final int INVISIBLE = 0x00000004;
918
919    /**
920     * This view is invisible, and it doesn't take any space for layout
921     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
922     * android:visibility}.
923     */
924    public static final int GONE = 0x00000008;
925
926    /**
927     * Mask for use with setFlags indicating bits used for visibility.
928     * {@hide}
929     */
930    static final int VISIBILITY_MASK = 0x0000000C;
931
932    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
933
934    /**
935     * This view is enabled. Interpretation varies by subclass.
936     * Use with ENABLED_MASK when calling setFlags.
937     * {@hide}
938     */
939    static final int ENABLED = 0x00000000;
940
941    /**
942     * This view is disabled. Interpretation varies by subclass.
943     * Use with ENABLED_MASK when calling setFlags.
944     * {@hide}
945     */
946    static final int DISABLED = 0x00000020;
947
948   /**
949    * Mask for use with setFlags indicating bits used for indicating whether
950    * this view is enabled
951    * {@hide}
952    */
953    static final int ENABLED_MASK = 0x00000020;
954
955    /**
956     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
957     * called and further optimizations will be performed. It is okay to have
958     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
959     * {@hide}
960     */
961    static final int WILL_NOT_DRAW = 0x00000080;
962
963    /**
964     * Mask for use with setFlags indicating bits used for indicating whether
965     * this view is will draw
966     * {@hide}
967     */
968    static final int DRAW_MASK = 0x00000080;
969
970    /**
971     * <p>This view doesn't show scrollbars.</p>
972     * {@hide}
973     */
974    static final int SCROLLBARS_NONE = 0x00000000;
975
976    /**
977     * <p>This view shows horizontal scrollbars.</p>
978     * {@hide}
979     */
980    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
981
982    /**
983     * <p>This view shows vertical scrollbars.</p>
984     * {@hide}
985     */
986    static final int SCROLLBARS_VERTICAL = 0x00000200;
987
988    /**
989     * <p>Mask for use with setFlags indicating bits used for indicating which
990     * scrollbars are enabled.</p>
991     * {@hide}
992     */
993    static final int SCROLLBARS_MASK = 0x00000300;
994
995    /**
996     * Indicates that the view should filter touches when its window is obscured.
997     * Refer to the class comments for more information about this security feature.
998     * {@hide}
999     */
1000    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
1001
1002    /**
1003     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
1004     * that they are optional and should be skipped if the window has
1005     * requested system UI flags that ignore those insets for layout.
1006     */
1007    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
1008
1009    /**
1010     * <p>This view doesn't show fading edges.</p>
1011     * {@hide}
1012     */
1013    static final int FADING_EDGE_NONE = 0x00000000;
1014
1015    /**
1016     * <p>This view shows horizontal fading edges.</p>
1017     * {@hide}
1018     */
1019    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1020
1021    /**
1022     * <p>This view shows vertical fading edges.</p>
1023     * {@hide}
1024     */
1025    static final int FADING_EDGE_VERTICAL = 0x00002000;
1026
1027    /**
1028     * <p>Mask for use with setFlags indicating bits used for indicating which
1029     * fading edges are enabled.</p>
1030     * {@hide}
1031     */
1032    static final int FADING_EDGE_MASK = 0x00003000;
1033
1034    /**
1035     * <p>Indicates this view can be clicked. When clickable, a View reacts
1036     * to clicks by notifying the OnClickListener.<p>
1037     * {@hide}
1038     */
1039    static final int CLICKABLE = 0x00004000;
1040
1041    /**
1042     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1043     * {@hide}
1044     */
1045    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1046
1047    /**
1048     * <p>Indicates that no icicle should be saved for this view.<p>
1049     * {@hide}
1050     */
1051    static final int SAVE_DISABLED = 0x000010000;
1052
1053    /**
1054     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1055     * property.</p>
1056     * {@hide}
1057     */
1058    static final int SAVE_DISABLED_MASK = 0x000010000;
1059
1060    /**
1061     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1062     * {@hide}
1063     */
1064    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1065
1066    /**
1067     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1068     * {@hide}
1069     */
1070    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1071
1072    /** @hide */
1073    @Retention(RetentionPolicy.SOURCE)
1074    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1075    public @interface DrawingCacheQuality {}
1076
1077    /**
1078     * <p>Enables low quality mode for the drawing cache.</p>
1079     */
1080    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1081
1082    /**
1083     * <p>Enables high quality mode for the drawing cache.</p>
1084     */
1085    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1086
1087    /**
1088     * <p>Enables automatic quality mode for the drawing cache.</p>
1089     */
1090    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1091
1092    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1093            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1094    };
1095
1096    /**
1097     * <p>Mask for use with setFlags indicating bits used for the cache
1098     * quality property.</p>
1099     * {@hide}
1100     */
1101    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1102
1103    /**
1104     * <p>
1105     * Indicates this view can be long clicked. When long clickable, a View
1106     * reacts to long clicks by notifying the OnLongClickListener or showing a
1107     * context menu.
1108     * </p>
1109     * {@hide}
1110     */
1111    static final int LONG_CLICKABLE = 0x00200000;
1112
1113    /**
1114     * <p>Indicates that this view gets its drawable states from its direct parent
1115     * and ignores its original internal states.</p>
1116     *
1117     * @hide
1118     */
1119    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1120
1121    /**
1122     * <p>
1123     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1124     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1125     * OnContextClickListener.
1126     * </p>
1127     * {@hide}
1128     */
1129    static final int CONTEXT_CLICKABLE = 0x00800000;
1130
1131
1132    /** @hide */
1133    @IntDef({
1134        SCROLLBARS_INSIDE_OVERLAY,
1135        SCROLLBARS_INSIDE_INSET,
1136        SCROLLBARS_OUTSIDE_OVERLAY,
1137        SCROLLBARS_OUTSIDE_INSET
1138    })
1139    @Retention(RetentionPolicy.SOURCE)
1140    public @interface ScrollBarStyle {}
1141
1142    /**
1143     * The scrollbar style to display the scrollbars inside the content area,
1144     * without increasing the padding. The scrollbars will be overlaid with
1145     * translucency on the view's content.
1146     */
1147    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1148
1149    /**
1150     * The scrollbar style to display the scrollbars inside the padded area,
1151     * increasing the padding of the view. The scrollbars will not overlap the
1152     * content area of the view.
1153     */
1154    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1155
1156    /**
1157     * The scrollbar style to display the scrollbars at the edge of the view,
1158     * without increasing the padding. The scrollbars will be overlaid with
1159     * translucency.
1160     */
1161    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1162
1163    /**
1164     * The scrollbar style to display the scrollbars at the edge of the view,
1165     * increasing the padding of the view. The scrollbars will only overlap the
1166     * background, if any.
1167     */
1168    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1169
1170    /**
1171     * Mask to check if the scrollbar style is overlay or inset.
1172     * {@hide}
1173     */
1174    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1175
1176    /**
1177     * Mask to check if the scrollbar style is inside or outside.
1178     * {@hide}
1179     */
1180    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1181
1182    /**
1183     * Mask for scrollbar style.
1184     * {@hide}
1185     */
1186    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1187
1188    /**
1189     * View flag indicating that the screen should remain on while the
1190     * window containing this view is visible to the user.  This effectively
1191     * takes care of automatically setting the WindowManager's
1192     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1193     */
1194    public static final int KEEP_SCREEN_ON = 0x04000000;
1195
1196    /**
1197     * View flag indicating whether this view should have sound effects enabled
1198     * for events such as clicking and touching.
1199     */
1200    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1201
1202    /**
1203     * View flag indicating whether this view should have haptic feedback
1204     * enabled for events such as long presses.
1205     */
1206    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1207
1208    /**
1209     * <p>Indicates that the view hierarchy should stop saving state when
1210     * it reaches this view.  If state saving is initiated immediately at
1211     * the view, it will be allowed.
1212     * {@hide}
1213     */
1214    static final int PARENT_SAVE_DISABLED = 0x20000000;
1215
1216    /**
1217     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1218     * {@hide}
1219     */
1220    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1221
1222    private static Paint sDebugPaint;
1223
1224    /**
1225     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1226     * {@hide}
1227     */
1228    static final int TOOLTIP = 0x40000000;
1229
1230    /** @hide */
1231    @IntDef(flag = true,
1232            value = {
1233                FOCUSABLES_ALL,
1234                FOCUSABLES_TOUCH_MODE
1235            })
1236    @Retention(RetentionPolicy.SOURCE)
1237    public @interface FocusableMode {}
1238
1239    /**
1240     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1241     * should add all focusable Views regardless if they are focusable in touch mode.
1242     */
1243    public static final int FOCUSABLES_ALL = 0x00000000;
1244
1245    /**
1246     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1247     * should add only Views focusable in touch mode.
1248     */
1249    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1250
1251    /** @hide */
1252    @IntDef({
1253            FOCUS_BACKWARD,
1254            FOCUS_FORWARD,
1255            FOCUS_LEFT,
1256            FOCUS_UP,
1257            FOCUS_RIGHT,
1258            FOCUS_DOWN
1259    })
1260    @Retention(RetentionPolicy.SOURCE)
1261    public @interface FocusDirection {}
1262
1263    /** @hide */
1264    @IntDef({
1265            FOCUS_LEFT,
1266            FOCUS_UP,
1267            FOCUS_RIGHT,
1268            FOCUS_DOWN
1269    })
1270    @Retention(RetentionPolicy.SOURCE)
1271    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1272
1273    /**
1274     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1275     * item.
1276     */
1277    public static final int FOCUS_BACKWARD = 0x00000001;
1278
1279    /**
1280     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1281     * item.
1282     */
1283    public static final int FOCUS_FORWARD = 0x00000002;
1284
1285    /**
1286     * Use with {@link #focusSearch(int)}. Move focus to the left.
1287     */
1288    public static final int FOCUS_LEFT = 0x00000011;
1289
1290    /**
1291     * Use with {@link #focusSearch(int)}. Move focus up.
1292     */
1293    public static final int FOCUS_UP = 0x00000021;
1294
1295    /**
1296     * Use with {@link #focusSearch(int)}. Move focus to the right.
1297     */
1298    public static final int FOCUS_RIGHT = 0x00000042;
1299
1300    /**
1301     * Use with {@link #focusSearch(int)}. Move focus down.
1302     */
1303    public static final int FOCUS_DOWN = 0x00000082;
1304
1305    /**
1306     * Bits of {@link #getMeasuredWidthAndState()} and
1307     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1308     */
1309    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1310
1311    /**
1312     * Bits of {@link #getMeasuredWidthAndState()} and
1313     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1314     */
1315    public static final int MEASURED_STATE_MASK = 0xff000000;
1316
1317    /**
1318     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1319     * for functions that combine both width and height into a single int,
1320     * such as {@link #getMeasuredState()} and the childState argument of
1321     * {@link #resolveSizeAndState(int, int, int)}.
1322     */
1323    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1324
1325    /**
1326     * Bit of {@link #getMeasuredWidthAndState()} and
1327     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1328     * is smaller that the space the view would like to have.
1329     */
1330    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1331
1332    /**
1333     * Base View state sets
1334     */
1335    // Singles
1336    /**
1337     * Indicates the view has no states set. States are used with
1338     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1339     * view depending on its state.
1340     *
1341     * @see android.graphics.drawable.Drawable
1342     * @see #getDrawableState()
1343     */
1344    protected static final int[] EMPTY_STATE_SET;
1345    /**
1346     * Indicates the view is enabled. States are used with
1347     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1348     * view depending on its state.
1349     *
1350     * @see android.graphics.drawable.Drawable
1351     * @see #getDrawableState()
1352     */
1353    protected static final int[] ENABLED_STATE_SET;
1354    /**
1355     * Indicates the view is focused. States are used with
1356     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1357     * view depending on its state.
1358     *
1359     * @see android.graphics.drawable.Drawable
1360     * @see #getDrawableState()
1361     */
1362    protected static final int[] FOCUSED_STATE_SET;
1363    /**
1364     * Indicates the view is selected. States are used with
1365     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1366     * view depending on its state.
1367     *
1368     * @see android.graphics.drawable.Drawable
1369     * @see #getDrawableState()
1370     */
1371    protected static final int[] SELECTED_STATE_SET;
1372    /**
1373     * Indicates the view is pressed. States are used with
1374     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1375     * view depending on its state.
1376     *
1377     * @see android.graphics.drawable.Drawable
1378     * @see #getDrawableState()
1379     */
1380    protected static final int[] PRESSED_STATE_SET;
1381    /**
1382     * Indicates the view's window has focus. States are used with
1383     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1384     * view depending on its state.
1385     *
1386     * @see android.graphics.drawable.Drawable
1387     * @see #getDrawableState()
1388     */
1389    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1390    // Doubles
1391    /**
1392     * Indicates the view is enabled and has the focus.
1393     *
1394     * @see #ENABLED_STATE_SET
1395     * @see #FOCUSED_STATE_SET
1396     */
1397    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1398    /**
1399     * Indicates the view is enabled and selected.
1400     *
1401     * @see #ENABLED_STATE_SET
1402     * @see #SELECTED_STATE_SET
1403     */
1404    protected static final int[] ENABLED_SELECTED_STATE_SET;
1405    /**
1406     * Indicates the view is enabled and that its window has focus.
1407     *
1408     * @see #ENABLED_STATE_SET
1409     * @see #WINDOW_FOCUSED_STATE_SET
1410     */
1411    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1412    /**
1413     * Indicates the view is focused and selected.
1414     *
1415     * @see #FOCUSED_STATE_SET
1416     * @see #SELECTED_STATE_SET
1417     */
1418    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1419    /**
1420     * Indicates the view has the focus and that its window has the focus.
1421     *
1422     * @see #FOCUSED_STATE_SET
1423     * @see #WINDOW_FOCUSED_STATE_SET
1424     */
1425    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1426    /**
1427     * Indicates the view is selected and that its window has the focus.
1428     *
1429     * @see #SELECTED_STATE_SET
1430     * @see #WINDOW_FOCUSED_STATE_SET
1431     */
1432    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1433    // Triples
1434    /**
1435     * Indicates the view is enabled, focused and selected.
1436     *
1437     * @see #ENABLED_STATE_SET
1438     * @see #FOCUSED_STATE_SET
1439     * @see #SELECTED_STATE_SET
1440     */
1441    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1442    /**
1443     * Indicates the view is enabled, focused and its window has the focus.
1444     *
1445     * @see #ENABLED_STATE_SET
1446     * @see #FOCUSED_STATE_SET
1447     * @see #WINDOW_FOCUSED_STATE_SET
1448     */
1449    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1450    /**
1451     * Indicates the view is enabled, selected and its window has the focus.
1452     *
1453     * @see #ENABLED_STATE_SET
1454     * @see #SELECTED_STATE_SET
1455     * @see #WINDOW_FOCUSED_STATE_SET
1456     */
1457    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1458    /**
1459     * Indicates the view is focused, selected and its window has the focus.
1460     *
1461     * @see #FOCUSED_STATE_SET
1462     * @see #SELECTED_STATE_SET
1463     * @see #WINDOW_FOCUSED_STATE_SET
1464     */
1465    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1466    /**
1467     * Indicates the view is enabled, focused, selected and its window
1468     * has the focus.
1469     *
1470     * @see #ENABLED_STATE_SET
1471     * @see #FOCUSED_STATE_SET
1472     * @see #SELECTED_STATE_SET
1473     * @see #WINDOW_FOCUSED_STATE_SET
1474     */
1475    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1476    /**
1477     * Indicates the view is pressed and its window has the focus.
1478     *
1479     * @see #PRESSED_STATE_SET
1480     * @see #WINDOW_FOCUSED_STATE_SET
1481     */
1482    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1483    /**
1484     * Indicates the view is pressed and selected.
1485     *
1486     * @see #PRESSED_STATE_SET
1487     * @see #SELECTED_STATE_SET
1488     */
1489    protected static final int[] PRESSED_SELECTED_STATE_SET;
1490    /**
1491     * Indicates the view is pressed, selected and its window has the focus.
1492     *
1493     * @see #PRESSED_STATE_SET
1494     * @see #SELECTED_STATE_SET
1495     * @see #WINDOW_FOCUSED_STATE_SET
1496     */
1497    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1498    /**
1499     * Indicates the view is pressed and focused.
1500     *
1501     * @see #PRESSED_STATE_SET
1502     * @see #FOCUSED_STATE_SET
1503     */
1504    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1505    /**
1506     * Indicates the view is pressed, focused and its window has the focus.
1507     *
1508     * @see #PRESSED_STATE_SET
1509     * @see #FOCUSED_STATE_SET
1510     * @see #WINDOW_FOCUSED_STATE_SET
1511     */
1512    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1513    /**
1514     * Indicates the view is pressed, focused and selected.
1515     *
1516     * @see #PRESSED_STATE_SET
1517     * @see #SELECTED_STATE_SET
1518     * @see #FOCUSED_STATE_SET
1519     */
1520    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1521    /**
1522     * Indicates the view is pressed, focused, selected and its window has the focus.
1523     *
1524     * @see #PRESSED_STATE_SET
1525     * @see #FOCUSED_STATE_SET
1526     * @see #SELECTED_STATE_SET
1527     * @see #WINDOW_FOCUSED_STATE_SET
1528     */
1529    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1530    /**
1531     * Indicates the view is pressed and enabled.
1532     *
1533     * @see #PRESSED_STATE_SET
1534     * @see #ENABLED_STATE_SET
1535     */
1536    protected static final int[] PRESSED_ENABLED_STATE_SET;
1537    /**
1538     * Indicates the view is pressed, enabled and its window has the focus.
1539     *
1540     * @see #PRESSED_STATE_SET
1541     * @see #ENABLED_STATE_SET
1542     * @see #WINDOW_FOCUSED_STATE_SET
1543     */
1544    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1545    /**
1546     * Indicates the view is pressed, enabled and selected.
1547     *
1548     * @see #PRESSED_STATE_SET
1549     * @see #ENABLED_STATE_SET
1550     * @see #SELECTED_STATE_SET
1551     */
1552    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1553    /**
1554     * Indicates the view is pressed, enabled, selected and its window has the
1555     * focus.
1556     *
1557     * @see #PRESSED_STATE_SET
1558     * @see #ENABLED_STATE_SET
1559     * @see #SELECTED_STATE_SET
1560     * @see #WINDOW_FOCUSED_STATE_SET
1561     */
1562    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1563    /**
1564     * Indicates the view is pressed, enabled and focused.
1565     *
1566     * @see #PRESSED_STATE_SET
1567     * @see #ENABLED_STATE_SET
1568     * @see #FOCUSED_STATE_SET
1569     */
1570    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1571    /**
1572     * Indicates the view is pressed, enabled, focused and its window has the
1573     * focus.
1574     *
1575     * @see #PRESSED_STATE_SET
1576     * @see #ENABLED_STATE_SET
1577     * @see #FOCUSED_STATE_SET
1578     * @see #WINDOW_FOCUSED_STATE_SET
1579     */
1580    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1581    /**
1582     * Indicates the view is pressed, enabled, focused and selected.
1583     *
1584     * @see #PRESSED_STATE_SET
1585     * @see #ENABLED_STATE_SET
1586     * @see #SELECTED_STATE_SET
1587     * @see #FOCUSED_STATE_SET
1588     */
1589    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1590    /**
1591     * Indicates the view is pressed, enabled, focused, selected and its window
1592     * has the focus.
1593     *
1594     * @see #PRESSED_STATE_SET
1595     * @see #ENABLED_STATE_SET
1596     * @see #SELECTED_STATE_SET
1597     * @see #FOCUSED_STATE_SET
1598     * @see #WINDOW_FOCUSED_STATE_SET
1599     */
1600    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1601
1602    static {
1603        EMPTY_STATE_SET = StateSet.get(0);
1604
1605        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1606
1607        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1608        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1609                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1610
1611        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1612        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1613                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1614        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1615                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1616        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1617                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1618                        | StateSet.VIEW_STATE_FOCUSED);
1619
1620        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1621        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1622                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1623        ENABLED_SELECTED_STATE_SET = StateSet.get(
1624                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1625        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1626                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1627                        | StateSet.VIEW_STATE_ENABLED);
1628        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1629                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1630        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1631                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1632                        | StateSet.VIEW_STATE_ENABLED);
1633        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1634                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1635                        | StateSet.VIEW_STATE_ENABLED);
1636        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1637                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1638                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1639
1640        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1641        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1642                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1643        PRESSED_SELECTED_STATE_SET = StateSet.get(
1644                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1645        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1646                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1647                        | StateSet.VIEW_STATE_PRESSED);
1648        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1649                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1650        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1651                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1652                        | StateSet.VIEW_STATE_PRESSED);
1653        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1654                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1655                        | StateSet.VIEW_STATE_PRESSED);
1656        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1657                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1658                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1659        PRESSED_ENABLED_STATE_SET = StateSet.get(
1660                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1661        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1662                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1663                        | StateSet.VIEW_STATE_PRESSED);
1664        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1665                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1666                        | StateSet.VIEW_STATE_PRESSED);
1667        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1668                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1669                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1670        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1671                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1672                        | StateSet.VIEW_STATE_PRESSED);
1673        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1674                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1675                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1676        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1677                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1678                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1679        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1680                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1681                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1682                        | StateSet.VIEW_STATE_PRESSED);
1683    }
1684
1685    /**
1686     * Accessibility event types that are dispatched for text population.
1687     */
1688    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1689            AccessibilityEvent.TYPE_VIEW_CLICKED
1690            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1691            | AccessibilityEvent.TYPE_VIEW_SELECTED
1692            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1693            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1694            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1695            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1696            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1697            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1698            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1699            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1700
1701    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
1702
1703    static final int DEBUG_CORNERS_SIZE_DIP = 8;
1704
1705    /**
1706     * Temporary Rect currently for use in setBackground().  This will probably
1707     * be extended in the future to hold our own class with more than just
1708     * a Rect. :)
1709     */
1710    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1711
1712    /**
1713     * Map used to store views' tags.
1714     */
1715    private SparseArray<Object> mKeyedTags;
1716
1717    /**
1718     * The next available accessibility id.
1719     */
1720    private static int sNextAccessibilityViewId;
1721
1722    /**
1723     * The animation currently associated with this view.
1724     * @hide
1725     */
1726    protected Animation mCurrentAnimation = null;
1727
1728    /**
1729     * Width as measured during measure pass.
1730     * {@hide}
1731     */
1732    @ViewDebug.ExportedProperty(category = "measurement")
1733    int mMeasuredWidth;
1734
1735    /**
1736     * Height as measured during measure pass.
1737     * {@hide}
1738     */
1739    @ViewDebug.ExportedProperty(category = "measurement")
1740    int mMeasuredHeight;
1741
1742    /**
1743     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1744     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1745     * its display list. This flag, used only when hw accelerated, allows us to clear the
1746     * flag while retaining this information until it's needed (at getDisplayList() time and
1747     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1748     *
1749     * {@hide}
1750     */
1751    boolean mRecreateDisplayList = false;
1752
1753    /**
1754     * The view's identifier.
1755     * {@hide}
1756     *
1757     * @see #setId(int)
1758     * @see #getId()
1759     */
1760    @IdRes
1761    @ViewDebug.ExportedProperty(resolveId = true)
1762    int mID = NO_ID;
1763
1764    /**
1765     * The stable ID of this view for accessibility purposes.
1766     */
1767    int mAccessibilityViewId = NO_ID;
1768
1769    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1770
1771    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1772
1773    /**
1774     * The view's tag.
1775     * {@hide}
1776     *
1777     * @see #setTag(Object)
1778     * @see #getTag()
1779     */
1780    protected Object mTag = null;
1781
1782    // for mPrivateFlags:
1783    /** {@hide} */
1784    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1785    /** {@hide} */
1786    static final int PFLAG_FOCUSED                     = 0x00000002;
1787    /** {@hide} */
1788    static final int PFLAG_SELECTED                    = 0x00000004;
1789    /** {@hide} */
1790    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1791    /** {@hide} */
1792    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1793    /** {@hide} */
1794    static final int PFLAG_DRAWN                       = 0x00000020;
1795    /**
1796     * When this flag is set, this view is running an animation on behalf of its
1797     * children and should therefore not cancel invalidate requests, even if they
1798     * lie outside of this view's bounds.
1799     *
1800     * {@hide}
1801     */
1802    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1803    /** {@hide} */
1804    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1805    /** {@hide} */
1806    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1807    /** {@hide} */
1808    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1809    /** {@hide} */
1810    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1811    /** {@hide} */
1812    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1813    /** {@hide} */
1814    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1815
1816    private static final int PFLAG_PRESSED             = 0x00004000;
1817
1818    /** {@hide} */
1819    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1820    /**
1821     * Flag used to indicate that this view should be drawn once more (and only once
1822     * more) after its animation has completed.
1823     * {@hide}
1824     */
1825    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1826
1827    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1828
1829    /**
1830     * Indicates that the View returned true when onSetAlpha() was called and that
1831     * the alpha must be restored.
1832     * {@hide}
1833     */
1834    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1835
1836    /**
1837     * Set by {@link #setScrollContainer(boolean)}.
1838     */
1839    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1840
1841    /**
1842     * Set by {@link #setScrollContainer(boolean)}.
1843     */
1844    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1845
1846    /**
1847     * View flag indicating whether this view was invalidated (fully or partially.)
1848     *
1849     * @hide
1850     */
1851    static final int PFLAG_DIRTY                       = 0x00200000;
1852
1853    /**
1854     * View flag indicating whether this view was invalidated by an opaque
1855     * invalidate request.
1856     *
1857     * @hide
1858     */
1859    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1860
1861    /**
1862     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1863     *
1864     * @hide
1865     */
1866    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1867
1868    /**
1869     * Indicates whether the background is opaque.
1870     *
1871     * @hide
1872     */
1873    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1874
1875    /**
1876     * Indicates whether the scrollbars are opaque.
1877     *
1878     * @hide
1879     */
1880    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1881
1882    /**
1883     * Indicates whether the view is opaque.
1884     *
1885     * @hide
1886     */
1887    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1888
1889    /**
1890     * Indicates a prepressed state;
1891     * the short time between ACTION_DOWN and recognizing
1892     * a 'real' press. Prepressed is used to recognize quick taps
1893     * even when they are shorter than ViewConfiguration.getTapTimeout().
1894     *
1895     * @hide
1896     */
1897    private static final int PFLAG_PREPRESSED          = 0x02000000;
1898
1899    /**
1900     * Indicates whether the view is temporarily detached.
1901     *
1902     * @hide
1903     */
1904    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1905
1906    /**
1907     * Indicates that we should awaken scroll bars once attached
1908     *
1909     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1910     * during window attachment and it is no longer needed. Feel free to repurpose it.
1911     *
1912     * @hide
1913     */
1914    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1915
1916    /**
1917     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1918     * @hide
1919     */
1920    private static final int PFLAG_HOVERED             = 0x10000000;
1921
1922    /**
1923     * no longer needed, should be reused
1924     */
1925    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1926
1927    /** {@hide} */
1928    static final int PFLAG_ACTIVATED                   = 0x40000000;
1929
1930    /**
1931     * Indicates that this view was specifically invalidated, not just dirtied because some
1932     * child view was invalidated. The flag is used to determine when we need to recreate
1933     * a view's display list (as opposed to just returning a reference to its existing
1934     * display list).
1935     *
1936     * @hide
1937     */
1938    static final int PFLAG_INVALIDATED                 = 0x80000000;
1939
1940    /**
1941     * Masks for mPrivateFlags2, as generated by dumpFlags():
1942     *
1943     * |-------|-------|-------|-------|
1944     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1945     *                                1  PFLAG2_DRAG_HOVERED
1946     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1947     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1948     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1949     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1950     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1951     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1952     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1953     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1954     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1955     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1956     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1957     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1958     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1959     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1960     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1961     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1962     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1963     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1964     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1965     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1966     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1967     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1968     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1969     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1970     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1971     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1972     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1973     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1974     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1975     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1976     *    1                              PFLAG2_PADDING_RESOLVED
1977     *   1                               PFLAG2_DRAWABLE_RESOLVED
1978     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1979     * |-------|-------|-------|-------|
1980     */
1981
1982    /**
1983     * Indicates that this view has reported that it can accept the current drag's content.
1984     * Cleared when the drag operation concludes.
1985     * @hide
1986     */
1987    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1988
1989    /**
1990     * Indicates that this view is currently directly under the drag location in a
1991     * drag-and-drop operation involving content that it can accept.  Cleared when
1992     * the drag exits the view, or when the drag operation concludes.
1993     * @hide
1994     */
1995    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1996
1997    /** @hide */
1998    @IntDef({
1999        LAYOUT_DIRECTION_LTR,
2000        LAYOUT_DIRECTION_RTL,
2001        LAYOUT_DIRECTION_INHERIT,
2002        LAYOUT_DIRECTION_LOCALE
2003    })
2004    @Retention(RetentionPolicy.SOURCE)
2005    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2006    public @interface LayoutDir {}
2007
2008    /** @hide */
2009    @IntDef({
2010        LAYOUT_DIRECTION_LTR,
2011        LAYOUT_DIRECTION_RTL
2012    })
2013    @Retention(RetentionPolicy.SOURCE)
2014    public @interface ResolvedLayoutDir {}
2015
2016    /**
2017     * A flag to indicate that the layout direction of this view has not been defined yet.
2018     * @hide
2019     */
2020    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2021
2022    /**
2023     * Horizontal layout direction of this view is from Left to Right.
2024     * Use with {@link #setLayoutDirection}.
2025     */
2026    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2027
2028    /**
2029     * Horizontal layout direction of this view is from Right to Left.
2030     * Use with {@link #setLayoutDirection}.
2031     */
2032    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2033
2034    /**
2035     * Horizontal layout direction of this view is inherited from its parent.
2036     * Use with {@link #setLayoutDirection}.
2037     */
2038    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2039
2040    /**
2041     * Horizontal layout direction of this view is from deduced from the default language
2042     * script for the locale. Use with {@link #setLayoutDirection}.
2043     */
2044    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2045
2046    /**
2047     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2048     * @hide
2049     */
2050    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2051
2052    /**
2053     * Mask for use with private flags indicating bits used for horizontal layout direction.
2054     * @hide
2055     */
2056    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2057
2058    /**
2059     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2060     * right-to-left direction.
2061     * @hide
2062     */
2063    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2064
2065    /**
2066     * Indicates whether the view horizontal layout direction has been resolved.
2067     * @hide
2068     */
2069    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2070
2071    /**
2072     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2073     * @hide
2074     */
2075    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2076            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2077
2078    /*
2079     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2080     * flag value.
2081     * @hide
2082     */
2083    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2084            LAYOUT_DIRECTION_LTR,
2085            LAYOUT_DIRECTION_RTL,
2086            LAYOUT_DIRECTION_INHERIT,
2087            LAYOUT_DIRECTION_LOCALE
2088    };
2089
2090    /**
2091     * Default horizontal layout direction.
2092     */
2093    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2094
2095    /**
2096     * Default horizontal layout direction.
2097     * @hide
2098     */
2099    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2100
2101    /**
2102     * Text direction is inherited through {@link ViewGroup}
2103     */
2104    public static final int TEXT_DIRECTION_INHERIT = 0;
2105
2106    /**
2107     * Text direction is using "first strong algorithm". The first strong directional character
2108     * determines the paragraph direction. If there is no strong directional character, the
2109     * paragraph direction is the view's resolved layout direction.
2110     */
2111    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2112
2113    /**
2114     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2115     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2116     * If there are neither, the paragraph direction is the view's resolved layout direction.
2117     */
2118    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2119
2120    /**
2121     * Text direction is forced to LTR.
2122     */
2123    public static final int TEXT_DIRECTION_LTR = 3;
2124
2125    /**
2126     * Text direction is forced to RTL.
2127     */
2128    public static final int TEXT_DIRECTION_RTL = 4;
2129
2130    /**
2131     * Text direction is coming from the system Locale.
2132     */
2133    public static final int TEXT_DIRECTION_LOCALE = 5;
2134
2135    /**
2136     * Text direction is using "first strong algorithm". The first strong directional character
2137     * determines the paragraph direction. If there is no strong directional character, the
2138     * paragraph direction is LTR.
2139     */
2140    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2141
2142    /**
2143     * Text direction is using "first strong algorithm". The first strong directional character
2144     * determines the paragraph direction. If there is no strong directional character, the
2145     * paragraph direction is RTL.
2146     */
2147    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2148
2149    /**
2150     * Default text direction is inherited
2151     */
2152    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2153
2154    /**
2155     * Default resolved text direction
2156     * @hide
2157     */
2158    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2159
2160    /**
2161     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2162     * @hide
2163     */
2164    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2165
2166    /**
2167     * Mask for use with private flags indicating bits used for text direction.
2168     * @hide
2169     */
2170    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2171            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2172
2173    /**
2174     * Array of text direction flags for mapping attribute "textDirection" to correct
2175     * flag value.
2176     * @hide
2177     */
2178    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2179            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2180            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2181            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2182            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2183            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2184            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2185            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2186            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2187    };
2188
2189    /**
2190     * Indicates whether the view text direction has been resolved.
2191     * @hide
2192     */
2193    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2194            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2195
2196    /**
2197     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2198     * @hide
2199     */
2200    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2201
2202    /**
2203     * Mask for use with private flags indicating bits used for resolved text direction.
2204     * @hide
2205     */
2206    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2207            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2208
2209    /**
2210     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2211     * @hide
2212     */
2213    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2214            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2215
2216    /** @hide */
2217    @IntDef({
2218        TEXT_ALIGNMENT_INHERIT,
2219        TEXT_ALIGNMENT_GRAVITY,
2220        TEXT_ALIGNMENT_CENTER,
2221        TEXT_ALIGNMENT_TEXT_START,
2222        TEXT_ALIGNMENT_TEXT_END,
2223        TEXT_ALIGNMENT_VIEW_START,
2224        TEXT_ALIGNMENT_VIEW_END
2225    })
2226    @Retention(RetentionPolicy.SOURCE)
2227    public @interface TextAlignment {}
2228
2229    /**
2230     * Default text alignment. The text alignment of this View is inherited from its parent.
2231     * Use with {@link #setTextAlignment(int)}
2232     */
2233    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2234
2235    /**
2236     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2237     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2238     *
2239     * Use with {@link #setTextAlignment(int)}
2240     */
2241    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2242
2243    /**
2244     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2245     *
2246     * Use with {@link #setTextAlignment(int)}
2247     */
2248    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2249
2250    /**
2251     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2252     *
2253     * Use with {@link #setTextAlignment(int)}
2254     */
2255    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2256
2257    /**
2258     * Center the paragraph, e.g. ALIGN_CENTER.
2259     *
2260     * Use with {@link #setTextAlignment(int)}
2261     */
2262    public static final int TEXT_ALIGNMENT_CENTER = 4;
2263
2264    /**
2265     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2266     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2267     *
2268     * Use with {@link #setTextAlignment(int)}
2269     */
2270    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2271
2272    /**
2273     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2274     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2275     *
2276     * Use with {@link #setTextAlignment(int)}
2277     */
2278    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2279
2280    /**
2281     * Default text alignment is inherited
2282     */
2283    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2284
2285    /**
2286     * Default resolved text alignment
2287     * @hide
2288     */
2289    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2290
2291    /**
2292      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2293      * @hide
2294      */
2295    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2296
2297    /**
2298      * Mask for use with private flags indicating bits used for text alignment.
2299      * @hide
2300      */
2301    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2302
2303    /**
2304     * Array of text direction flags for mapping attribute "textAlignment" to correct
2305     * flag value.
2306     * @hide
2307     */
2308    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2309            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2310            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2311            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2312            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2313            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2314            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2315            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2316    };
2317
2318    /**
2319     * Indicates whether the view text alignment has been resolved.
2320     * @hide
2321     */
2322    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2323
2324    /**
2325     * Bit shift to get the resolved text alignment.
2326     * @hide
2327     */
2328    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2329
2330    /**
2331     * Mask for use with private flags indicating bits used for text alignment.
2332     * @hide
2333     */
2334    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2335            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2336
2337    /**
2338     * Indicates whether if the view text alignment has been resolved to gravity
2339     */
2340    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2341            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2342
2343    // Accessiblity constants for mPrivateFlags2
2344
2345    /**
2346     * Shift for the bits in {@link #mPrivateFlags2} related to the
2347     * "importantForAccessibility" attribute.
2348     */
2349    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2350
2351    /**
2352     * Automatically determine whether a view is important for accessibility.
2353     */
2354    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2355
2356    /**
2357     * The view is important for accessibility.
2358     */
2359    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2360
2361    /**
2362     * The view is not important for accessibility.
2363     */
2364    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2365
2366    /**
2367     * The view is not important for accessibility, nor are any of its
2368     * descendant views.
2369     */
2370    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2371
2372    /**
2373     * The default whether the view is important for accessibility.
2374     */
2375    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2376
2377    /**
2378     * Mask for obtaining the bits which specify how to determine
2379     * whether a view is important for accessibility.
2380     */
2381    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2382        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2383        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2384        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2385
2386    /**
2387     * Shift for the bits in {@link #mPrivateFlags2} related to the
2388     * "accessibilityLiveRegion" attribute.
2389     */
2390    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2391
2392    /**
2393     * Live region mode specifying that accessibility services should not
2394     * automatically announce changes to this view. This is the default live
2395     * region mode for most views.
2396     * <p>
2397     * Use with {@link #setAccessibilityLiveRegion(int)}.
2398     */
2399    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2400
2401    /**
2402     * Live region mode specifying that accessibility services should announce
2403     * changes to this view.
2404     * <p>
2405     * Use with {@link #setAccessibilityLiveRegion(int)}.
2406     */
2407    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2408
2409    /**
2410     * Live region mode specifying that accessibility services should interrupt
2411     * ongoing speech to immediately announce changes to this view.
2412     * <p>
2413     * Use with {@link #setAccessibilityLiveRegion(int)}.
2414     */
2415    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2416
2417    /**
2418     * The default whether the view is important for accessibility.
2419     */
2420    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2421
2422    /**
2423     * Mask for obtaining the bits which specify a view's accessibility live
2424     * region mode.
2425     */
2426    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2427            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2428            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2429
2430    /**
2431     * Flag indicating whether a view has accessibility focus.
2432     */
2433    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2434
2435    /**
2436     * Flag whether the accessibility state of the subtree rooted at this view changed.
2437     */
2438    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2439
2440    /**
2441     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2442     * is used to check whether later changes to the view's transform should invalidate the
2443     * view to force the quickReject test to run again.
2444     */
2445    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2446
2447    /**
2448     * Flag indicating that start/end padding has been resolved into left/right padding
2449     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2450     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2451     * during measurement. In some special cases this is required such as when an adapter-based
2452     * view measures prospective children without attaching them to a window.
2453     */
2454    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2455
2456    /**
2457     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2458     */
2459    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2460
2461    /**
2462     * Indicates that the view is tracking some sort of transient state
2463     * that the app should not need to be aware of, but that the framework
2464     * should take special care to preserve.
2465     */
2466    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2467
2468    /**
2469     * Group of bits indicating that RTL properties resolution is done.
2470     */
2471    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2472            PFLAG2_TEXT_DIRECTION_RESOLVED |
2473            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2474            PFLAG2_PADDING_RESOLVED |
2475            PFLAG2_DRAWABLE_RESOLVED;
2476
2477    // There are a couple of flags left in mPrivateFlags2
2478
2479    /* End of masks for mPrivateFlags2 */
2480
2481    /**
2482     * Masks for mPrivateFlags3, as generated by dumpFlags():
2483     *
2484     * |-------|-------|-------|-------|
2485     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2486     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2487     *                               1   PFLAG3_IS_LAID_OUT
2488     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2489     *                             1     PFLAG3_CALLED_SUPER
2490     *                            1      PFLAG3_APPLYING_INSETS
2491     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2492     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2493     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2494     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2495     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2496     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2497     *                     1             PFLAG3_SCROLL_INDICATOR_START
2498     *                    1              PFLAG3_SCROLL_INDICATOR_END
2499     *                   1               PFLAG3_ASSIST_BLOCKED
2500     *                  1                PFLAG3_CLUSTER
2501     *                 x                 * NO LONGER NEEDED, SHOULD BE REUSED *
2502     *                1                  PFLAG3_FINGER_DOWN
2503     *               1                   PFLAG3_FOCUSED_BY_DEFAULT
2504     *           xxxx                    * NO LONGER NEEDED, SHOULD BE REUSED *
2505     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2506     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2507     *        1                          PFLAG3_TEMPORARY_DETACH
2508     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2509     * |-------|-------|-------|-------|
2510     */
2511
2512    /**
2513     * Flag indicating that view has a transform animation set on it. This is used to track whether
2514     * an animation is cleared between successive frames, in order to tell the associated
2515     * DisplayList to clear its animation matrix.
2516     */
2517    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2518
2519    /**
2520     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2521     * animation is cleared between successive frames, in order to tell the associated
2522     * DisplayList to restore its alpha value.
2523     */
2524    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2525
2526    /**
2527     * Flag indicating that the view has been through at least one layout since it
2528     * was last attached to a window.
2529     */
2530    static final int PFLAG3_IS_LAID_OUT = 0x4;
2531
2532    /**
2533     * Flag indicating that a call to measure() was skipped and should be done
2534     * instead when layout() is invoked.
2535     */
2536    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2537
2538    /**
2539     * Flag indicating that an overridden method correctly called down to
2540     * the superclass implementation as required by the API spec.
2541     */
2542    static final int PFLAG3_CALLED_SUPER = 0x10;
2543
2544    /**
2545     * Flag indicating that we're in the process of applying window insets.
2546     */
2547    static final int PFLAG3_APPLYING_INSETS = 0x20;
2548
2549    /**
2550     * Flag indicating that we're in the process of fitting system windows using the old method.
2551     */
2552    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2553
2554    /**
2555     * Flag indicating that nested scrolling is enabled for this view.
2556     * The view will optionally cooperate with views up its parent chain to allow for
2557     * integrated nested scrolling along the same axis.
2558     */
2559    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2560
2561    /**
2562     * Flag indicating that the bottom scroll indicator should be displayed
2563     * when this view can scroll up.
2564     */
2565    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2566
2567    /**
2568     * Flag indicating that the bottom scroll indicator should be displayed
2569     * when this view can scroll down.
2570     */
2571    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2572
2573    /**
2574     * Flag indicating that the left scroll indicator should be displayed
2575     * when this view can scroll left.
2576     */
2577    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2578
2579    /**
2580     * Flag indicating that the right scroll indicator should be displayed
2581     * when this view can scroll right.
2582     */
2583    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2584
2585    /**
2586     * Flag indicating that the start scroll indicator should be displayed
2587     * when this view can scroll in the start direction.
2588     */
2589    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2590
2591    /**
2592     * Flag indicating that the end scroll indicator should be displayed
2593     * when this view can scroll in the end direction.
2594     */
2595    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2596
2597    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2598
2599    static final int SCROLL_INDICATORS_NONE = 0x0000;
2600
2601    /**
2602     * Mask for use with setFlags indicating bits used for indicating which
2603     * scroll indicators are enabled.
2604     */
2605    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2606            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2607            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2608            | PFLAG3_SCROLL_INDICATOR_END;
2609
2610    /**
2611     * Left-shift required to translate between public scroll indicator flags
2612     * and internal PFLAGS3 flags. When used as a right-shift, translates
2613     * PFLAGS3 flags to public flags.
2614     */
2615    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2616
2617    /** @hide */
2618    @Retention(RetentionPolicy.SOURCE)
2619    @IntDef(flag = true,
2620            value = {
2621                    SCROLL_INDICATOR_TOP,
2622                    SCROLL_INDICATOR_BOTTOM,
2623                    SCROLL_INDICATOR_LEFT,
2624                    SCROLL_INDICATOR_RIGHT,
2625                    SCROLL_INDICATOR_START,
2626                    SCROLL_INDICATOR_END,
2627            })
2628    public @interface ScrollIndicators {}
2629
2630    /**
2631     * Scroll indicator direction for the top edge of the view.
2632     *
2633     * @see #setScrollIndicators(int)
2634     * @see #setScrollIndicators(int, int)
2635     * @see #getScrollIndicators()
2636     */
2637    public static final int SCROLL_INDICATOR_TOP =
2638            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2639
2640    /**
2641     * Scroll indicator direction for the bottom edge of the view.
2642     *
2643     * @see #setScrollIndicators(int)
2644     * @see #setScrollIndicators(int, int)
2645     * @see #getScrollIndicators()
2646     */
2647    public static final int SCROLL_INDICATOR_BOTTOM =
2648            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2649
2650    /**
2651     * Scroll indicator direction for the left edge of the view.
2652     *
2653     * @see #setScrollIndicators(int)
2654     * @see #setScrollIndicators(int, int)
2655     * @see #getScrollIndicators()
2656     */
2657    public static final int SCROLL_INDICATOR_LEFT =
2658            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2659
2660    /**
2661     * Scroll indicator direction for the right edge of the view.
2662     *
2663     * @see #setScrollIndicators(int)
2664     * @see #setScrollIndicators(int, int)
2665     * @see #getScrollIndicators()
2666     */
2667    public static final int SCROLL_INDICATOR_RIGHT =
2668            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2669
2670    /**
2671     * Scroll indicator direction for the starting edge of the view.
2672     * <p>
2673     * Resolved according to the view's layout direction, see
2674     * {@link #getLayoutDirection()} for more information.
2675     *
2676     * @see #setScrollIndicators(int)
2677     * @see #setScrollIndicators(int, int)
2678     * @see #getScrollIndicators()
2679     */
2680    public static final int SCROLL_INDICATOR_START =
2681            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2682
2683    /**
2684     * Scroll indicator direction for the ending edge of the view.
2685     * <p>
2686     * Resolved according to the view's layout direction, see
2687     * {@link #getLayoutDirection()} for more information.
2688     *
2689     * @see #setScrollIndicators(int)
2690     * @see #setScrollIndicators(int, int)
2691     * @see #getScrollIndicators()
2692     */
2693    public static final int SCROLL_INDICATOR_END =
2694            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2695
2696    /**
2697     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2698     * into this view.<p>
2699     */
2700    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2701
2702    /**
2703     * Flag indicating that the view is a root of a keyboard navigation cluster.
2704     *
2705     * @see #isKeyboardNavigationCluster()
2706     * @see #setKeyboardNavigationCluster(boolean)
2707     */
2708    private static final int PFLAG3_CLUSTER = 0x8000;
2709
2710    /**
2711     * Indicates that the user is currently touching the screen.
2712     * Currently used for the tooltip positioning only.
2713     */
2714    private static final int PFLAG3_FINGER_DOWN = 0x20000;
2715
2716    /**
2717     * Flag indicating that this view is the default-focus view.
2718     *
2719     * @see #isFocusedByDefault()
2720     * @see #setFocusedByDefault(boolean)
2721     */
2722    private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
2723
2724    /**
2725     * Whether this view has rendered elements that overlap (see {@link
2726     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2727     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2728     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2729     * determined by whatever {@link #hasOverlappingRendering()} returns.
2730     */
2731    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2732
2733    /**
2734     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2735     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2736     */
2737    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2738
2739    /**
2740     * Flag indicating that the view is temporarily detached from the parent view.
2741     *
2742     * @see #onStartTemporaryDetach()
2743     * @see #onFinishTemporaryDetach()
2744     */
2745    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2746
2747    /**
2748     * Flag indicating that the view does not wish to be revealed within its parent
2749     * hierarchy when it gains focus. Expressed in the negative since the historical
2750     * default behavior is to reveal on focus; this flag suppresses that behavior.
2751     *
2752     * @see #setRevealOnFocusHint(boolean)
2753     * @see #getRevealOnFocusHint()
2754     */
2755    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
2756
2757    /* End of masks for mPrivateFlags3 */
2758
2759    /**
2760     * Always allow a user to over-scroll this view, provided it is a
2761     * view that can scroll.
2762     *
2763     * @see #getOverScrollMode()
2764     * @see #setOverScrollMode(int)
2765     */
2766    public static final int OVER_SCROLL_ALWAYS = 0;
2767
2768    /**
2769     * Allow a user to over-scroll this view only if the content is large
2770     * enough to meaningfully scroll, provided it is a view that can scroll.
2771     *
2772     * @see #getOverScrollMode()
2773     * @see #setOverScrollMode(int)
2774     */
2775    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2776
2777    /**
2778     * Never allow a user to over-scroll this view.
2779     *
2780     * @see #getOverScrollMode()
2781     * @see #setOverScrollMode(int)
2782     */
2783    public static final int OVER_SCROLL_NEVER = 2;
2784
2785    /**
2786     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2787     * requested the system UI (status bar) to be visible (the default).
2788     *
2789     * @see #setSystemUiVisibility(int)
2790     */
2791    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2792
2793    /**
2794     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2795     * system UI to enter an unobtrusive "low profile" mode.
2796     *
2797     * <p>This is for use in games, book readers, video players, or any other
2798     * "immersive" application where the usual system chrome is deemed too distracting.
2799     *
2800     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2801     *
2802     * @see #setSystemUiVisibility(int)
2803     */
2804    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2805
2806    /**
2807     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2808     * system navigation be temporarily hidden.
2809     *
2810     * <p>This is an even less obtrusive state than that called for by
2811     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2812     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2813     * those to disappear. This is useful (in conjunction with the
2814     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2815     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2816     * window flags) for displaying content using every last pixel on the display.
2817     *
2818     * <p>There is a limitation: because navigation controls are so important, the least user
2819     * interaction will cause them to reappear immediately.  When this happens, both
2820     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2821     * so that both elements reappear at the same time.
2822     *
2823     * @see #setSystemUiVisibility(int)
2824     */
2825    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2826
2827    /**
2828     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2829     * into the normal fullscreen mode so that its content can take over the screen
2830     * while still allowing the user to interact with the application.
2831     *
2832     * <p>This has the same visual effect as
2833     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2834     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2835     * meaning that non-critical screen decorations (such as the status bar) will be
2836     * hidden while the user is in the View's window, focusing the experience on
2837     * that content.  Unlike the window flag, if you are using ActionBar in
2838     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2839     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2840     * hide the action bar.
2841     *
2842     * <p>This approach to going fullscreen is best used over the window flag when
2843     * it is a transient state -- that is, the application does this at certain
2844     * points in its user interaction where it wants to allow the user to focus
2845     * on content, but not as a continuous state.  For situations where the application
2846     * would like to simply stay full screen the entire time (such as a game that
2847     * wants to take over the screen), the
2848     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2849     * is usually a better approach.  The state set here will be removed by the system
2850     * in various situations (such as the user moving to another application) like
2851     * the other system UI states.
2852     *
2853     * <p>When using this flag, the application should provide some easy facility
2854     * for the user to go out of it.  A common example would be in an e-book
2855     * reader, where tapping on the screen brings back whatever screen and UI
2856     * decorations that had been hidden while the user was immersed in reading
2857     * the book.
2858     *
2859     * @see #setSystemUiVisibility(int)
2860     */
2861    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2862
2863    /**
2864     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2865     * flags, we would like a stable view of the content insets given to
2866     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2867     * will always represent the worst case that the application can expect
2868     * as a continuous state.  In the stock Android UI this is the space for
2869     * the system bar, nav bar, and status bar, but not more transient elements
2870     * such as an input method.
2871     *
2872     * The stable layout your UI sees is based on the system UI modes you can
2873     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2874     * then you will get a stable layout for changes of the
2875     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2876     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2877     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2878     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2879     * with a stable layout.  (Note that you should avoid using
2880     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2881     *
2882     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2883     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2884     * then a hidden status bar will be considered a "stable" state for purposes
2885     * here.  This allows your UI to continually hide the status bar, while still
2886     * using the system UI flags to hide the action bar while still retaining
2887     * a stable layout.  Note that changing the window fullscreen flag will never
2888     * provide a stable layout for a clean transition.
2889     *
2890     * <p>If you are using ActionBar in
2891     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2892     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2893     * insets it adds to those given to the application.
2894     */
2895    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2896
2897    /**
2898     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2899     * to be laid out as if it has requested
2900     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2901     * allows it to avoid artifacts when switching in and out of that mode, at
2902     * the expense that some of its user interface may be covered by screen
2903     * decorations when they are shown.  You can perform layout of your inner
2904     * UI elements to account for the navigation system UI through the
2905     * {@link #fitSystemWindows(Rect)} method.
2906     */
2907    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2908
2909    /**
2910     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2911     * to be laid out as if it has requested
2912     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2913     * allows it to avoid artifacts when switching in and out of that mode, at
2914     * the expense that some of its user interface may be covered by screen
2915     * decorations when they are shown.  You can perform layout of your inner
2916     * UI elements to account for non-fullscreen system UI through the
2917     * {@link #fitSystemWindows(Rect)} method.
2918     */
2919    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2920
2921    /**
2922     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2923     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2924     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2925     * user interaction.
2926     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2927     * has an effect when used in combination with that flag.</p>
2928     */
2929    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2930
2931    /**
2932     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2933     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2934     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2935     * experience while also hiding the system bars.  If this flag is not set,
2936     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2937     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2938     * if the user swipes from the top of the screen.
2939     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2940     * system gestures, such as swiping from the top of the screen.  These transient system bars
2941     * will overlay app’s content, may have some degree of transparency, and will automatically
2942     * hide after a short timeout.
2943     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2944     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2945     * with one or both of those flags.</p>
2946     */
2947    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2948
2949    /**
2950     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2951     * is compatible with light status bar backgrounds.
2952     *
2953     * <p>For this to take effect, the window must request
2954     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2955     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2956     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2957     *         FLAG_TRANSLUCENT_STATUS}.
2958     *
2959     * @see android.R.attr#windowLightStatusBar
2960     */
2961    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2962
2963    /**
2964     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
2965     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
2966     */
2967    private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
2968
2969    /**
2970     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
2971     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
2972     */
2973    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
2974
2975    /**
2976     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
2977     * that is compatible with light navigation bar backgrounds.
2978     *
2979     * <p>For this to take effect, the window must request
2980     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2981     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2982     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
2983     *         FLAG_TRANSLUCENT_NAVIGATION}.
2984     */
2985    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
2986
2987    /**
2988     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2989     */
2990    @Deprecated
2991    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2992
2993    /**
2994     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2995     */
2996    @Deprecated
2997    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2998
2999    /**
3000     * @hide
3001     *
3002     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3003     * out of the public fields to keep the undefined bits out of the developer's way.
3004     *
3005     * Flag to make the status bar not expandable.  Unless you also
3006     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3007     */
3008    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3009
3010    /**
3011     * @hide
3012     *
3013     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3014     * out of the public fields to keep the undefined bits out of the developer's way.
3015     *
3016     * Flag to hide notification icons and scrolling ticker text.
3017     */
3018    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3019
3020    /**
3021     * @hide
3022     *
3023     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3024     * out of the public fields to keep the undefined bits out of the developer's way.
3025     *
3026     * Flag to disable incoming notification alerts.  This will not block
3027     * icons, but it will block sound, vibrating and other visual or aural notifications.
3028     */
3029    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3030
3031    /**
3032     * @hide
3033     *
3034     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3035     * out of the public fields to keep the undefined bits out of the developer's way.
3036     *
3037     * Flag to hide only the scrolling ticker.  Note that
3038     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3039     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3040     */
3041    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3042
3043    /**
3044     * @hide
3045     *
3046     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3047     * out of the public fields to keep the undefined bits out of the developer's way.
3048     *
3049     * Flag to hide the center system info area.
3050     */
3051    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3052
3053    /**
3054     * @hide
3055     *
3056     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3057     * out of the public fields to keep the undefined bits out of the developer's way.
3058     *
3059     * Flag to hide only the home button.  Don't use this
3060     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3061     */
3062    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3063
3064    /**
3065     * @hide
3066     *
3067     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3068     * out of the public fields to keep the undefined bits out of the developer's way.
3069     *
3070     * Flag to hide only the back button. Don't use this
3071     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3072     */
3073    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3074
3075    /**
3076     * @hide
3077     *
3078     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3079     * out of the public fields to keep the undefined bits out of the developer's way.
3080     *
3081     * Flag to hide only the clock.  You might use this if your activity has
3082     * its own clock making the status bar's clock redundant.
3083     */
3084    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3085
3086    /**
3087     * @hide
3088     *
3089     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3090     * out of the public fields to keep the undefined bits out of the developer's way.
3091     *
3092     * Flag to hide only the recent apps button. Don't use this
3093     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3094     */
3095    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3096
3097    /**
3098     * @hide
3099     *
3100     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3101     * out of the public fields to keep the undefined bits out of the developer's way.
3102     *
3103     * Flag to disable the global search gesture. Don't use this
3104     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3105     */
3106    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3107
3108    /**
3109     * @hide
3110     *
3111     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3112     * out of the public fields to keep the undefined bits out of the developer's way.
3113     *
3114     * Flag to specify that the status bar is displayed in transient mode.
3115     */
3116    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3117
3118    /**
3119     * @hide
3120     *
3121     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3122     * out of the public fields to keep the undefined bits out of the developer's way.
3123     *
3124     * Flag to specify that the navigation bar is displayed in transient mode.
3125     */
3126    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3127
3128    /**
3129     * @hide
3130     *
3131     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3132     * out of the public fields to keep the undefined bits out of the developer's way.
3133     *
3134     * Flag to specify that the hidden status bar would like to be shown.
3135     */
3136    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3137
3138    /**
3139     * @hide
3140     *
3141     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3142     * out of the public fields to keep the undefined bits out of the developer's way.
3143     *
3144     * Flag to specify that the hidden navigation bar would like to be shown.
3145     */
3146    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3147
3148    /**
3149     * @hide
3150     *
3151     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3152     * out of the public fields to keep the undefined bits out of the developer's way.
3153     *
3154     * Flag to specify that the status bar is displayed in translucent mode.
3155     */
3156    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3157
3158    /**
3159     * @hide
3160     *
3161     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3162     * out of the public fields to keep the undefined bits out of the developer's way.
3163     *
3164     * Flag to specify that the navigation bar is displayed in translucent mode.
3165     */
3166    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3167
3168    /**
3169     * @hide
3170     *
3171     * Makes navigation bar transparent (but not the status bar).
3172     */
3173    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3174
3175    /**
3176     * @hide
3177     *
3178     * Makes status bar transparent (but not the navigation bar).
3179     */
3180    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3181
3182    /**
3183     * @hide
3184     *
3185     * Makes both status bar and navigation bar transparent.
3186     */
3187    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3188            | STATUS_BAR_TRANSPARENT;
3189
3190    /**
3191     * @hide
3192     */
3193    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3194
3195    /**
3196     * These are the system UI flags that can be cleared by events outside
3197     * of an application.  Currently this is just the ability to tap on the
3198     * screen while hiding the navigation bar to have it return.
3199     * @hide
3200     */
3201    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3202            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3203            | SYSTEM_UI_FLAG_FULLSCREEN;
3204
3205    /**
3206     * Flags that can impact the layout in relation to system UI.
3207     */
3208    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3209            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3210            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3211
3212    /** @hide */
3213    @IntDef(flag = true,
3214            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3215    @Retention(RetentionPolicy.SOURCE)
3216    public @interface FindViewFlags {}
3217
3218    /**
3219     * Find views that render the specified text.
3220     *
3221     * @see #findViewsWithText(ArrayList, CharSequence, int)
3222     */
3223    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3224
3225    /**
3226     * Find find views that contain the specified content description.
3227     *
3228     * @see #findViewsWithText(ArrayList, CharSequence, int)
3229     */
3230    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3231
3232    /**
3233     * Find views that contain {@link AccessibilityNodeProvider}. Such
3234     * a View is a root of virtual view hierarchy and may contain the searched
3235     * text. If this flag is set Views with providers are automatically
3236     * added and it is a responsibility of the client to call the APIs of
3237     * the provider to determine whether the virtual tree rooted at this View
3238     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3239     * representing the virtual views with this text.
3240     *
3241     * @see #findViewsWithText(ArrayList, CharSequence, int)
3242     *
3243     * @hide
3244     */
3245    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3246
3247    /**
3248     * The undefined cursor position.
3249     *
3250     * @hide
3251     */
3252    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3253
3254    /**
3255     * Indicates that the screen has changed state and is now off.
3256     *
3257     * @see #onScreenStateChanged(int)
3258     */
3259    public static final int SCREEN_STATE_OFF = 0x0;
3260
3261    /**
3262     * Indicates that the screen has changed state and is now on.
3263     *
3264     * @see #onScreenStateChanged(int)
3265     */
3266    public static final int SCREEN_STATE_ON = 0x1;
3267
3268    /**
3269     * Indicates no axis of view scrolling.
3270     */
3271    public static final int SCROLL_AXIS_NONE = 0;
3272
3273    /**
3274     * Indicates scrolling along the horizontal axis.
3275     */
3276    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3277
3278    /**
3279     * Indicates scrolling along the vertical axis.
3280     */
3281    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3282
3283    /**
3284     * Controls the over-scroll mode for this view.
3285     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3286     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3287     * and {@link #OVER_SCROLL_NEVER}.
3288     */
3289    private int mOverScrollMode;
3290
3291    /**
3292     * The parent this view is attached to.
3293     * {@hide}
3294     *
3295     * @see #getParent()
3296     */
3297    protected ViewParent mParent;
3298
3299    /**
3300     * {@hide}
3301     */
3302    AttachInfo mAttachInfo;
3303
3304    /**
3305     * {@hide}
3306     */
3307    @ViewDebug.ExportedProperty(flagMapping = {
3308        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3309                name = "FORCE_LAYOUT"),
3310        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3311                name = "LAYOUT_REQUIRED"),
3312        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3313            name = "DRAWING_CACHE_INVALID", outputIf = false),
3314        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3315        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3316        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3317        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3318    }, formatToHexString = true)
3319
3320    /* @hide */
3321    public int mPrivateFlags;
3322    int mPrivateFlags2;
3323    int mPrivateFlags3;
3324
3325    /**
3326     * This view's request for the visibility of the status bar.
3327     * @hide
3328     */
3329    @ViewDebug.ExportedProperty(flagMapping = {
3330        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3331                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3332                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3333        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3334                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3335                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3336        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3337                                equals = SYSTEM_UI_FLAG_VISIBLE,
3338                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3339    }, formatToHexString = true)
3340    int mSystemUiVisibility;
3341
3342    /**
3343     * Reference count for transient state.
3344     * @see #setHasTransientState(boolean)
3345     */
3346    int mTransientStateCount = 0;
3347
3348    /**
3349     * Count of how many windows this view has been attached to.
3350     */
3351    int mWindowAttachCount;
3352
3353    /**
3354     * The layout parameters associated with this view and used by the parent
3355     * {@link android.view.ViewGroup} to determine how this view should be
3356     * laid out.
3357     * {@hide}
3358     */
3359    protected ViewGroup.LayoutParams mLayoutParams;
3360
3361    /**
3362     * The view flags hold various views states.
3363     * {@hide}
3364     */
3365    @ViewDebug.ExportedProperty(formatToHexString = true)
3366    int mViewFlags;
3367
3368    static class TransformationInfo {
3369        /**
3370         * The transform matrix for the View. This transform is calculated internally
3371         * based on the translation, rotation, and scale properties.
3372         *
3373         * Do *not* use this variable directly; instead call getMatrix(), which will
3374         * load the value from the View's RenderNode.
3375         */
3376        private final Matrix mMatrix = new Matrix();
3377
3378        /**
3379         * The inverse transform matrix for the View. This transform is calculated
3380         * internally based on the translation, rotation, and scale properties.
3381         *
3382         * Do *not* use this variable directly; instead call getInverseMatrix(),
3383         * which will load the value from the View's RenderNode.
3384         */
3385        private Matrix mInverseMatrix;
3386
3387        /**
3388         * The opacity of the View. This is a value from 0 to 1, where 0 means
3389         * completely transparent and 1 means completely opaque.
3390         */
3391        @ViewDebug.ExportedProperty
3392        float mAlpha = 1f;
3393
3394        /**
3395         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3396         * property only used by transitions, which is composited with the other alpha
3397         * values to calculate the final visual alpha value.
3398         */
3399        float mTransitionAlpha = 1f;
3400    }
3401
3402    /** @hide */
3403    public TransformationInfo mTransformationInfo;
3404
3405    /**
3406     * Current clip bounds. to which all drawing of this view are constrained.
3407     */
3408    Rect mClipBounds = null;
3409
3410    private boolean mLastIsOpaque;
3411
3412    /**
3413     * The distance in pixels from the left edge of this view's parent
3414     * to the left edge of this view.
3415     * {@hide}
3416     */
3417    @ViewDebug.ExportedProperty(category = "layout")
3418    protected int mLeft;
3419    /**
3420     * The distance in pixels from the left edge of this view's parent
3421     * to the right edge of this view.
3422     * {@hide}
3423     */
3424    @ViewDebug.ExportedProperty(category = "layout")
3425    protected int mRight;
3426    /**
3427     * The distance in pixels from the top edge of this view's parent
3428     * to the top edge of this view.
3429     * {@hide}
3430     */
3431    @ViewDebug.ExportedProperty(category = "layout")
3432    protected int mTop;
3433    /**
3434     * The distance in pixels from the top edge of this view's parent
3435     * to the bottom edge of this view.
3436     * {@hide}
3437     */
3438    @ViewDebug.ExportedProperty(category = "layout")
3439    protected int mBottom;
3440
3441    /**
3442     * The offset, in pixels, by which the content of this view is scrolled
3443     * horizontally.
3444     * {@hide}
3445     */
3446    @ViewDebug.ExportedProperty(category = "scrolling")
3447    protected int mScrollX;
3448    /**
3449     * The offset, in pixels, by which the content of this view is scrolled
3450     * vertically.
3451     * {@hide}
3452     */
3453    @ViewDebug.ExportedProperty(category = "scrolling")
3454    protected int mScrollY;
3455
3456    /**
3457     * The left padding in pixels, that is the distance in pixels between the
3458     * left edge of this view and the left edge of its content.
3459     * {@hide}
3460     */
3461    @ViewDebug.ExportedProperty(category = "padding")
3462    protected int mPaddingLeft = 0;
3463    /**
3464     * The right padding in pixels, that is the distance in pixels between the
3465     * right edge of this view and the right edge of its content.
3466     * {@hide}
3467     */
3468    @ViewDebug.ExportedProperty(category = "padding")
3469    protected int mPaddingRight = 0;
3470    /**
3471     * The top padding in pixels, that is the distance in pixels between the
3472     * top edge of this view and the top edge of its content.
3473     * {@hide}
3474     */
3475    @ViewDebug.ExportedProperty(category = "padding")
3476    protected int mPaddingTop;
3477    /**
3478     * The bottom padding in pixels, that is the distance in pixels between the
3479     * bottom edge of this view and the bottom edge of its content.
3480     * {@hide}
3481     */
3482    @ViewDebug.ExportedProperty(category = "padding")
3483    protected int mPaddingBottom;
3484
3485    /**
3486     * The layout insets in pixels, that is the distance in pixels between the
3487     * visible edges of this view its bounds.
3488     */
3489    private Insets mLayoutInsets;
3490
3491    /**
3492     * Briefly describes the view and is primarily used for accessibility support.
3493     */
3494    private CharSequence mContentDescription;
3495
3496    /**
3497     * Specifies the id of a view for which this view serves as a label for
3498     * accessibility purposes.
3499     */
3500    private int mLabelForId = View.NO_ID;
3501
3502    /**
3503     * Predicate for matching labeled view id with its label for
3504     * accessibility purposes.
3505     */
3506    private MatchLabelForPredicate mMatchLabelForPredicate;
3507
3508    /**
3509     * Specifies a view before which this one is visited in accessibility traversal.
3510     */
3511    private int mAccessibilityTraversalBeforeId = NO_ID;
3512
3513    /**
3514     * Specifies a view after which this one is visited in accessibility traversal.
3515     */
3516    private int mAccessibilityTraversalAfterId = NO_ID;
3517
3518    /**
3519     * Predicate for matching a view by its id.
3520     */
3521    private MatchIdPredicate mMatchIdPredicate;
3522
3523    /**
3524     * Cache the paddingRight set by the user to append to the scrollbar's size.
3525     *
3526     * @hide
3527     */
3528    @ViewDebug.ExportedProperty(category = "padding")
3529    protected int mUserPaddingRight;
3530
3531    /**
3532     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3533     *
3534     * @hide
3535     */
3536    @ViewDebug.ExportedProperty(category = "padding")
3537    protected int mUserPaddingBottom;
3538
3539    /**
3540     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3541     *
3542     * @hide
3543     */
3544    @ViewDebug.ExportedProperty(category = "padding")
3545    protected int mUserPaddingLeft;
3546
3547    /**
3548     * Cache the paddingStart set by the user to append to the scrollbar's size.
3549     *
3550     */
3551    @ViewDebug.ExportedProperty(category = "padding")
3552    int mUserPaddingStart;
3553
3554    /**
3555     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3556     *
3557     */
3558    @ViewDebug.ExportedProperty(category = "padding")
3559    int mUserPaddingEnd;
3560
3561    /**
3562     * Cache initial left padding.
3563     *
3564     * @hide
3565     */
3566    int mUserPaddingLeftInitial;
3567
3568    /**
3569     * Cache initial right padding.
3570     *
3571     * @hide
3572     */
3573    int mUserPaddingRightInitial;
3574
3575    /**
3576     * Default undefined padding
3577     */
3578    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3579
3580    /**
3581     * Cache if a left padding has been defined
3582     */
3583    private boolean mLeftPaddingDefined = false;
3584
3585    /**
3586     * Cache if a right padding has been defined
3587     */
3588    private boolean mRightPaddingDefined = false;
3589
3590    /**
3591     * @hide
3592     */
3593    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3594    /**
3595     * @hide
3596     */
3597    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3598
3599    private LongSparseLongArray mMeasureCache;
3600
3601    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3602    private Drawable mBackground;
3603    private TintInfo mBackgroundTint;
3604
3605    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3606    private ForegroundInfo mForegroundInfo;
3607
3608    private Drawable mScrollIndicatorDrawable;
3609
3610    /**
3611     * RenderNode used for backgrounds.
3612     * <p>
3613     * When non-null and valid, this is expected to contain an up-to-date copy
3614     * of the background drawable. It is cleared on temporary detach, and reset
3615     * on cleanup.
3616     */
3617    private RenderNode mBackgroundRenderNode;
3618
3619    private int mBackgroundResource;
3620    private boolean mBackgroundSizeChanged;
3621
3622    private String mTransitionName;
3623
3624    static class TintInfo {
3625        ColorStateList mTintList;
3626        PorterDuff.Mode mTintMode;
3627        boolean mHasTintMode;
3628        boolean mHasTintList;
3629    }
3630
3631    private static class ForegroundInfo {
3632        private Drawable mDrawable;
3633        private TintInfo mTintInfo;
3634        private int mGravity = Gravity.FILL;
3635        private boolean mInsidePadding = true;
3636        private boolean mBoundsChanged = true;
3637        private final Rect mSelfBounds = new Rect();
3638        private final Rect mOverlayBounds = new Rect();
3639    }
3640
3641    static class ListenerInfo {
3642        /**
3643         * Listener used to dispatch focus change events.
3644         * This field should be made private, so it is hidden from the SDK.
3645         * {@hide}
3646         */
3647        protected OnFocusChangeListener mOnFocusChangeListener;
3648
3649        /**
3650         * Listeners for layout change events.
3651         */
3652        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3653
3654        protected OnScrollChangeListener mOnScrollChangeListener;
3655
3656        /**
3657         * Listeners for attach events.
3658         */
3659        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3660
3661        /**
3662         * Listener used to dispatch click events.
3663         * This field should be made private, so it is hidden from the SDK.
3664         * {@hide}
3665         */
3666        public OnClickListener mOnClickListener;
3667
3668        /**
3669         * Listener used to dispatch long click events.
3670         * This field should be made private, so it is hidden from the SDK.
3671         * {@hide}
3672         */
3673        protected OnLongClickListener mOnLongClickListener;
3674
3675        /**
3676         * Listener used to dispatch context click events. This field should be made private, so it
3677         * is hidden from the SDK.
3678         * {@hide}
3679         */
3680        protected OnContextClickListener mOnContextClickListener;
3681
3682        /**
3683         * Listener used to build the context menu.
3684         * This field should be made private, so it is hidden from the SDK.
3685         * {@hide}
3686         */
3687        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3688
3689        private OnKeyListener mOnKeyListener;
3690
3691        private OnTouchListener mOnTouchListener;
3692
3693        private OnHoverListener mOnHoverListener;
3694
3695        private OnGenericMotionListener mOnGenericMotionListener;
3696
3697        private OnDragListener mOnDragListener;
3698
3699        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3700
3701        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3702
3703        OnCapturedPointerListener mOnCapturedPointerListener;
3704    }
3705
3706    ListenerInfo mListenerInfo;
3707
3708    private static class TooltipInfo {
3709        /**
3710         * Text to be displayed in a tooltip popup.
3711         */
3712        @Nullable
3713        CharSequence mTooltipText;
3714
3715        /**
3716         * View-relative position of the tooltip anchor point.
3717         */
3718        int mAnchorX;
3719        int mAnchorY;
3720
3721        /**
3722         * The tooltip popup.
3723         */
3724        @Nullable
3725        TooltipPopup mTooltipPopup;
3726
3727        /**
3728         * Set to true if the tooltip was shown as a result of a long click.
3729         */
3730        boolean mTooltipFromLongClick;
3731
3732        /**
3733         * Keep these Runnables so that they can be used to reschedule.
3734         */
3735        Runnable mShowTooltipRunnable;
3736        Runnable mHideTooltipRunnable;
3737    }
3738
3739    TooltipInfo mTooltipInfo;
3740
3741    // Temporary values used to hold (x,y) coordinates when delegating from the
3742    // two-arg performLongClick() method to the legacy no-arg version.
3743    private float mLongClickX = Float.NaN;
3744    private float mLongClickY = Float.NaN;
3745
3746    /**
3747     * The application environment this view lives in.
3748     * This field should be made private, so it is hidden from the SDK.
3749     * {@hide}
3750     */
3751    @ViewDebug.ExportedProperty(deepExport = true)
3752    protected Context mContext;
3753
3754    private final Resources mResources;
3755
3756    private ScrollabilityCache mScrollCache;
3757
3758    private int[] mDrawableState = null;
3759
3760    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3761
3762    /**
3763     * Animator that automatically runs based on state changes.
3764     */
3765    private StateListAnimator mStateListAnimator;
3766
3767    /**
3768     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3769     * the user may specify which view to go to next.
3770     */
3771    private int mNextFocusLeftId = View.NO_ID;
3772
3773    /**
3774     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3775     * the user may specify which view to go to next.
3776     */
3777    private int mNextFocusRightId = View.NO_ID;
3778
3779    /**
3780     * When this view has focus and the next focus is {@link #FOCUS_UP},
3781     * the user may specify which view to go to next.
3782     */
3783    private int mNextFocusUpId = View.NO_ID;
3784
3785    /**
3786     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3787     * the user may specify which view to go to next.
3788     */
3789    private int mNextFocusDownId = View.NO_ID;
3790
3791    /**
3792     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3793     * the user may specify which view to go to next.
3794     */
3795    int mNextFocusForwardId = View.NO_ID;
3796
3797    /**
3798     * User-specified next keyboard navigation cluster.
3799     */
3800    int mNextClusterForwardId = View.NO_ID;
3801
3802    private CheckForLongPress mPendingCheckForLongPress;
3803    private CheckForTap mPendingCheckForTap = null;
3804    private PerformClick mPerformClick;
3805    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3806
3807    private UnsetPressedState mUnsetPressedState;
3808
3809    /**
3810     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3811     * up event while a long press is invoked as soon as the long press duration is reached, so
3812     * a long press could be performed before the tap is checked, in which case the tap's action
3813     * should not be invoked.
3814     */
3815    private boolean mHasPerformedLongPress;
3816
3817    /**
3818     * Whether a context click button is currently pressed down. This is true when the stylus is
3819     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3820     * pressed. This is false once the button is released or if the stylus has been lifted.
3821     */
3822    private boolean mInContextButtonPress;
3823
3824    /**
3825     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3826     * true after a stylus button press has occured, when the next up event should not be recognized
3827     * as a tap.
3828     */
3829    private boolean mIgnoreNextUpEvent;
3830
3831    /**
3832     * The minimum height of the view. We'll try our best to have the height
3833     * of this view to at least this amount.
3834     */
3835    @ViewDebug.ExportedProperty(category = "measurement")
3836    private int mMinHeight;
3837
3838    /**
3839     * The minimum width of the view. We'll try our best to have the width
3840     * of this view to at least this amount.
3841     */
3842    @ViewDebug.ExportedProperty(category = "measurement")
3843    private int mMinWidth;
3844
3845    /**
3846     * The delegate to handle touch events that are physically in this view
3847     * but should be handled by another view.
3848     */
3849    private TouchDelegate mTouchDelegate = null;
3850
3851    /**
3852     * Solid color to use as a background when creating the drawing cache. Enables
3853     * the cache to use 16 bit bitmaps instead of 32 bit.
3854     */
3855    private int mDrawingCacheBackgroundColor = 0;
3856
3857    /**
3858     * Special tree observer used when mAttachInfo is null.
3859     */
3860    private ViewTreeObserver mFloatingTreeObserver;
3861
3862    /**
3863     * Cache the touch slop from the context that created the view.
3864     */
3865    private int mTouchSlop;
3866
3867    /**
3868     * Object that handles automatic animation of view properties.
3869     */
3870    private ViewPropertyAnimator mAnimator = null;
3871
3872    /**
3873     * List of registered FrameMetricsObservers.
3874     */
3875    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3876
3877    /**
3878     * Flag indicating that a drag can cross window boundaries.  When
3879     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3880     * with this flag set, all visible applications with targetSdkVersion >=
3881     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3882     * in the drag operation and receive the dragged content.
3883     *
3884     * <p>If this is the only flag set, then the drag recipient will only have access to text data
3885     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3886     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
3887     */
3888    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3889
3890    /**
3891     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3892     * request read access to the content URI(s) contained in the {@link ClipData} object.
3893     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3894     */
3895    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3896
3897    /**
3898     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3899     * request write access to the content URI(s) contained in the {@link ClipData} object.
3900     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3901     */
3902    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3903
3904    /**
3905     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3906     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3907     * reboots until explicitly revoked with
3908     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3909     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3910     */
3911    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3912            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3913
3914    /**
3915     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3916     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3917     * match against the original granted URI.
3918     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3919     */
3920    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3921            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3922
3923    /**
3924     * Flag indicating that the drag shadow will be opaque.  When
3925     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3926     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3927     */
3928    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3929
3930    /**
3931     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3932     */
3933    private float mVerticalScrollFactor;
3934
3935    /**
3936     * Position of the vertical scroll bar.
3937     */
3938    private int mVerticalScrollbarPosition;
3939
3940    /**
3941     * Position the scroll bar at the default position as determined by the system.
3942     */
3943    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3944
3945    /**
3946     * Position the scroll bar along the left edge.
3947     */
3948    public static final int SCROLLBAR_POSITION_LEFT = 1;
3949
3950    /**
3951     * Position the scroll bar along the right edge.
3952     */
3953    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3954
3955    /**
3956     * Indicates that the view does not have a layer.
3957     *
3958     * @see #getLayerType()
3959     * @see #setLayerType(int, android.graphics.Paint)
3960     * @see #LAYER_TYPE_SOFTWARE
3961     * @see #LAYER_TYPE_HARDWARE
3962     */
3963    public static final int LAYER_TYPE_NONE = 0;
3964
3965    /**
3966     * <p>Indicates that the view has a software layer. A software layer is backed
3967     * by a bitmap and causes the view to be rendered using Android's software
3968     * rendering pipeline, even if hardware acceleration is enabled.</p>
3969     *
3970     * <p>Software layers have various usages:</p>
3971     * <p>When the application is not using hardware acceleration, a software layer
3972     * is useful to apply a specific color filter and/or blending mode and/or
3973     * translucency to a view and all its children.</p>
3974     * <p>When the application is using hardware acceleration, a software layer
3975     * is useful to render drawing primitives not supported by the hardware
3976     * accelerated pipeline. It can also be used to cache a complex view tree
3977     * into a texture and reduce the complexity of drawing operations. For instance,
3978     * when animating a complex view tree with a translation, a software layer can
3979     * be used to render the view tree only once.</p>
3980     * <p>Software layers should be avoided when the affected view tree updates
3981     * often. Every update will require to re-render the software layer, which can
3982     * potentially be slow (particularly when hardware acceleration is turned on
3983     * since the layer will have to be uploaded into a hardware texture after every
3984     * update.)</p>
3985     *
3986     * @see #getLayerType()
3987     * @see #setLayerType(int, android.graphics.Paint)
3988     * @see #LAYER_TYPE_NONE
3989     * @see #LAYER_TYPE_HARDWARE
3990     */
3991    public static final int LAYER_TYPE_SOFTWARE = 1;
3992
3993    /**
3994     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3995     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3996     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3997     * rendering pipeline, but only if hardware acceleration is turned on for the
3998     * view hierarchy. When hardware acceleration is turned off, hardware layers
3999     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
4000     *
4001     * <p>A hardware layer is useful to apply a specific color filter and/or
4002     * blending mode and/or translucency to a view and all its children.</p>
4003     * <p>A hardware layer can be used to cache a complex view tree into a
4004     * texture and reduce the complexity of drawing operations. For instance,
4005     * when animating a complex view tree with a translation, a hardware layer can
4006     * be used to render the view tree only once.</p>
4007     * <p>A hardware layer can also be used to increase the rendering quality when
4008     * rotation transformations are applied on a view. It can also be used to
4009     * prevent potential clipping issues when applying 3D transforms on a view.</p>
4010     *
4011     * @see #getLayerType()
4012     * @see #setLayerType(int, android.graphics.Paint)
4013     * @see #LAYER_TYPE_NONE
4014     * @see #LAYER_TYPE_SOFTWARE
4015     */
4016    public static final int LAYER_TYPE_HARDWARE = 2;
4017
4018    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4019            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
4020            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
4021            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
4022    })
4023    int mLayerType = LAYER_TYPE_NONE;
4024    Paint mLayerPaint;
4025
4026
4027    /**
4028     * Set when a request was made to decide if views in an {@link android.app.Activity} can be
4029     * auto-filled by an {@link android.service.autofill.AutoFillService}.
4030     *
4031     * <p>Since this request is made without a explicit user consent, the resulting
4032     * {@link android.app.assist.AssistStructure} should not contain any PII
4033     * (Personally Identifiable Information).
4034     *
4035     * <p>Examples:
4036     * <ul>
4037     * <li>{@link android.widget.TextView} texts should only be included when they were set by
4038     * static resources.
4039     * <li>{@link android.webkit.WebView} virtual children should be restricted to a subset of
4040     * input fields and tags (like {@code id}).
4041     * </ul>
4042     */
4043    // TODO(b/33197203): cannot conflict with flags defined on AutoFillManager until they're removed
4044    // (when save is refactored).
4045    public static final int AUTO_FILL_FLAG_TYPE_FILL = 0x10000000;
4046
4047    /**
4048     * Set when the user explicitly asked a {@link android.service.autofill.AutoFillService} to save
4049     * the value of the {@link View}s in an {@link android.app.Activity}.
4050     *
4051     * <p>The resulting {@link android.app.assist.AssistStructure} can contain any kind of PII
4052     * (Personally Identifiable Information). For example, the text of password fields should be
4053     * included since that's what's typically saved.
4054     */
4055    // TODO(b/33197203): cannot conflict with flags defined on AutoFillManager until they're removed
4056    // (when save is refactored).
4057    public static final int AUTO_FILL_FLAG_TYPE_SAVE = 0x20000000;
4058
4059    /**
4060     * Set to true when drawing cache is enabled and cannot be created.
4061     *
4062     * @hide
4063     */
4064    public boolean mCachingFailed;
4065    private Bitmap mDrawingCache;
4066    private Bitmap mUnscaledDrawingCache;
4067
4068    /**
4069     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4070     * <p>
4071     * When non-null and valid, this is expected to contain an up-to-date copy
4072     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4073     * cleanup.
4074     */
4075    final RenderNode mRenderNode;
4076
4077    /**
4078     * Set to true when the view is sending hover accessibility events because it
4079     * is the innermost hovered view.
4080     */
4081    private boolean mSendingHoverAccessibilityEvents;
4082
4083    /**
4084     * Delegate for injecting accessibility functionality.
4085     */
4086    AccessibilityDelegate mAccessibilityDelegate;
4087
4088    /**
4089     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4090     * and add/remove objects to/from the overlay directly through the Overlay methods.
4091     */
4092    ViewOverlay mOverlay;
4093
4094    /**
4095     * The currently active parent view for receiving delegated nested scrolling events.
4096     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4097     * by {@link #stopNestedScroll()} at the same point where we clear
4098     * requestDisallowInterceptTouchEvent.
4099     */
4100    private ViewParent mNestedScrollingParent;
4101
4102    /**
4103     * Consistency verifier for debugging purposes.
4104     * @hide
4105     */
4106    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4107            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4108                    new InputEventConsistencyVerifier(this, 0) : null;
4109
4110    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4111
4112    private int[] mTempNestedScrollConsumed;
4113
4114    /**
4115     * An overlay is going to draw this View instead of being drawn as part of this
4116     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4117     * when this view is invalidated.
4118     */
4119    GhostView mGhostView;
4120
4121    /**
4122     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4123     * @hide
4124     */
4125    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4126    public String[] mAttributes;
4127
4128    /**
4129     * Maps a Resource id to its name.
4130     */
4131    private static SparseArray<String> mAttributeMap;
4132
4133    /**
4134     * Queue of pending runnables. Used to postpone calls to post() until this
4135     * view is attached and has a handler.
4136     */
4137    private HandlerActionQueue mRunQueue;
4138
4139    /**
4140     * The pointer icon when the mouse hovers on this view. The default is null.
4141     */
4142    private PointerIcon mPointerIcon;
4143
4144    /**
4145     * @hide
4146     */
4147    String mStartActivityRequestWho;
4148
4149    @Nullable
4150    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4151
4152    /**
4153     * Simple constructor to use when creating a view from code.
4154     *
4155     * @param context The Context the view is running in, through which it can
4156     *        access the current theme, resources, etc.
4157     */
4158    public View(Context context) {
4159        mContext = context;
4160        mResources = context != null ? context.getResources() : null;
4161        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO;
4162        // Set some flags defaults
4163        mPrivateFlags2 =
4164                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4165                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4166                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4167                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4168                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4169                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4170        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4171        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4172        mUserPaddingStart = UNDEFINED_PADDING;
4173        mUserPaddingEnd = UNDEFINED_PADDING;
4174        mRenderNode = RenderNode.create(getClass().getName(), this);
4175
4176        if (!sCompatibilityDone && context != null) {
4177            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4178
4179            // Older apps may need this compatibility hack for measurement.
4180            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4181
4182            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4183            // of whether a layout was requested on that View.
4184            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4185
4186            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4187
4188            // In M and newer, our widgets can pass a "hint" value in the size
4189            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4190            // know what the expected parent size is going to be, so e.g. list items can size
4191            // themselves at 1/3 the size of their container. It breaks older apps though,
4192            // specifically apps that use some popular open source libraries.
4193            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4194
4195            // Old versions of the platform would give different results from
4196            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4197            // modes, so we always need to run an additional EXACTLY pass.
4198            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4199
4200            // Prior to N, layout params could change without requiring a
4201            // subsequent call to setLayoutParams() and they would usually
4202            // work. Partial layout breaks this assumption.
4203            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4204
4205            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4206            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4207            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4208
4209            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4210            // in apps so we target check it to avoid breaking existing apps.
4211            sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N;
4212
4213            sCascadedDragDrop = targetSdkVersion < N;
4214
4215            sCompatibilityDone = true;
4216        }
4217    }
4218
4219    /**
4220     * Constructor that is called when inflating a view from XML. This is called
4221     * when a view is being constructed from an XML file, supplying attributes
4222     * that were specified in the XML file. This version uses a default style of
4223     * 0, so the only attribute values applied are those in the Context's Theme
4224     * and the given AttributeSet.
4225     *
4226     * <p>
4227     * The method onFinishInflate() will be called after all children have been
4228     * added.
4229     *
4230     * @param context The Context the view is running in, through which it can
4231     *        access the current theme, resources, etc.
4232     * @param attrs The attributes of the XML tag that is inflating the view.
4233     * @see #View(Context, AttributeSet, int)
4234     */
4235    public View(Context context, @Nullable AttributeSet attrs) {
4236        this(context, attrs, 0);
4237    }
4238
4239    /**
4240     * Perform inflation from XML and apply a class-specific base style from a
4241     * theme attribute. This constructor of View allows subclasses to use their
4242     * own base style when they are inflating. For example, a Button class's
4243     * constructor would call this version of the super class constructor and
4244     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4245     * allows the theme's button style to modify all of the base view attributes
4246     * (in particular its background) as well as the Button class's attributes.
4247     *
4248     * @param context The Context the view is running in, through which it can
4249     *        access the current theme, resources, etc.
4250     * @param attrs The attributes of the XML tag that is inflating the view.
4251     * @param defStyleAttr An attribute in the current theme that contains a
4252     *        reference to a style resource that supplies default values for
4253     *        the view. Can be 0 to not look for defaults.
4254     * @see #View(Context, AttributeSet)
4255     */
4256    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4257        this(context, attrs, defStyleAttr, 0);
4258    }
4259
4260    /**
4261     * Perform inflation from XML and apply a class-specific base style from a
4262     * theme attribute or style resource. This constructor of View allows
4263     * subclasses to use their own base style when they are inflating.
4264     * <p>
4265     * When determining the final value of a particular attribute, there are
4266     * four inputs that come into play:
4267     * <ol>
4268     * <li>Any attribute values in the given AttributeSet.
4269     * <li>The style resource specified in the AttributeSet (named "style").
4270     * <li>The default style specified by <var>defStyleAttr</var>.
4271     * <li>The default style specified by <var>defStyleRes</var>.
4272     * <li>The base values in this theme.
4273     * </ol>
4274     * <p>
4275     * Each of these inputs is considered in-order, with the first listed taking
4276     * precedence over the following ones. In other words, if in the
4277     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4278     * , then the button's text will <em>always</em> be black, regardless of
4279     * what is specified in any of the styles.
4280     *
4281     * @param context The Context the view is running in, through which it can
4282     *        access the current theme, resources, etc.
4283     * @param attrs The attributes of the XML tag that is inflating the view.
4284     * @param defStyleAttr An attribute in the current theme that contains a
4285     *        reference to a style resource that supplies default values for
4286     *        the view. Can be 0 to not look for defaults.
4287     * @param defStyleRes A resource identifier of a style resource that
4288     *        supplies default values for the view, used only if
4289     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4290     *        to not look for defaults.
4291     * @see #View(Context, AttributeSet, int)
4292     */
4293    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4294        this(context);
4295
4296        final TypedArray a = context.obtainStyledAttributes(
4297                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4298
4299        if (mDebugViewAttributes) {
4300            saveAttributeData(attrs, a);
4301        }
4302
4303        Drawable background = null;
4304
4305        int leftPadding = -1;
4306        int topPadding = -1;
4307        int rightPadding = -1;
4308        int bottomPadding = -1;
4309        int startPadding = UNDEFINED_PADDING;
4310        int endPadding = UNDEFINED_PADDING;
4311
4312        int padding = -1;
4313        int paddingHorizontal = -1;
4314        int paddingVertical = -1;
4315
4316        int viewFlagValues = 0;
4317        int viewFlagMasks = 0;
4318
4319        boolean setScrollContainer = false;
4320
4321        int x = 0;
4322        int y = 0;
4323
4324        float tx = 0;
4325        float ty = 0;
4326        float tz = 0;
4327        float elevation = 0;
4328        float rotation = 0;
4329        float rotationX = 0;
4330        float rotationY = 0;
4331        float sx = 1f;
4332        float sy = 1f;
4333        boolean transformSet = false;
4334
4335        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4336        int overScrollMode = mOverScrollMode;
4337        boolean initializeScrollbars = false;
4338        boolean initializeScrollIndicators = false;
4339
4340        boolean startPaddingDefined = false;
4341        boolean endPaddingDefined = false;
4342        boolean leftPaddingDefined = false;
4343        boolean rightPaddingDefined = false;
4344
4345        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4346
4347        // Set default values.
4348        viewFlagValues |= FOCUSABLE_AUTO;
4349        viewFlagMasks |= FOCUSABLE_AUTO;
4350
4351        final int N = a.getIndexCount();
4352        for (int i = 0; i < N; i++) {
4353            int attr = a.getIndex(i);
4354            switch (attr) {
4355                case com.android.internal.R.styleable.View_background:
4356                    background = a.getDrawable(attr);
4357                    break;
4358                case com.android.internal.R.styleable.View_padding:
4359                    padding = a.getDimensionPixelSize(attr, -1);
4360                    mUserPaddingLeftInitial = padding;
4361                    mUserPaddingRightInitial = padding;
4362                    leftPaddingDefined = true;
4363                    rightPaddingDefined = true;
4364                    break;
4365                case com.android.internal.R.styleable.View_paddingHorizontal:
4366                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
4367                    mUserPaddingLeftInitial = paddingHorizontal;
4368                    mUserPaddingRightInitial = paddingHorizontal;
4369                    leftPaddingDefined = true;
4370                    rightPaddingDefined = true;
4371                    break;
4372                case com.android.internal.R.styleable.View_paddingVertical:
4373                    paddingVertical = a.getDimensionPixelSize(attr, -1);
4374                    break;
4375                 case com.android.internal.R.styleable.View_paddingLeft:
4376                    leftPadding = a.getDimensionPixelSize(attr, -1);
4377                    mUserPaddingLeftInitial = leftPadding;
4378                    leftPaddingDefined = true;
4379                    break;
4380                case com.android.internal.R.styleable.View_paddingTop:
4381                    topPadding = a.getDimensionPixelSize(attr, -1);
4382                    break;
4383                case com.android.internal.R.styleable.View_paddingRight:
4384                    rightPadding = a.getDimensionPixelSize(attr, -1);
4385                    mUserPaddingRightInitial = rightPadding;
4386                    rightPaddingDefined = true;
4387                    break;
4388                case com.android.internal.R.styleable.View_paddingBottom:
4389                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4390                    break;
4391                case com.android.internal.R.styleable.View_paddingStart:
4392                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4393                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4394                    break;
4395                case com.android.internal.R.styleable.View_paddingEnd:
4396                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4397                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4398                    break;
4399                case com.android.internal.R.styleable.View_scrollX:
4400                    x = a.getDimensionPixelOffset(attr, 0);
4401                    break;
4402                case com.android.internal.R.styleable.View_scrollY:
4403                    y = a.getDimensionPixelOffset(attr, 0);
4404                    break;
4405                case com.android.internal.R.styleable.View_alpha:
4406                    setAlpha(a.getFloat(attr, 1f));
4407                    break;
4408                case com.android.internal.R.styleable.View_transformPivotX:
4409                    setPivotX(a.getDimension(attr, 0));
4410                    break;
4411                case com.android.internal.R.styleable.View_transformPivotY:
4412                    setPivotY(a.getDimension(attr, 0));
4413                    break;
4414                case com.android.internal.R.styleable.View_translationX:
4415                    tx = a.getDimension(attr, 0);
4416                    transformSet = true;
4417                    break;
4418                case com.android.internal.R.styleable.View_translationY:
4419                    ty = a.getDimension(attr, 0);
4420                    transformSet = true;
4421                    break;
4422                case com.android.internal.R.styleable.View_translationZ:
4423                    tz = a.getDimension(attr, 0);
4424                    transformSet = true;
4425                    break;
4426                case com.android.internal.R.styleable.View_elevation:
4427                    elevation = a.getDimension(attr, 0);
4428                    transformSet = true;
4429                    break;
4430                case com.android.internal.R.styleable.View_rotation:
4431                    rotation = a.getFloat(attr, 0);
4432                    transformSet = true;
4433                    break;
4434                case com.android.internal.R.styleable.View_rotationX:
4435                    rotationX = a.getFloat(attr, 0);
4436                    transformSet = true;
4437                    break;
4438                case com.android.internal.R.styleable.View_rotationY:
4439                    rotationY = a.getFloat(attr, 0);
4440                    transformSet = true;
4441                    break;
4442                case com.android.internal.R.styleable.View_scaleX:
4443                    sx = a.getFloat(attr, 1f);
4444                    transformSet = true;
4445                    break;
4446                case com.android.internal.R.styleable.View_scaleY:
4447                    sy = a.getFloat(attr, 1f);
4448                    transformSet = true;
4449                    break;
4450                case com.android.internal.R.styleable.View_id:
4451                    mID = a.getResourceId(attr, NO_ID);
4452                    break;
4453                case com.android.internal.R.styleable.View_tag:
4454                    mTag = a.getText(attr);
4455                    break;
4456                case com.android.internal.R.styleable.View_fitsSystemWindows:
4457                    if (a.getBoolean(attr, false)) {
4458                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4459                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4460                    }
4461                    break;
4462                case com.android.internal.R.styleable.View_focusable:
4463                    viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
4464                    if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
4465                        viewFlagMasks |= FOCUSABLE_MASK;
4466                    }
4467                    break;
4468                case com.android.internal.R.styleable.View_focusableInTouchMode:
4469                    if (a.getBoolean(attr, false)) {
4470                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4471                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4472                    }
4473                    break;
4474                case com.android.internal.R.styleable.View_clickable:
4475                    if (a.getBoolean(attr, false)) {
4476                        viewFlagValues |= CLICKABLE;
4477                        viewFlagMasks |= CLICKABLE;
4478                    }
4479                    break;
4480                case com.android.internal.R.styleable.View_longClickable:
4481                    if (a.getBoolean(attr, false)) {
4482                        viewFlagValues |= LONG_CLICKABLE;
4483                        viewFlagMasks |= LONG_CLICKABLE;
4484                    }
4485                    break;
4486                case com.android.internal.R.styleable.View_contextClickable:
4487                    if (a.getBoolean(attr, false)) {
4488                        viewFlagValues |= CONTEXT_CLICKABLE;
4489                        viewFlagMasks |= CONTEXT_CLICKABLE;
4490                    }
4491                    break;
4492                case com.android.internal.R.styleable.View_saveEnabled:
4493                    if (!a.getBoolean(attr, true)) {
4494                        viewFlagValues |= SAVE_DISABLED;
4495                        viewFlagMasks |= SAVE_DISABLED_MASK;
4496                    }
4497                    break;
4498                case com.android.internal.R.styleable.View_duplicateParentState:
4499                    if (a.getBoolean(attr, false)) {
4500                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4501                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4502                    }
4503                    break;
4504                case com.android.internal.R.styleable.View_visibility:
4505                    final int visibility = a.getInt(attr, 0);
4506                    if (visibility != 0) {
4507                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4508                        viewFlagMasks |= VISIBILITY_MASK;
4509                    }
4510                    break;
4511                case com.android.internal.R.styleable.View_layoutDirection:
4512                    // Clear any layout direction flags (included resolved bits) already set
4513                    mPrivateFlags2 &=
4514                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4515                    // Set the layout direction flags depending on the value of the attribute
4516                    final int layoutDirection = a.getInt(attr, -1);
4517                    final int value = (layoutDirection != -1) ?
4518                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4519                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4520                    break;
4521                case com.android.internal.R.styleable.View_drawingCacheQuality:
4522                    final int cacheQuality = a.getInt(attr, 0);
4523                    if (cacheQuality != 0) {
4524                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4525                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4526                    }
4527                    break;
4528                case com.android.internal.R.styleable.View_contentDescription:
4529                    setContentDescription(a.getString(attr));
4530                    break;
4531                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4532                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4533                    break;
4534                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4535                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4536                    break;
4537                case com.android.internal.R.styleable.View_labelFor:
4538                    setLabelFor(a.getResourceId(attr, NO_ID));
4539                    break;
4540                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4541                    if (!a.getBoolean(attr, true)) {
4542                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4543                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4544                    }
4545                    break;
4546                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4547                    if (!a.getBoolean(attr, true)) {
4548                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4549                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4550                    }
4551                    break;
4552                case R.styleable.View_scrollbars:
4553                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4554                    if (scrollbars != SCROLLBARS_NONE) {
4555                        viewFlagValues |= scrollbars;
4556                        viewFlagMasks |= SCROLLBARS_MASK;
4557                        initializeScrollbars = true;
4558                    }
4559                    break;
4560                //noinspection deprecation
4561                case R.styleable.View_fadingEdge:
4562                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4563                        // Ignore the attribute starting with ICS
4564                        break;
4565                    }
4566                    // With builds < ICS, fall through and apply fading edges
4567                case R.styleable.View_requiresFadingEdge:
4568                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4569                    if (fadingEdge != FADING_EDGE_NONE) {
4570                        viewFlagValues |= fadingEdge;
4571                        viewFlagMasks |= FADING_EDGE_MASK;
4572                        initializeFadingEdgeInternal(a);
4573                    }
4574                    break;
4575                case R.styleable.View_scrollbarStyle:
4576                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4577                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4578                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4579                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4580                    }
4581                    break;
4582                case R.styleable.View_isScrollContainer:
4583                    setScrollContainer = true;
4584                    if (a.getBoolean(attr, false)) {
4585                        setScrollContainer(true);
4586                    }
4587                    break;
4588                case com.android.internal.R.styleable.View_keepScreenOn:
4589                    if (a.getBoolean(attr, false)) {
4590                        viewFlagValues |= KEEP_SCREEN_ON;
4591                        viewFlagMasks |= KEEP_SCREEN_ON;
4592                    }
4593                    break;
4594                case R.styleable.View_filterTouchesWhenObscured:
4595                    if (a.getBoolean(attr, false)) {
4596                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4597                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4598                    }
4599                    break;
4600                case R.styleable.View_nextFocusLeft:
4601                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4602                    break;
4603                case R.styleable.View_nextFocusRight:
4604                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4605                    break;
4606                case R.styleable.View_nextFocusUp:
4607                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4608                    break;
4609                case R.styleable.View_nextFocusDown:
4610                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4611                    break;
4612                case R.styleable.View_nextFocusForward:
4613                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4614                    break;
4615                case R.styleable.View_nextClusterForward:
4616                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
4617                    break;
4618                case R.styleable.View_minWidth:
4619                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4620                    break;
4621                case R.styleable.View_minHeight:
4622                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4623                    break;
4624                case R.styleable.View_onClick:
4625                    if (context.isRestricted()) {
4626                        throw new IllegalStateException("The android:onClick attribute cannot "
4627                                + "be used within a restricted context");
4628                    }
4629
4630                    final String handlerName = a.getString(attr);
4631                    if (handlerName != null) {
4632                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4633                    }
4634                    break;
4635                case R.styleable.View_overScrollMode:
4636                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4637                    break;
4638                case R.styleable.View_verticalScrollbarPosition:
4639                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4640                    break;
4641                case R.styleable.View_layerType:
4642                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4643                    break;
4644                case R.styleable.View_textDirection:
4645                    // Clear any text direction flag already set
4646                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4647                    // Set the text direction flags depending on the value of the attribute
4648                    final int textDirection = a.getInt(attr, -1);
4649                    if (textDirection != -1) {
4650                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4651                    }
4652                    break;
4653                case R.styleable.View_textAlignment:
4654                    // Clear any text alignment flag already set
4655                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4656                    // Set the text alignment flag depending on the value of the attribute
4657                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4658                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4659                    break;
4660                case R.styleable.View_importantForAccessibility:
4661                    setImportantForAccessibility(a.getInt(attr,
4662                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4663                    break;
4664                case R.styleable.View_accessibilityLiveRegion:
4665                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4666                    break;
4667                case R.styleable.View_transitionName:
4668                    setTransitionName(a.getString(attr));
4669                    break;
4670                case R.styleable.View_nestedScrollingEnabled:
4671                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4672                    break;
4673                case R.styleable.View_stateListAnimator:
4674                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4675                            a.getResourceId(attr, 0)));
4676                    break;
4677                case R.styleable.View_backgroundTint:
4678                    // This will get applied later during setBackground().
4679                    if (mBackgroundTint == null) {
4680                        mBackgroundTint = new TintInfo();
4681                    }
4682                    mBackgroundTint.mTintList = a.getColorStateList(
4683                            R.styleable.View_backgroundTint);
4684                    mBackgroundTint.mHasTintList = true;
4685                    break;
4686                case R.styleable.View_backgroundTintMode:
4687                    // This will get applied later during setBackground().
4688                    if (mBackgroundTint == null) {
4689                        mBackgroundTint = new TintInfo();
4690                    }
4691                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4692                            R.styleable.View_backgroundTintMode, -1), null);
4693                    mBackgroundTint.mHasTintMode = true;
4694                    break;
4695                case R.styleable.View_outlineProvider:
4696                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4697                            PROVIDER_BACKGROUND));
4698                    break;
4699                case R.styleable.View_foreground:
4700                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4701                        setForeground(a.getDrawable(attr));
4702                    }
4703                    break;
4704                case R.styleable.View_foregroundGravity:
4705                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4706                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4707                    }
4708                    break;
4709                case R.styleable.View_foregroundTintMode:
4710                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4711                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4712                    }
4713                    break;
4714                case R.styleable.View_foregroundTint:
4715                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4716                        setForegroundTintList(a.getColorStateList(attr));
4717                    }
4718                    break;
4719                case R.styleable.View_foregroundInsidePadding:
4720                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4721                        if (mForegroundInfo == null) {
4722                            mForegroundInfo = new ForegroundInfo();
4723                        }
4724                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4725                                mForegroundInfo.mInsidePadding);
4726                    }
4727                    break;
4728                case R.styleable.View_scrollIndicators:
4729                    final int scrollIndicators =
4730                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4731                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4732                    if (scrollIndicators != 0) {
4733                        mPrivateFlags3 |= scrollIndicators;
4734                        initializeScrollIndicators = true;
4735                    }
4736                    break;
4737                case R.styleable.View_pointerIcon:
4738                    final int resourceId = a.getResourceId(attr, 0);
4739                    if (resourceId != 0) {
4740                        setPointerIcon(PointerIcon.load(
4741                                context.getResources(), resourceId));
4742                    } else {
4743                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4744                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4745                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4746                        }
4747                    }
4748                    break;
4749                case R.styleable.View_forceHasOverlappingRendering:
4750                    if (a.peekValue(attr) != null) {
4751                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4752                    }
4753                    break;
4754                case R.styleable.View_tooltipText:
4755                    setTooltipText(a.getText(attr));
4756                    break;
4757                case R.styleable.View_keyboardNavigationCluster:
4758                    if (a.peekValue(attr) != null) {
4759                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
4760                    }
4761                    break;
4762                case R.styleable.View_focusedByDefault:
4763                    if (a.peekValue(attr) != null) {
4764                        setFocusedByDefault(a.getBoolean(attr, true));
4765                    }
4766                    break;
4767            }
4768        }
4769
4770        setOverScrollMode(overScrollMode);
4771
4772        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4773        // the resolved layout direction). Those cached values will be used later during padding
4774        // resolution.
4775        mUserPaddingStart = startPadding;
4776        mUserPaddingEnd = endPadding;
4777
4778        if (background != null) {
4779            setBackground(background);
4780        }
4781
4782        // setBackground above will record that padding is currently provided by the background.
4783        // If we have padding specified via xml, record that here instead and use it.
4784        mLeftPaddingDefined = leftPaddingDefined;
4785        mRightPaddingDefined = rightPaddingDefined;
4786
4787        if (padding >= 0) {
4788            leftPadding = padding;
4789            topPadding = padding;
4790            rightPadding = padding;
4791            bottomPadding = padding;
4792            mUserPaddingLeftInitial = padding;
4793            mUserPaddingRightInitial = padding;
4794        } else {
4795            if (paddingHorizontal >= 0) {
4796                leftPadding = paddingHorizontal;
4797                rightPadding = paddingHorizontal;
4798                mUserPaddingLeftInitial = paddingHorizontal;
4799                mUserPaddingRightInitial = paddingHorizontal;
4800            }
4801            if (paddingVertical >= 0) {
4802                topPadding = paddingVertical;
4803                bottomPadding = paddingVertical;
4804            }
4805        }
4806
4807        if (isRtlCompatibilityMode()) {
4808            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4809            // left / right padding are used if defined (meaning here nothing to do). If they are not
4810            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4811            // start / end and resolve them as left / right (layout direction is not taken into account).
4812            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4813            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4814            // defined.
4815            if (!mLeftPaddingDefined && startPaddingDefined) {
4816                leftPadding = startPadding;
4817            }
4818            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4819            if (!mRightPaddingDefined && endPaddingDefined) {
4820                rightPadding = endPadding;
4821            }
4822            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4823        } else {
4824            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4825            // values defined. Otherwise, left /right values are used.
4826            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4827            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4828            // defined.
4829            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4830
4831            if (mLeftPaddingDefined && !hasRelativePadding) {
4832                mUserPaddingLeftInitial = leftPadding;
4833            }
4834            if (mRightPaddingDefined && !hasRelativePadding) {
4835                mUserPaddingRightInitial = rightPadding;
4836            }
4837        }
4838
4839        internalSetPadding(
4840                mUserPaddingLeftInitial,
4841                topPadding >= 0 ? topPadding : mPaddingTop,
4842                mUserPaddingRightInitial,
4843                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4844
4845        if (viewFlagMasks != 0) {
4846            setFlags(viewFlagValues, viewFlagMasks);
4847        }
4848
4849        if (initializeScrollbars) {
4850            initializeScrollbarsInternal(a);
4851        }
4852
4853        if (initializeScrollIndicators) {
4854            initializeScrollIndicatorsInternal();
4855        }
4856
4857        a.recycle();
4858
4859        // Needs to be called after mViewFlags is set
4860        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4861            recomputePadding();
4862        }
4863
4864        if (x != 0 || y != 0) {
4865            scrollTo(x, y);
4866        }
4867
4868        if (transformSet) {
4869            setTranslationX(tx);
4870            setTranslationY(ty);
4871            setTranslationZ(tz);
4872            setElevation(elevation);
4873            setRotation(rotation);
4874            setRotationX(rotationX);
4875            setRotationY(rotationY);
4876            setScaleX(sx);
4877            setScaleY(sy);
4878        }
4879
4880        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4881            setScrollContainer(true);
4882        }
4883
4884        computeOpaqueFlags();
4885    }
4886
4887    /**
4888     * An implementation of OnClickListener that attempts to lazily load a
4889     * named click handling method from a parent or ancestor context.
4890     */
4891    private static class DeclaredOnClickListener implements OnClickListener {
4892        private final View mHostView;
4893        private final String mMethodName;
4894
4895        private Method mResolvedMethod;
4896        private Context mResolvedContext;
4897
4898        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4899            mHostView = hostView;
4900            mMethodName = methodName;
4901        }
4902
4903        @Override
4904        public void onClick(@NonNull View v) {
4905            if (mResolvedMethod == null) {
4906                resolveMethod(mHostView.getContext(), mMethodName);
4907            }
4908
4909            try {
4910                mResolvedMethod.invoke(mResolvedContext, v);
4911            } catch (IllegalAccessException e) {
4912                throw new IllegalStateException(
4913                        "Could not execute non-public method for android:onClick", e);
4914            } catch (InvocationTargetException e) {
4915                throw new IllegalStateException(
4916                        "Could not execute method for android:onClick", e);
4917            }
4918        }
4919
4920        @NonNull
4921        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4922            while (context != null) {
4923                try {
4924                    if (!context.isRestricted()) {
4925                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4926                        if (method != null) {
4927                            mResolvedMethod = method;
4928                            mResolvedContext = context;
4929                            return;
4930                        }
4931                    }
4932                } catch (NoSuchMethodException e) {
4933                    // Failed to find method, keep searching up the hierarchy.
4934                }
4935
4936                if (context instanceof ContextWrapper) {
4937                    context = ((ContextWrapper) context).getBaseContext();
4938                } else {
4939                    // Can't search up the hierarchy, null out and fail.
4940                    context = null;
4941                }
4942            }
4943
4944            final int id = mHostView.getId();
4945            final String idText = id == NO_ID ? "" : " with id '"
4946                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4947            throw new IllegalStateException("Could not find method " + mMethodName
4948                    + "(View) in a parent or ancestor Context for android:onClick "
4949                    + "attribute defined on view " + mHostView.getClass() + idText);
4950        }
4951    }
4952
4953    /**
4954     * Non-public constructor for use in testing
4955     */
4956    View() {
4957        mResources = null;
4958        mRenderNode = RenderNode.create(getClass().getName(), this);
4959    }
4960
4961    final boolean debugDraw() {
4962        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
4963    }
4964
4965    private static SparseArray<String> getAttributeMap() {
4966        if (mAttributeMap == null) {
4967            mAttributeMap = new SparseArray<>();
4968        }
4969        return mAttributeMap;
4970    }
4971
4972    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4973        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4974        final int indexCount = t.getIndexCount();
4975        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4976
4977        int i = 0;
4978
4979        // Store raw XML attributes.
4980        for (int j = 0; j < attrsCount; ++j) {
4981            attributes[i] = attrs.getAttributeName(j);
4982            attributes[i + 1] = attrs.getAttributeValue(j);
4983            i += 2;
4984        }
4985
4986        // Store resolved styleable attributes.
4987        final Resources res = t.getResources();
4988        final SparseArray<String> attributeMap = getAttributeMap();
4989        for (int j = 0; j < indexCount; ++j) {
4990            final int index = t.getIndex(j);
4991            if (!t.hasValueOrEmpty(index)) {
4992                // Value is undefined. Skip it.
4993                continue;
4994            }
4995
4996            final int resourceId = t.getResourceId(index, 0);
4997            if (resourceId == 0) {
4998                // Value is not a reference. Skip it.
4999                continue;
5000            }
5001
5002            String resourceName = attributeMap.get(resourceId);
5003            if (resourceName == null) {
5004                try {
5005                    resourceName = res.getResourceName(resourceId);
5006                } catch (Resources.NotFoundException e) {
5007                    resourceName = "0x" + Integer.toHexString(resourceId);
5008                }
5009                attributeMap.put(resourceId, resourceName);
5010            }
5011
5012            attributes[i] = resourceName;
5013            attributes[i + 1] = t.getString(index);
5014            i += 2;
5015        }
5016
5017        // Trim to fit contents.
5018        final String[] trimmed = new String[i];
5019        System.arraycopy(attributes, 0, trimmed, 0, i);
5020        mAttributes = trimmed;
5021    }
5022
5023    public String toString() {
5024        StringBuilder out = new StringBuilder(128);
5025        out.append(getClass().getName());
5026        out.append('{');
5027        out.append(Integer.toHexString(System.identityHashCode(this)));
5028        out.append(' ');
5029        switch (mViewFlags&VISIBILITY_MASK) {
5030            case VISIBLE: out.append('V'); break;
5031            case INVISIBLE: out.append('I'); break;
5032            case GONE: out.append('G'); break;
5033            default: out.append('.'); break;
5034        }
5035        out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.');
5036        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
5037        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
5038        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
5039        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
5040        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
5041        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
5042        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
5043        out.append(' ');
5044        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
5045        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
5046        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
5047        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
5048            out.append('p');
5049        } else {
5050            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5051        }
5052        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5053        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5054        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5055        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5056        out.append(' ');
5057        out.append(mLeft);
5058        out.append(',');
5059        out.append(mTop);
5060        out.append('-');
5061        out.append(mRight);
5062        out.append(',');
5063        out.append(mBottom);
5064        final int id = getId();
5065        if (id != NO_ID) {
5066            out.append(" #");
5067            out.append(Integer.toHexString(id));
5068            final Resources r = mResources;
5069            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5070                try {
5071                    String pkgname;
5072                    switch (id&0xff000000) {
5073                        case 0x7f000000:
5074                            pkgname="app";
5075                            break;
5076                        case 0x01000000:
5077                            pkgname="android";
5078                            break;
5079                        default:
5080                            pkgname = r.getResourcePackageName(id);
5081                            break;
5082                    }
5083                    String typename = r.getResourceTypeName(id);
5084                    String entryname = r.getResourceEntryName(id);
5085                    out.append(" ");
5086                    out.append(pkgname);
5087                    out.append(":");
5088                    out.append(typename);
5089                    out.append("/");
5090                    out.append(entryname);
5091                } catch (Resources.NotFoundException e) {
5092                }
5093            }
5094        }
5095        out.append("}");
5096        return out.toString();
5097    }
5098
5099    /**
5100     * <p>
5101     * Initializes the fading edges from a given set of styled attributes. This
5102     * method should be called by subclasses that need fading edges and when an
5103     * instance of these subclasses is created programmatically rather than
5104     * being inflated from XML. This method is automatically called when the XML
5105     * is inflated.
5106     * </p>
5107     *
5108     * @param a the styled attributes set to initialize the fading edges from
5109     *
5110     * @removed
5111     */
5112    protected void initializeFadingEdge(TypedArray a) {
5113        // This method probably shouldn't have been included in the SDK to begin with.
5114        // It relies on 'a' having been initialized using an attribute filter array that is
5115        // not publicly available to the SDK. The old method has been renamed
5116        // to initializeFadingEdgeInternal and hidden for framework use only;
5117        // this one initializes using defaults to make it safe to call for apps.
5118
5119        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5120
5121        initializeFadingEdgeInternal(arr);
5122
5123        arr.recycle();
5124    }
5125
5126    /**
5127     * <p>
5128     * Initializes the fading edges from a given set of styled attributes. This
5129     * method should be called by subclasses that need fading edges and when an
5130     * instance of these subclasses is created programmatically rather than
5131     * being inflated from XML. This method is automatically called when the XML
5132     * is inflated.
5133     * </p>
5134     *
5135     * @param a the styled attributes set to initialize the fading edges from
5136     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5137     */
5138    protected void initializeFadingEdgeInternal(TypedArray a) {
5139        initScrollCache();
5140
5141        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5142                R.styleable.View_fadingEdgeLength,
5143                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5144    }
5145
5146    /**
5147     * Returns the size of the vertical faded edges used to indicate that more
5148     * content in this view is visible.
5149     *
5150     * @return The size in pixels of the vertical faded edge or 0 if vertical
5151     *         faded edges are not enabled for this view.
5152     * @attr ref android.R.styleable#View_fadingEdgeLength
5153     */
5154    public int getVerticalFadingEdgeLength() {
5155        if (isVerticalFadingEdgeEnabled()) {
5156            ScrollabilityCache cache = mScrollCache;
5157            if (cache != null) {
5158                return cache.fadingEdgeLength;
5159            }
5160        }
5161        return 0;
5162    }
5163
5164    /**
5165     * Set the size of the faded edge used to indicate that more content in this
5166     * view is available.  Will not change whether the fading edge is enabled; use
5167     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5168     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5169     * for the vertical or horizontal fading edges.
5170     *
5171     * @param length The size in pixels of the faded edge used to indicate that more
5172     *        content in this view is visible.
5173     */
5174    public void setFadingEdgeLength(int length) {
5175        initScrollCache();
5176        mScrollCache.fadingEdgeLength = length;
5177    }
5178
5179    /**
5180     * Returns the size of the horizontal faded edges used to indicate that more
5181     * content in this view is visible.
5182     *
5183     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5184     *         faded edges are not enabled for this view.
5185     * @attr ref android.R.styleable#View_fadingEdgeLength
5186     */
5187    public int getHorizontalFadingEdgeLength() {
5188        if (isHorizontalFadingEdgeEnabled()) {
5189            ScrollabilityCache cache = mScrollCache;
5190            if (cache != null) {
5191                return cache.fadingEdgeLength;
5192            }
5193        }
5194        return 0;
5195    }
5196
5197    /**
5198     * Returns the width of the vertical scrollbar.
5199     *
5200     * @return The width in pixels of the vertical scrollbar or 0 if there
5201     *         is no vertical scrollbar.
5202     */
5203    public int getVerticalScrollbarWidth() {
5204        ScrollabilityCache cache = mScrollCache;
5205        if (cache != null) {
5206            ScrollBarDrawable scrollBar = cache.scrollBar;
5207            if (scrollBar != null) {
5208                int size = scrollBar.getSize(true);
5209                if (size <= 0) {
5210                    size = cache.scrollBarSize;
5211                }
5212                return size;
5213            }
5214            return 0;
5215        }
5216        return 0;
5217    }
5218
5219    /**
5220     * Returns the height of the horizontal scrollbar.
5221     *
5222     * @return The height in pixels of the horizontal scrollbar or 0 if
5223     *         there is no horizontal scrollbar.
5224     */
5225    protected int getHorizontalScrollbarHeight() {
5226        ScrollabilityCache cache = mScrollCache;
5227        if (cache != null) {
5228            ScrollBarDrawable scrollBar = cache.scrollBar;
5229            if (scrollBar != null) {
5230                int size = scrollBar.getSize(false);
5231                if (size <= 0) {
5232                    size = cache.scrollBarSize;
5233                }
5234                return size;
5235            }
5236            return 0;
5237        }
5238        return 0;
5239    }
5240
5241    /**
5242     * <p>
5243     * Initializes the scrollbars from a given set of styled attributes. This
5244     * method should be called by subclasses that need scrollbars and when an
5245     * instance of these subclasses is created programmatically rather than
5246     * being inflated from XML. This method is automatically called when the XML
5247     * is inflated.
5248     * </p>
5249     *
5250     * @param a the styled attributes set to initialize the scrollbars from
5251     *
5252     * @removed
5253     */
5254    protected void initializeScrollbars(TypedArray a) {
5255        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5256        // using the View filter array which is not available to the SDK. As such, internal
5257        // framework usage now uses initializeScrollbarsInternal and we grab a default
5258        // TypedArray with the right filter instead here.
5259        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5260
5261        initializeScrollbarsInternal(arr);
5262
5263        // We ignored the method parameter. Recycle the one we actually did use.
5264        arr.recycle();
5265    }
5266
5267    /**
5268     * <p>
5269     * Initializes the scrollbars from a given set of styled attributes. This
5270     * method should be called by subclasses that need scrollbars and when an
5271     * instance of these subclasses is created programmatically rather than
5272     * being inflated from XML. This method is automatically called when the XML
5273     * is inflated.
5274     * </p>
5275     *
5276     * @param a the styled attributes set to initialize the scrollbars from
5277     * @hide
5278     */
5279    protected void initializeScrollbarsInternal(TypedArray a) {
5280        initScrollCache();
5281
5282        final ScrollabilityCache scrollabilityCache = mScrollCache;
5283
5284        if (scrollabilityCache.scrollBar == null) {
5285            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5286            scrollabilityCache.scrollBar.setState(getDrawableState());
5287            scrollabilityCache.scrollBar.setCallback(this);
5288        }
5289
5290        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5291
5292        if (!fadeScrollbars) {
5293            scrollabilityCache.state = ScrollabilityCache.ON;
5294        }
5295        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5296
5297
5298        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5299                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5300                        .getScrollBarFadeDuration());
5301        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5302                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5303                ViewConfiguration.getScrollDefaultDelay());
5304
5305
5306        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5307                com.android.internal.R.styleable.View_scrollbarSize,
5308                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5309
5310        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5311        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5312
5313        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5314        if (thumb != null) {
5315            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5316        }
5317
5318        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5319                false);
5320        if (alwaysDraw) {
5321            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5322        }
5323
5324        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5325        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5326
5327        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5328        if (thumb != null) {
5329            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5330        }
5331
5332        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5333                false);
5334        if (alwaysDraw) {
5335            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5336        }
5337
5338        // Apply layout direction to the new Drawables if needed
5339        final int layoutDirection = getLayoutDirection();
5340        if (track != null) {
5341            track.setLayoutDirection(layoutDirection);
5342        }
5343        if (thumb != null) {
5344            thumb.setLayoutDirection(layoutDirection);
5345        }
5346
5347        // Re-apply user/background padding so that scrollbar(s) get added
5348        resolvePadding();
5349    }
5350
5351    private void initializeScrollIndicatorsInternal() {
5352        // Some day maybe we'll break this into top/left/start/etc. and let the
5353        // client control it. Until then, you can have any scroll indicator you
5354        // want as long as it's a 1dp foreground-colored rectangle.
5355        if (mScrollIndicatorDrawable == null) {
5356            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5357        }
5358    }
5359
5360    /**
5361     * <p>
5362     * Initalizes the scrollability cache if necessary.
5363     * </p>
5364     */
5365    private void initScrollCache() {
5366        if (mScrollCache == null) {
5367            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5368        }
5369    }
5370
5371    private ScrollabilityCache getScrollCache() {
5372        initScrollCache();
5373        return mScrollCache;
5374    }
5375
5376    /**
5377     * Set the position of the vertical scroll bar. Should be one of
5378     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5379     * {@link #SCROLLBAR_POSITION_RIGHT}.
5380     *
5381     * @param position Where the vertical scroll bar should be positioned.
5382     */
5383    public void setVerticalScrollbarPosition(int position) {
5384        if (mVerticalScrollbarPosition != position) {
5385            mVerticalScrollbarPosition = position;
5386            computeOpaqueFlags();
5387            resolvePadding();
5388        }
5389    }
5390
5391    /**
5392     * @return The position where the vertical scroll bar will show, if applicable.
5393     * @see #setVerticalScrollbarPosition(int)
5394     */
5395    public int getVerticalScrollbarPosition() {
5396        return mVerticalScrollbarPosition;
5397    }
5398
5399    boolean isOnScrollbar(float x, float y) {
5400        if (mScrollCache == null) {
5401            return false;
5402        }
5403        x += getScrollX();
5404        y += getScrollY();
5405        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5406            final Rect bounds = mScrollCache.mScrollBarBounds;
5407            getVerticalScrollBarBounds(bounds);
5408            if (bounds.contains((int)x, (int)y)) {
5409                return true;
5410            }
5411        }
5412        if (isHorizontalScrollBarEnabled()) {
5413            final Rect bounds = mScrollCache.mScrollBarBounds;
5414            getHorizontalScrollBarBounds(bounds);
5415            if (bounds.contains((int)x, (int)y)) {
5416                return true;
5417            }
5418        }
5419        return false;
5420    }
5421
5422    boolean isOnScrollbarThumb(float x, float y) {
5423        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5424    }
5425
5426    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5427        if (mScrollCache == null) {
5428            return false;
5429        }
5430        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5431            x += getScrollX();
5432            y += getScrollY();
5433            final Rect bounds = mScrollCache.mScrollBarBounds;
5434            getVerticalScrollBarBounds(bounds);
5435            final int range = computeVerticalScrollRange();
5436            final int offset = computeVerticalScrollOffset();
5437            final int extent = computeVerticalScrollExtent();
5438            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5439                    extent, range);
5440            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5441                    extent, range, offset);
5442            final int thumbTop = bounds.top + thumbOffset;
5443            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5444                    && y <= thumbTop + thumbLength) {
5445                return true;
5446            }
5447        }
5448        return false;
5449    }
5450
5451    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5452        if (mScrollCache == null) {
5453            return false;
5454        }
5455        if (isHorizontalScrollBarEnabled()) {
5456            x += getScrollX();
5457            y += getScrollY();
5458            final Rect bounds = mScrollCache.mScrollBarBounds;
5459            getHorizontalScrollBarBounds(bounds);
5460            final int range = computeHorizontalScrollRange();
5461            final int offset = computeHorizontalScrollOffset();
5462            final int extent = computeHorizontalScrollExtent();
5463            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5464                    extent, range);
5465            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5466                    extent, range, offset);
5467            final int thumbLeft = bounds.left + thumbOffset;
5468            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5469                    && y <= bounds.bottom) {
5470                return true;
5471            }
5472        }
5473        return false;
5474    }
5475
5476    boolean isDraggingScrollBar() {
5477        return mScrollCache != null
5478                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5479    }
5480
5481    /**
5482     * Sets the state of all scroll indicators.
5483     * <p>
5484     * See {@link #setScrollIndicators(int, int)} for usage information.
5485     *
5486     * @param indicators a bitmask of indicators that should be enabled, or
5487     *                   {@code 0} to disable all indicators
5488     * @see #setScrollIndicators(int, int)
5489     * @see #getScrollIndicators()
5490     * @attr ref android.R.styleable#View_scrollIndicators
5491     */
5492    public void setScrollIndicators(@ScrollIndicators int indicators) {
5493        setScrollIndicators(indicators,
5494                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5495    }
5496
5497    /**
5498     * Sets the state of the scroll indicators specified by the mask. To change
5499     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5500     * <p>
5501     * When a scroll indicator is enabled, it will be displayed if the view
5502     * can scroll in the direction of the indicator.
5503     * <p>
5504     * Multiple indicator types may be enabled or disabled by passing the
5505     * logical OR of the desired types. If multiple types are specified, they
5506     * will all be set to the same enabled state.
5507     * <p>
5508     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5509     *
5510     * @param indicators the indicator direction, or the logical OR of multiple
5511     *             indicator directions. One or more of:
5512     *             <ul>
5513     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5514     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5515     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5516     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5517     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5518     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5519     *             </ul>
5520     * @see #setScrollIndicators(int)
5521     * @see #getScrollIndicators()
5522     * @attr ref android.R.styleable#View_scrollIndicators
5523     */
5524    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5525        // Shift and sanitize mask.
5526        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5527        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5528
5529        // Shift and mask indicators.
5530        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5531        indicators &= mask;
5532
5533        // Merge with non-masked flags.
5534        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5535
5536        if (mPrivateFlags3 != updatedFlags) {
5537            mPrivateFlags3 = updatedFlags;
5538
5539            if (indicators != 0) {
5540                initializeScrollIndicatorsInternal();
5541            }
5542            invalidate();
5543        }
5544    }
5545
5546    /**
5547     * Returns a bitmask representing the enabled scroll indicators.
5548     * <p>
5549     * For example, if the top and left scroll indicators are enabled and all
5550     * other indicators are disabled, the return value will be
5551     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5552     * <p>
5553     * To check whether the bottom scroll indicator is enabled, use the value
5554     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5555     *
5556     * @return a bitmask representing the enabled scroll indicators
5557     */
5558    @ScrollIndicators
5559    public int getScrollIndicators() {
5560        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5561                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5562    }
5563
5564    ListenerInfo getListenerInfo() {
5565        if (mListenerInfo != null) {
5566            return mListenerInfo;
5567        }
5568        mListenerInfo = new ListenerInfo();
5569        return mListenerInfo;
5570    }
5571
5572    /**
5573     * Register a callback to be invoked when the scroll X or Y positions of
5574     * this view change.
5575     * <p>
5576     * <b>Note:</b> Some views handle scrolling independently from View and may
5577     * have their own separate listeners for scroll-type events. For example,
5578     * {@link android.widget.ListView ListView} allows clients to register an
5579     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5580     * to listen for changes in list scroll position.
5581     *
5582     * @param l The listener to notify when the scroll X or Y position changes.
5583     * @see android.view.View#getScrollX()
5584     * @see android.view.View#getScrollY()
5585     */
5586    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5587        getListenerInfo().mOnScrollChangeListener = l;
5588    }
5589
5590    /**
5591     * Register a callback to be invoked when focus of this view changed.
5592     *
5593     * @param l The callback that will run.
5594     */
5595    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5596        getListenerInfo().mOnFocusChangeListener = l;
5597    }
5598
5599    /**
5600     * Add a listener that will be called when the bounds of the view change due to
5601     * layout processing.
5602     *
5603     * @param listener The listener that will be called when layout bounds change.
5604     */
5605    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5606        ListenerInfo li = getListenerInfo();
5607        if (li.mOnLayoutChangeListeners == null) {
5608            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5609        }
5610        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5611            li.mOnLayoutChangeListeners.add(listener);
5612        }
5613    }
5614
5615    /**
5616     * Remove a listener for layout changes.
5617     *
5618     * @param listener The listener for layout bounds change.
5619     */
5620    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5621        ListenerInfo li = mListenerInfo;
5622        if (li == null || li.mOnLayoutChangeListeners == null) {
5623            return;
5624        }
5625        li.mOnLayoutChangeListeners.remove(listener);
5626    }
5627
5628    /**
5629     * Add a listener for attach state changes.
5630     *
5631     * This listener will be called whenever this view is attached or detached
5632     * from a window. Remove the listener using
5633     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5634     *
5635     * @param listener Listener to attach
5636     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5637     */
5638    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5639        ListenerInfo li = getListenerInfo();
5640        if (li.mOnAttachStateChangeListeners == null) {
5641            li.mOnAttachStateChangeListeners
5642                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5643        }
5644        li.mOnAttachStateChangeListeners.add(listener);
5645    }
5646
5647    /**
5648     * Remove a listener for attach state changes. The listener will receive no further
5649     * notification of window attach/detach events.
5650     *
5651     * @param listener Listener to remove
5652     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5653     */
5654    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5655        ListenerInfo li = mListenerInfo;
5656        if (li == null || li.mOnAttachStateChangeListeners == null) {
5657            return;
5658        }
5659        li.mOnAttachStateChangeListeners.remove(listener);
5660    }
5661
5662    /**
5663     * Returns the focus-change callback registered for this view.
5664     *
5665     * @return The callback, or null if one is not registered.
5666     */
5667    public OnFocusChangeListener getOnFocusChangeListener() {
5668        ListenerInfo li = mListenerInfo;
5669        return li != null ? li.mOnFocusChangeListener : null;
5670    }
5671
5672    /**
5673     * Register a callback to be invoked when this view is clicked. If this view is not
5674     * clickable, it becomes clickable.
5675     *
5676     * @param l The callback that will run
5677     *
5678     * @see #setClickable(boolean)
5679     */
5680    public void setOnClickListener(@Nullable OnClickListener l) {
5681        if (!isClickable()) {
5682            setClickable(true);
5683        }
5684        getListenerInfo().mOnClickListener = l;
5685    }
5686
5687    /**
5688     * Return whether this view has an attached OnClickListener.  Returns
5689     * true if there is a listener, false if there is none.
5690     */
5691    public boolean hasOnClickListeners() {
5692        ListenerInfo li = mListenerInfo;
5693        return (li != null && li.mOnClickListener != null);
5694    }
5695
5696    /**
5697     * Register a callback to be invoked when this view is clicked and held. If this view is not
5698     * long clickable, it becomes long clickable.
5699     *
5700     * @param l The callback that will run
5701     *
5702     * @see #setLongClickable(boolean)
5703     */
5704    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5705        if (!isLongClickable()) {
5706            setLongClickable(true);
5707        }
5708        getListenerInfo().mOnLongClickListener = l;
5709    }
5710
5711    /**
5712     * Register a callback to be invoked when this view is context clicked. If the view is not
5713     * context clickable, it becomes context clickable.
5714     *
5715     * @param l The callback that will run
5716     * @see #setContextClickable(boolean)
5717     */
5718    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5719        if (!isContextClickable()) {
5720            setContextClickable(true);
5721        }
5722        getListenerInfo().mOnContextClickListener = l;
5723    }
5724
5725    /**
5726     * Register a callback to be invoked when the context menu for this view is
5727     * being built. If this view is not long clickable, it becomes long clickable.
5728     *
5729     * @param l The callback that will run
5730     *
5731     */
5732    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5733        if (!isLongClickable()) {
5734            setLongClickable(true);
5735        }
5736        getListenerInfo().mOnCreateContextMenuListener = l;
5737    }
5738
5739    /**
5740     * Set an observer to collect stats for each frame rendered for this view.
5741     *
5742     * @hide
5743     */
5744    public void addFrameMetricsListener(Window window,
5745            Window.OnFrameMetricsAvailableListener listener,
5746            Handler handler) {
5747        if (mAttachInfo != null) {
5748            if (mAttachInfo.mThreadedRenderer != null) {
5749                if (mFrameMetricsObservers == null) {
5750                    mFrameMetricsObservers = new ArrayList<>();
5751                }
5752
5753                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5754                        handler.getLooper(), listener);
5755                mFrameMetricsObservers.add(fmo);
5756                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
5757            } else {
5758                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5759            }
5760        } else {
5761            if (mFrameMetricsObservers == null) {
5762                mFrameMetricsObservers = new ArrayList<>();
5763            }
5764
5765            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5766                    handler.getLooper(), listener);
5767            mFrameMetricsObservers.add(fmo);
5768        }
5769    }
5770
5771    /**
5772     * Remove observer configured to collect frame stats for this view.
5773     *
5774     * @hide
5775     */
5776    public void removeFrameMetricsListener(
5777            Window.OnFrameMetricsAvailableListener listener) {
5778        ThreadedRenderer renderer = getThreadedRenderer();
5779        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5780        if (fmo == null) {
5781            throw new IllegalArgumentException(
5782                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5783        }
5784
5785        if (mFrameMetricsObservers != null) {
5786            mFrameMetricsObservers.remove(fmo);
5787            if (renderer != null) {
5788                renderer.removeFrameMetricsObserver(fmo);
5789            }
5790        }
5791    }
5792
5793    private void registerPendingFrameMetricsObservers() {
5794        if (mFrameMetricsObservers != null) {
5795            ThreadedRenderer renderer = getThreadedRenderer();
5796            if (renderer != null) {
5797                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5798                    renderer.addFrameMetricsObserver(fmo);
5799                }
5800            } else {
5801                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5802            }
5803        }
5804    }
5805
5806    private FrameMetricsObserver findFrameMetricsObserver(
5807            Window.OnFrameMetricsAvailableListener listener) {
5808        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5809            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5810            if (observer.mListener == listener) {
5811                return observer;
5812            }
5813        }
5814
5815        return null;
5816    }
5817
5818    /**
5819     * Call this view's OnClickListener, if it is defined.  Performs all normal
5820     * actions associated with clicking: reporting accessibility event, playing
5821     * a sound, etc.
5822     *
5823     * @return True there was an assigned OnClickListener that was called, false
5824     *         otherwise is returned.
5825     */
5826    public boolean performClick() {
5827        final boolean result;
5828        final ListenerInfo li = mListenerInfo;
5829        if (li != null && li.mOnClickListener != null) {
5830            playSoundEffect(SoundEffectConstants.CLICK);
5831            li.mOnClickListener.onClick(this);
5832            result = true;
5833        } else {
5834            result = false;
5835        }
5836
5837        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5838        return result;
5839    }
5840
5841    /**
5842     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5843     * this only calls the listener, and does not do any associated clicking
5844     * actions like reporting an accessibility event.
5845     *
5846     * @return True there was an assigned OnClickListener that was called, false
5847     *         otherwise is returned.
5848     */
5849    public boolean callOnClick() {
5850        ListenerInfo li = mListenerInfo;
5851        if (li != null && li.mOnClickListener != null) {
5852            li.mOnClickListener.onClick(this);
5853            return true;
5854        }
5855        return false;
5856    }
5857
5858    /**
5859     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5860     * context menu if the OnLongClickListener did not consume the event.
5861     *
5862     * @return {@code true} if one of the above receivers consumed the event,
5863     *         {@code false} otherwise
5864     */
5865    public boolean performLongClick() {
5866        return performLongClickInternal(mLongClickX, mLongClickY);
5867    }
5868
5869    /**
5870     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5871     * context menu if the OnLongClickListener did not consume the event,
5872     * anchoring it to an (x,y) coordinate.
5873     *
5874     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5875     *          to disable anchoring
5876     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5877     *          to disable anchoring
5878     * @return {@code true} if one of the above receivers consumed the event,
5879     *         {@code false} otherwise
5880     */
5881    public boolean performLongClick(float x, float y) {
5882        mLongClickX = x;
5883        mLongClickY = y;
5884        final boolean handled = performLongClick();
5885        mLongClickX = Float.NaN;
5886        mLongClickY = Float.NaN;
5887        return handled;
5888    }
5889
5890    /**
5891     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5892     * context menu if the OnLongClickListener did not consume the event,
5893     * optionally anchoring it to an (x,y) coordinate.
5894     *
5895     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5896     *          to disable anchoring
5897     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5898     *          to disable anchoring
5899     * @return {@code true} if one of the above receivers consumed the event,
5900     *         {@code false} otherwise
5901     */
5902    private boolean performLongClickInternal(float x, float y) {
5903        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5904
5905        boolean handled = false;
5906        final ListenerInfo li = mListenerInfo;
5907        if (li != null && li.mOnLongClickListener != null) {
5908            handled = li.mOnLongClickListener.onLongClick(View.this);
5909        }
5910        if (!handled) {
5911            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5912            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5913        }
5914        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
5915            if (!handled) {
5916                handled = showLongClickTooltip((int) x, (int) y);
5917            }
5918        }
5919        if (handled) {
5920            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5921        }
5922        return handled;
5923    }
5924
5925    /**
5926     * Call this view's OnContextClickListener, if it is defined.
5927     *
5928     * @param x the x coordinate of the context click
5929     * @param y the y coordinate of the context click
5930     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5931     *         otherwise.
5932     */
5933    public boolean performContextClick(float x, float y) {
5934        return performContextClick();
5935    }
5936
5937    /**
5938     * Call this view's OnContextClickListener, if it is defined.
5939     *
5940     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5941     *         otherwise.
5942     */
5943    public boolean performContextClick() {
5944        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5945
5946        boolean handled = false;
5947        ListenerInfo li = mListenerInfo;
5948        if (li != null && li.mOnContextClickListener != null) {
5949            handled = li.mOnContextClickListener.onContextClick(View.this);
5950        }
5951        if (handled) {
5952            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5953        }
5954        return handled;
5955    }
5956
5957    /**
5958     * Performs button-related actions during a touch down event.
5959     *
5960     * @param event The event.
5961     * @return True if the down was consumed.
5962     *
5963     * @hide
5964     */
5965    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5966        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5967            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5968            showContextMenu(event.getX(), event.getY());
5969            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5970            return true;
5971        }
5972        return false;
5973    }
5974
5975    /**
5976     * Shows the context menu for this view.
5977     *
5978     * @return {@code true} if the context menu was shown, {@code false}
5979     *         otherwise
5980     * @see #showContextMenu(float, float)
5981     */
5982    public boolean showContextMenu() {
5983        return getParent().showContextMenuForChild(this);
5984    }
5985
5986    /**
5987     * Shows the context menu for this view anchored to the specified
5988     * view-relative coordinate.
5989     *
5990     * @param x the X coordinate in pixels relative to the view to which the
5991     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5992     * @param y the Y coordinate in pixels relative to the view to which the
5993     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5994     * @return {@code true} if the context menu was shown, {@code false}
5995     *         otherwise
5996     */
5997    public boolean showContextMenu(float x, float y) {
5998        return getParent().showContextMenuForChild(this, x, y);
5999    }
6000
6001    /**
6002     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
6003     *
6004     * @param callback Callback that will control the lifecycle of the action mode
6005     * @return The new action mode if it is started, null otherwise
6006     *
6007     * @see ActionMode
6008     * @see #startActionMode(android.view.ActionMode.Callback, int)
6009     */
6010    public ActionMode startActionMode(ActionMode.Callback callback) {
6011        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
6012    }
6013
6014    /**
6015     * Start an action mode with the given type.
6016     *
6017     * @param callback Callback that will control the lifecycle of the action mode
6018     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6019     * @return The new action mode if it is started, null otherwise
6020     *
6021     * @see ActionMode
6022     */
6023    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6024        ViewParent parent = getParent();
6025        if (parent == null) return null;
6026        try {
6027            return parent.startActionModeForChild(this, callback, type);
6028        } catch (AbstractMethodError ame) {
6029            // Older implementations of custom views might not implement this.
6030            return parent.startActionModeForChild(this, callback);
6031        }
6032    }
6033
6034    /**
6035     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
6036     * Context, creating a unique View identifier to retrieve the result.
6037     *
6038     * @param intent The Intent to be started.
6039     * @param requestCode The request code to use.
6040     * @hide
6041     */
6042    public void startActivityForResult(Intent intent, int requestCode) {
6043        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
6044        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
6045    }
6046
6047    /**
6048     * If this View corresponds to the calling who, dispatches the activity result.
6049     * @param who The identifier for the targeted View to receive the result.
6050     * @param requestCode The integer request code originally supplied to
6051     *                    startActivityForResult(), allowing you to identify who this
6052     *                    result came from.
6053     * @param resultCode The integer result code returned by the child activity
6054     *                   through its setResult().
6055     * @param data An Intent, which can return result data to the caller
6056     *               (various data can be attached to Intent "extras").
6057     * @return {@code true} if the activity result was dispatched.
6058     * @hide
6059     */
6060    public boolean dispatchActivityResult(
6061            String who, int requestCode, int resultCode, Intent data) {
6062        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6063            onActivityResult(requestCode, resultCode, data);
6064            mStartActivityRequestWho = null;
6065            return true;
6066        }
6067        return false;
6068    }
6069
6070    /**
6071     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6072     *
6073     * @param requestCode The integer request code originally supplied to
6074     *                    startActivityForResult(), allowing you to identify who this
6075     *                    result came from.
6076     * @param resultCode The integer result code returned by the child activity
6077     *                   through its setResult().
6078     * @param data An Intent, which can return result data to the caller
6079     *               (various data can be attached to Intent "extras").
6080     * @hide
6081     */
6082    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6083        // Do nothing.
6084    }
6085
6086    /**
6087     * Register a callback to be invoked when a hardware key is pressed in this view.
6088     * Key presses in software input methods will generally not trigger the methods of
6089     * this listener.
6090     * @param l the key listener to attach to this view
6091     */
6092    public void setOnKeyListener(OnKeyListener l) {
6093        getListenerInfo().mOnKeyListener = l;
6094    }
6095
6096    /**
6097     * Register a callback to be invoked when a touch event is sent to this view.
6098     * @param l the touch listener to attach to this view
6099     */
6100    public void setOnTouchListener(OnTouchListener l) {
6101        getListenerInfo().mOnTouchListener = l;
6102    }
6103
6104    /**
6105     * Register a callback to be invoked when a generic motion event is sent to this view.
6106     * @param l the generic motion listener to attach to this view
6107     */
6108    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6109        getListenerInfo().mOnGenericMotionListener = l;
6110    }
6111
6112    /**
6113     * Register a callback to be invoked when a hover event is sent to this view.
6114     * @param l the hover listener to attach to this view
6115     */
6116    public void setOnHoverListener(OnHoverListener l) {
6117        getListenerInfo().mOnHoverListener = l;
6118    }
6119
6120    /**
6121     * Register a drag event listener callback object for this View. The parameter is
6122     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6123     * View, the system calls the
6124     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6125     * @param l An implementation of {@link android.view.View.OnDragListener}.
6126     */
6127    public void setOnDragListener(OnDragListener l) {
6128        getListenerInfo().mOnDragListener = l;
6129    }
6130
6131    /**
6132     * Give this view focus. This will cause
6133     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6134     *
6135     * Note: this does not check whether this {@link View} should get focus, it just
6136     * gives it focus no matter what.  It should only be called internally by framework
6137     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6138     *
6139     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6140     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6141     *        focus moved when requestFocus() is called. It may not always
6142     *        apply, in which case use the default View.FOCUS_DOWN.
6143     * @param previouslyFocusedRect The rectangle of the view that had focus
6144     *        prior in this View's coordinate system.
6145     */
6146    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6147        if (DBG) {
6148            System.out.println(this + " requestFocus()");
6149        }
6150
6151        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6152            mPrivateFlags |= PFLAG_FOCUSED;
6153
6154            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6155
6156            if (mParent != null) {
6157                mParent.requestChildFocus(this, this);
6158                if (mParent instanceof ViewGroup) {
6159                    ((ViewGroup) mParent).setDefaultFocus(this);
6160                }
6161            }
6162
6163            if (mAttachInfo != null) {
6164                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6165            }
6166
6167            onFocusChanged(true, direction, previouslyFocusedRect);
6168            refreshDrawableState();
6169        }
6170    }
6171
6172    /**
6173     * Sets this view's preference for reveal behavior when it gains focus.
6174     *
6175     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6176     * this view would prefer to be brought fully into view when it gains focus.
6177     * For example, a text field that a user is meant to type into. Other views such
6178     * as scrolling containers may prefer to opt-out of this behavior.</p>
6179     *
6180     * <p>The default value for views is true, though subclasses may change this
6181     * based on their preferred behavior.</p>
6182     *
6183     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6184     *
6185     * @see #getRevealOnFocusHint()
6186     */
6187    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6188        if (revealOnFocus) {
6189            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6190        } else {
6191            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6192        }
6193    }
6194
6195    /**
6196     * Returns this view's preference for reveal behavior when it gains focus.
6197     *
6198     * <p>When this method returns true for a child view requesting focus, ancestor
6199     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6200     * should make a best effort to make the newly focused child fully visible to the user.
6201     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6202     * other properties affecting visibility to the user as part of the focus change.</p>
6203     *
6204     * @return true if this view would prefer to become fully visible when it gains focus,
6205     *         false if it would prefer not to disrupt scroll positioning
6206     *
6207     * @see #setRevealOnFocusHint(boolean)
6208     */
6209    public final boolean getRevealOnFocusHint() {
6210        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6211    }
6212
6213    /**
6214     * Populates <code>outRect</code> with the hotspot bounds. By default,
6215     * the hotspot bounds are identical to the screen bounds.
6216     *
6217     * @param outRect rect to populate with hotspot bounds
6218     * @hide Only for internal use by views and widgets.
6219     */
6220    public void getHotspotBounds(Rect outRect) {
6221        final Drawable background = getBackground();
6222        if (background != null) {
6223            background.getHotspotBounds(outRect);
6224        } else {
6225            getBoundsOnScreen(outRect);
6226        }
6227    }
6228
6229    /**
6230     * Request that a rectangle of this view be visible on the screen,
6231     * scrolling if necessary just enough.
6232     *
6233     * <p>A View should call this if it maintains some notion of which part
6234     * of its content is interesting.  For example, a text editing view
6235     * should call this when its cursor moves.
6236     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6237     * It should not be affected by which part of the View is currently visible or its scroll
6238     * position.
6239     *
6240     * @param rectangle The rectangle in the View's content coordinate space
6241     * @return Whether any parent scrolled.
6242     */
6243    public boolean requestRectangleOnScreen(Rect rectangle) {
6244        return requestRectangleOnScreen(rectangle, false);
6245    }
6246
6247    /**
6248     * Request that a rectangle of this view be visible on the screen,
6249     * scrolling if necessary just enough.
6250     *
6251     * <p>A View should call this if it maintains some notion of which part
6252     * of its content is interesting.  For example, a text editing view
6253     * should call this when its cursor moves.
6254     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6255     * It should not be affected by which part of the View is currently visible or its scroll
6256     * position.
6257     * <p>When <code>immediate</code> is set to true, scrolling will not be
6258     * animated.
6259     *
6260     * @param rectangle The rectangle in the View's content coordinate space
6261     * @param immediate True to forbid animated scrolling, false otherwise
6262     * @return Whether any parent scrolled.
6263     */
6264    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6265        if (mParent == null) {
6266            return false;
6267        }
6268
6269        View child = this;
6270
6271        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6272        position.set(rectangle);
6273
6274        ViewParent parent = mParent;
6275        boolean scrolled = false;
6276        while (parent != null) {
6277            rectangle.set((int) position.left, (int) position.top,
6278                    (int) position.right, (int) position.bottom);
6279
6280            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6281
6282            if (!(parent instanceof View)) {
6283                break;
6284            }
6285
6286            // move it from child's content coordinate space to parent's content coordinate space
6287            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6288
6289            child = (View) parent;
6290            parent = child.getParent();
6291        }
6292
6293        return scrolled;
6294    }
6295
6296    /**
6297     * Called when this view wants to give up focus. If focus is cleared
6298     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6299     * <p>
6300     * <strong>Note:</strong> When a View clears focus the framework is trying
6301     * to give focus to the first focusable View from the top. Hence, if this
6302     * View is the first from the top that can take focus, then all callbacks
6303     * related to clearing focus will be invoked after which the framework will
6304     * give focus to this view.
6305     * </p>
6306     */
6307    public void clearFocus() {
6308        if (DBG) {
6309            System.out.println(this + " clearFocus()");
6310        }
6311
6312        clearFocusInternal(null, true, true);
6313    }
6314
6315    /**
6316     * Clears focus from the view, optionally propagating the change up through
6317     * the parent hierarchy and requesting that the root view place new focus.
6318     *
6319     * @param propagate whether to propagate the change up through the parent
6320     *            hierarchy
6321     * @param refocus when propagate is true, specifies whether to request the
6322     *            root view place new focus
6323     */
6324    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6325        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6326            mPrivateFlags &= ~PFLAG_FOCUSED;
6327
6328            if (propagate && mParent != null) {
6329                mParent.clearChildFocus(this);
6330            }
6331
6332            onFocusChanged(false, 0, null);
6333            refreshDrawableState();
6334
6335            if (propagate && (!refocus || !rootViewRequestFocus())) {
6336                notifyGlobalFocusCleared(this);
6337            }
6338        }
6339    }
6340
6341    void notifyGlobalFocusCleared(View oldFocus) {
6342        if (oldFocus != null && mAttachInfo != null) {
6343            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6344        }
6345    }
6346
6347    boolean rootViewRequestFocus() {
6348        final View root = getRootView();
6349        return root != null && root.requestFocus();
6350    }
6351
6352    /**
6353     * Called internally by the view system when a new view is getting focus.
6354     * This is what clears the old focus.
6355     * <p>
6356     * <b>NOTE:</b> The parent view's focused child must be updated manually
6357     * after calling this method. Otherwise, the view hierarchy may be left in
6358     * an inconstent state.
6359     */
6360    void unFocus(View focused) {
6361        if (DBG) {
6362            System.out.println(this + " unFocus()");
6363        }
6364
6365        clearFocusInternal(focused, false, false);
6366    }
6367
6368    /**
6369     * Returns true if this view has focus itself, or is the ancestor of the
6370     * view that has focus.
6371     *
6372     * @return True if this view has or contains focus, false otherwise.
6373     */
6374    @ViewDebug.ExportedProperty(category = "focus")
6375    public boolean hasFocus() {
6376        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6377    }
6378
6379    /**
6380     * Returns true if this view is focusable or if it contains a reachable View
6381     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6382     * is a View whose parents do not block descendants focus.
6383     *
6384     * Only {@link #VISIBLE} views are considered focusable.
6385     *
6386     * @return True if the view is focusable or if the view contains a focusable
6387     *         View, false otherwise.
6388     *
6389     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6390     * @see ViewGroup#getTouchscreenBlocksFocus()
6391     */
6392    public boolean hasFocusable() {
6393        if (!isFocusableInTouchMode()) {
6394            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6395                final ViewGroup g = (ViewGroup) p;
6396                if (g.shouldBlockFocusForTouchscreen()) {
6397                    return false;
6398                }
6399            }
6400        }
6401        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6402    }
6403
6404    /**
6405     * Called by the view system when the focus state of this view changes.
6406     * When the focus change event is caused by directional navigation, direction
6407     * and previouslyFocusedRect provide insight into where the focus is coming from.
6408     * When overriding, be sure to call up through to the super class so that
6409     * the standard focus handling will occur.
6410     *
6411     * @param gainFocus True if the View has focus; false otherwise.
6412     * @param direction The direction focus has moved when requestFocus()
6413     *                  is called to give this view focus. Values are
6414     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6415     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6416     *                  It may not always apply, in which case use the default.
6417     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6418     *        system, of the previously focused view.  If applicable, this will be
6419     *        passed in as finer grained information about where the focus is coming
6420     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6421     */
6422    @CallSuper
6423    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6424            @Nullable Rect previouslyFocusedRect) {
6425        if (gainFocus) {
6426            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6427        } else {
6428            notifyViewAccessibilityStateChangedIfNeeded(
6429                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6430        }
6431
6432        InputMethodManager imm = InputMethodManager.peekInstance();
6433        if (!gainFocus) {
6434            if (isPressed()) {
6435                setPressed(false);
6436            }
6437            if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6438                imm.focusOut(this);
6439            }
6440            onFocusLost();
6441        } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6442            imm.focusIn(this);
6443        }
6444
6445        if (isAutoFillable()) {
6446            AutoFillManager afm = getAutoFillManager();
6447            if (afm != null) {
6448                afm.updateAutoFillInput(this, gainFocus
6449                        ? AutoFillManager.FLAG_UPDATE_UI_SHOW
6450                        : AutoFillManager.FLAG_UPDATE_UI_HIDE);
6451            }
6452        }
6453
6454        invalidate(true);
6455        ListenerInfo li = mListenerInfo;
6456        if (li != null && li.mOnFocusChangeListener != null) {
6457            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6458        }
6459
6460        if (mAttachInfo != null) {
6461            mAttachInfo.mKeyDispatchState.reset(this);
6462        }
6463    }
6464
6465    /**
6466     * Sends an accessibility event of the given type. If accessibility is
6467     * not enabled this method has no effect. The default implementation calls
6468     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6469     * to populate information about the event source (this View), then calls
6470     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6471     * populate the text content of the event source including its descendants,
6472     * and last calls
6473     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6474     * on its parent to request sending of the event to interested parties.
6475     * <p>
6476     * If an {@link AccessibilityDelegate} has been specified via calling
6477     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6478     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6479     * responsible for handling this call.
6480     * </p>
6481     *
6482     * @param eventType The type of the event to send, as defined by several types from
6483     * {@link android.view.accessibility.AccessibilityEvent}, such as
6484     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6485     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6486     *
6487     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6488     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6489     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6490     * @see AccessibilityDelegate
6491     */
6492    public void sendAccessibilityEvent(int eventType) {
6493        if (mAccessibilityDelegate != null) {
6494            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6495        } else {
6496            sendAccessibilityEventInternal(eventType);
6497        }
6498    }
6499
6500    /**
6501     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6502     * {@link AccessibilityEvent} to make an announcement which is related to some
6503     * sort of a context change for which none of the events representing UI transitions
6504     * is a good fit. For example, announcing a new page in a book. If accessibility
6505     * is not enabled this method does nothing.
6506     *
6507     * @param text The announcement text.
6508     */
6509    public void announceForAccessibility(CharSequence text) {
6510        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6511            AccessibilityEvent event = AccessibilityEvent.obtain(
6512                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6513            onInitializeAccessibilityEvent(event);
6514            event.getText().add(text);
6515            event.setContentDescription(null);
6516            mParent.requestSendAccessibilityEvent(this, event);
6517        }
6518    }
6519
6520    /**
6521     * @see #sendAccessibilityEvent(int)
6522     *
6523     * Note: Called from the default {@link AccessibilityDelegate}.
6524     *
6525     * @hide
6526     */
6527    public void sendAccessibilityEventInternal(int eventType) {
6528        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6529            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6530        }
6531    }
6532
6533    /**
6534     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6535     * takes as an argument an empty {@link AccessibilityEvent} and does not
6536     * perform a check whether accessibility is enabled.
6537     * <p>
6538     * If an {@link AccessibilityDelegate} has been specified via calling
6539     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6540     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6541     * is responsible for handling this call.
6542     * </p>
6543     *
6544     * @param event The event to send.
6545     *
6546     * @see #sendAccessibilityEvent(int)
6547     */
6548    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6549        if (mAccessibilityDelegate != null) {
6550            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6551        } else {
6552            sendAccessibilityEventUncheckedInternal(event);
6553        }
6554    }
6555
6556    /**
6557     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6558     *
6559     * Note: Called from the default {@link AccessibilityDelegate}.
6560     *
6561     * @hide
6562     */
6563    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6564        if (!isShown()) {
6565            return;
6566        }
6567        onInitializeAccessibilityEvent(event);
6568        // Only a subset of accessibility events populates text content.
6569        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6570            dispatchPopulateAccessibilityEvent(event);
6571        }
6572        // In the beginning we called #isShown(), so we know that getParent() is not null.
6573        getParent().requestSendAccessibilityEvent(this, event);
6574    }
6575
6576    /**
6577     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6578     * to its children for adding their text content to the event. Note that the
6579     * event text is populated in a separate dispatch path since we add to the
6580     * event not only the text of the source but also the text of all its descendants.
6581     * A typical implementation will call
6582     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6583     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6584     * on each child. Override this method if custom population of the event text
6585     * content is required.
6586     * <p>
6587     * If an {@link AccessibilityDelegate} has been specified via calling
6588     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6589     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6590     * is responsible for handling this call.
6591     * </p>
6592     * <p>
6593     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6594     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6595     * </p>
6596     *
6597     * @param event The event.
6598     *
6599     * @return True if the event population was completed.
6600     */
6601    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6602        if (mAccessibilityDelegate != null) {
6603            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6604        } else {
6605            return dispatchPopulateAccessibilityEventInternal(event);
6606        }
6607    }
6608
6609    /**
6610     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6611     *
6612     * Note: Called from the default {@link AccessibilityDelegate}.
6613     *
6614     * @hide
6615     */
6616    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6617        onPopulateAccessibilityEvent(event);
6618        return false;
6619    }
6620
6621    /**
6622     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6623     * giving a chance to this View to populate the accessibility event with its
6624     * text content. While this method is free to modify event
6625     * attributes other than text content, doing so should normally be performed in
6626     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6627     * <p>
6628     * Example: Adding formatted date string to an accessibility event in addition
6629     *          to the text added by the super implementation:
6630     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6631     *     super.onPopulateAccessibilityEvent(event);
6632     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6633     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6634     *         mCurrentDate.getTimeInMillis(), flags);
6635     *     event.getText().add(selectedDateUtterance);
6636     * }</pre>
6637     * <p>
6638     * If an {@link AccessibilityDelegate} has been specified via calling
6639     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6640     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6641     * is responsible for handling this call.
6642     * </p>
6643     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6644     * information to the event, in case the default implementation has basic information to add.
6645     * </p>
6646     *
6647     * @param event The accessibility event which to populate.
6648     *
6649     * @see #sendAccessibilityEvent(int)
6650     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6651     */
6652    @CallSuper
6653    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6654        if (mAccessibilityDelegate != null) {
6655            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6656        } else {
6657            onPopulateAccessibilityEventInternal(event);
6658        }
6659    }
6660
6661    /**
6662     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6663     *
6664     * Note: Called from the default {@link AccessibilityDelegate}.
6665     *
6666     * @hide
6667     */
6668    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6669    }
6670
6671    /**
6672     * Initializes an {@link AccessibilityEvent} with information about
6673     * this View which is the event source. In other words, the source of
6674     * an accessibility event is the view whose state change triggered firing
6675     * the event.
6676     * <p>
6677     * Example: Setting the password property of an event in addition
6678     *          to properties set by the super implementation:
6679     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6680     *     super.onInitializeAccessibilityEvent(event);
6681     *     event.setPassword(true);
6682     * }</pre>
6683     * <p>
6684     * If an {@link AccessibilityDelegate} has been specified via calling
6685     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6686     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6687     * is responsible for handling this call.
6688     * </p>
6689     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6690     * information to the event, in case the default implementation has basic information to add.
6691     * </p>
6692     * @param event The event to initialize.
6693     *
6694     * @see #sendAccessibilityEvent(int)
6695     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6696     */
6697    @CallSuper
6698    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6699        if (mAccessibilityDelegate != null) {
6700            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6701        } else {
6702            onInitializeAccessibilityEventInternal(event);
6703        }
6704    }
6705
6706    /**
6707     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6708     *
6709     * Note: Called from the default {@link AccessibilityDelegate}.
6710     *
6711     * @hide
6712     */
6713    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6714        event.setSource(this);
6715        event.setClassName(getAccessibilityClassName());
6716        event.setPackageName(getContext().getPackageName());
6717        event.setEnabled(isEnabled());
6718        event.setContentDescription(mContentDescription);
6719
6720        switch (event.getEventType()) {
6721            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6722                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6723                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6724                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6725                event.setItemCount(focusablesTempList.size());
6726                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6727                if (mAttachInfo != null) {
6728                    focusablesTempList.clear();
6729                }
6730            } break;
6731            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6732                CharSequence text = getIterableTextForAccessibility();
6733                if (text != null && text.length() > 0) {
6734                    event.setFromIndex(getAccessibilitySelectionStart());
6735                    event.setToIndex(getAccessibilitySelectionEnd());
6736                    event.setItemCount(text.length());
6737                }
6738            } break;
6739        }
6740    }
6741
6742    /**
6743     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6744     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6745     * This method is responsible for obtaining an accessibility node info from a
6746     * pool of reusable instances and calling
6747     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6748     * initialize the former.
6749     * <p>
6750     * Note: The client is responsible for recycling the obtained instance by calling
6751     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6752     * </p>
6753     *
6754     * @return A populated {@link AccessibilityNodeInfo}.
6755     *
6756     * @see AccessibilityNodeInfo
6757     */
6758    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6759        if (mAccessibilityDelegate != null) {
6760            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6761        } else {
6762            return createAccessibilityNodeInfoInternal();
6763        }
6764    }
6765
6766    /**
6767     * @see #createAccessibilityNodeInfo()
6768     *
6769     * @hide
6770     */
6771    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6772        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6773        if (provider != null) {
6774            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6775        } else {
6776            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6777            onInitializeAccessibilityNodeInfo(info);
6778            return info;
6779        }
6780    }
6781
6782    /**
6783     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6784     * The base implementation sets:
6785     * <ul>
6786     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6787     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6788     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6789     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6790     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6791     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6792     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6793     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6794     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6795     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6796     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6797     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6798     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6799     * </ul>
6800     * <p>
6801     * Subclasses should override this method, call the super implementation,
6802     * and set additional attributes.
6803     * </p>
6804     * <p>
6805     * If an {@link AccessibilityDelegate} has been specified via calling
6806     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6807     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6808     * is responsible for handling this call.
6809     * </p>
6810     *
6811     * @param info The instance to initialize.
6812     */
6813    @CallSuper
6814    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6815        if (mAccessibilityDelegate != null) {
6816            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6817        } else {
6818            onInitializeAccessibilityNodeInfoInternal(info);
6819        }
6820    }
6821
6822    /**
6823     * Gets the location of this view in screen coordinates.
6824     *
6825     * @param outRect The output location
6826     * @hide
6827     */
6828    public void getBoundsOnScreen(Rect outRect) {
6829        getBoundsOnScreen(outRect, false);
6830    }
6831
6832    /**
6833     * Gets the location of this view in screen coordinates.
6834     *
6835     * @param outRect The output location
6836     * @param clipToParent Whether to clip child bounds to the parent ones.
6837     * @hide
6838     */
6839    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6840        if (mAttachInfo == null) {
6841            return;
6842        }
6843
6844        RectF position = mAttachInfo.mTmpTransformRect;
6845        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6846
6847        if (!hasIdentityMatrix()) {
6848            getMatrix().mapRect(position);
6849        }
6850
6851        position.offset(mLeft, mTop);
6852
6853        ViewParent parent = mParent;
6854        while (parent instanceof View) {
6855            View parentView = (View) parent;
6856
6857            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6858
6859            if (clipToParent) {
6860                position.left = Math.max(position.left, 0);
6861                position.top = Math.max(position.top, 0);
6862                position.right = Math.min(position.right, parentView.getWidth());
6863                position.bottom = Math.min(position.bottom, parentView.getHeight());
6864            }
6865
6866            if (!parentView.hasIdentityMatrix()) {
6867                parentView.getMatrix().mapRect(position);
6868            }
6869
6870            position.offset(parentView.mLeft, parentView.mTop);
6871
6872            parent = parentView.mParent;
6873        }
6874
6875        if (parent instanceof ViewRootImpl) {
6876            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6877            position.offset(0, -viewRootImpl.mCurScrollY);
6878        }
6879
6880        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6881
6882        outRect.set(Math.round(position.left), Math.round(position.top),
6883                Math.round(position.right), Math.round(position.bottom));
6884    }
6885
6886    /**
6887     * Return the class name of this object to be used for accessibility purposes.
6888     * Subclasses should only override this if they are implementing something that
6889     * should be seen as a completely new class of view when used by accessibility,
6890     * unrelated to the class it is deriving from.  This is used to fill in
6891     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6892     */
6893    public CharSequence getAccessibilityClassName() {
6894        return View.class.getName();
6895    }
6896
6897    /**
6898     * Called when assist structure is being retrieved from a view as part of
6899     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6900     * @param structure Fill in with structured view data.  The default implementation
6901     * fills in all data that can be inferred from the view itself.
6902     */
6903    public void onProvideStructure(ViewStructure structure) {
6904        onProvideStructureForAssistOrAutoFill(structure, 0);
6905    }
6906
6907    /**
6908     * Called when assist structure is being retrieved from a view as part of an auto-fill request.
6909     *
6910     * <p>The structure must be filled according to the request type, which is set in the
6911     * {@code flags} parameter - see the documentation on each flag for more details.
6912     *
6913     * @param structure Fill in with structured view data.  The default implementation
6914     * fills in all data that can be inferred from the view itself.
6915     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
6916     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
6917     */
6918    public void onProvideAutoFillStructure(ViewStructure structure, int flags) {
6919        onProvideStructureForAssistOrAutoFill(structure, flags);
6920    }
6921
6922    private void onProvideStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
6923        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
6924        // this method should take a boolean with the type of request.
6925        boolean forAutoFill = (flags
6926                & (View.AUTO_FILL_FLAG_TYPE_FILL
6927                        | View.AUTO_FILL_FLAG_TYPE_SAVE)) != 0;
6928        final int id = mID;
6929        if (id != NO_ID && !isViewIdGenerated(id)) {
6930            String pkg, type, entry;
6931            try {
6932                final Resources res = getResources();
6933                entry = res.getResourceEntryName(id);
6934                type = res.getResourceTypeName(id);
6935                pkg = res.getResourcePackageName(id);
6936            } catch (Resources.NotFoundException e) {
6937                entry = type = pkg = null;
6938            }
6939            structure.setId(id, pkg, type, entry);
6940        } else {
6941            structure.setId(id, null, null, null);
6942        }
6943
6944        if (forAutoFill) {
6945            // The auto-fill id needs to be unique, but its value doesn't matter, so it's better to
6946            // reuse the accessibility id to save space.
6947            structure.setAutoFillId(getAccessibilityViewId());
6948            structure.setAutoFillType(getAutoFillType());
6949        }
6950
6951        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6952        if (!hasIdentityMatrix()) {
6953            structure.setTransformation(getMatrix());
6954        }
6955        structure.setElevation(getZ());
6956        structure.setVisibility(getVisibility());
6957        structure.setEnabled(isEnabled());
6958        if (isClickable()) {
6959            structure.setClickable(true);
6960        }
6961        if (isFocusable()) {
6962            structure.setFocusable(true);
6963        }
6964        if (isFocused()) {
6965            structure.setFocused(true);
6966        }
6967        if (isAccessibilityFocused()) {
6968            structure.setAccessibilityFocused(true);
6969        }
6970        if (isSelected()) {
6971            structure.setSelected(true);
6972        }
6973        if (isActivated()) {
6974            structure.setActivated(true);
6975        }
6976        if (isLongClickable()) {
6977            structure.setLongClickable(true);
6978        }
6979        if (this instanceof Checkable) {
6980            structure.setCheckable(true);
6981            if (((Checkable)this).isChecked()) {
6982                structure.setChecked(true);
6983            }
6984        }
6985        if (isContextClickable()) {
6986            structure.setContextClickable(true);
6987        }
6988        structure.setClassName(getAccessibilityClassName().toString());
6989        structure.setContentDescription(getContentDescription());
6990    }
6991
6992    /**
6993     * Called when assist structure is being retrieved from a view as part of
6994     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6995     * generate additional virtual structure under this view.  The defaullt implementation
6996     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6997     * view's virtual accessibility nodes, if any.  You can override this for a more
6998     * optimal implementation providing this data.
6999     */
7000    public void onProvideVirtualStructure(ViewStructure structure) {
7001        onProvideVirtualStructureForAssistOrAutoFill(structure, 0);
7002    }
7003
7004    /**
7005     * Called when assist structure is being retrieved from a view as part of an auto-fill request
7006     * to generate additional virtual structure under this view.
7007     *
7008     * <p>The defaullt implementation uses {@link #getAccessibilityNodeProvider()} to try to
7009     * generate this from the view's virtual accessibility nodes, if any. You can override this
7010     * for a more optimal implementation providing this data.
7011     *
7012     * <p>The structure must be filled according to the request type, which is set in the
7013     * {@code flags} parameter - see the documentation on each flag for more details.
7014     *
7015     * @param structure Fill in with structured view data.
7016     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7017     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
7018     */
7019    public void onProvideAutoFillVirtualStructure(ViewStructure structure, int flags) {
7020        onProvideVirtualStructureForAssistOrAutoFill(structure, flags);
7021    }
7022
7023    private void onProvideVirtualStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
7024        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7025        // this method should take a boolean with the type of request.
7026        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7027        if (provider != null) {
7028            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
7029            structure.setChildCount(1);
7030            ViewStructure root = structure.newChild(0);
7031            populateVirtualStructure(root, provider, info, flags);
7032            info.recycle();
7033        }
7034    }
7035
7036    /**
7037     * Gets the {@link VirtualViewDelegate} responsible for auto-filling the virtual children of
7038     * this view.
7039     *
7040     * <p>By default returns {@code null} but should be overridden when view provides a virtual
7041     * hierachy on {@link OnProvideAssistDataListener} that takes flags used by the AutoFill
7042     * Framework (such as {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7043     * {@link #AUTO_FILL_FLAG_TYPE_SAVE}).
7044     */
7045    @Nullable
7046    public VirtualViewDelegate getAutoFillVirtualViewDelegate(
7047            @SuppressWarnings("unused") VirtualViewDelegate.Callback callback) {
7048        return null;
7049    }
7050
7051    /**
7052     * Automatically fills the content of this view with the {@code value}.
7053     *
7054     * <p>By default does nothing, but views should override it (and {@link #getAutoFillType()} to
7055     * support the AutoFill Framework.
7056     *
7057     * <p>Typically, it is implemented by:
7058     *
7059     * <ol>
7060     * <li>Call the proper getter method on {@link AutoFillValue} to fetch the actual value.
7061     * <li>Pass the actual value to the equivalent setter in the view.
7062     * <ol>
7063     *
7064     * <p>For example, a text-field view would call:
7065     *
7066     * <pre class="prettyprint">
7067     * CharSequence text = value.getTextValue();
7068     * if (text != null) {
7069     *     setText(text);
7070     * }
7071     * </pre>
7072     */
7073    public void autoFill(@SuppressWarnings("unused") AutoFillValue value) {
7074    }
7075
7076    /**
7077     * Describes the auto-fill type that should be used on calls to
7078     * {@link #autoFill(AutoFillValue)} and
7079     * {@link VirtualViewDelegate#autoFill(int, AutoFillValue)}.
7080     *
7081     * <p>By default returns {@code null}, but views should override it (and
7082     * {@link #autoFill(AutoFillValue)} to support the AutoFill Framework.
7083     */
7084    @Nullable
7085    public AutoFillType getAutoFillType() {
7086        return null;
7087    }
7088
7089    @Nullable
7090    private AutoFillManager getAutoFillManager() {
7091        return mContext.getSystemService(AutoFillManager.class);
7092    }
7093
7094    private boolean isAutoFillable() {
7095        return getAutoFillType() != null && !isAutoFillBlocked();
7096    }
7097
7098    private void populateVirtualStructure(ViewStructure structure,
7099            AccessibilityNodeProvider provider, AccessibilityNodeInfo info, int flags) {
7100        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7101        // this method should take a boolean with the type of request.
7102
7103        final boolean sanitized = (flags & View.AUTO_FILL_FLAG_TYPE_FILL) != 0;
7104
7105        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
7106                null, null, null);
7107        Rect rect = structure.getTempRect();
7108        info.getBoundsInParent(rect);
7109        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
7110        structure.setVisibility(VISIBLE);
7111        structure.setEnabled(info.isEnabled());
7112        if (info.isClickable()) {
7113            structure.setClickable(true);
7114        }
7115        if (info.isFocusable()) {
7116            structure.setFocusable(true);
7117        }
7118        if (info.isFocused()) {
7119            structure.setFocused(true);
7120        }
7121        if (info.isAccessibilityFocused()) {
7122            structure.setAccessibilityFocused(true);
7123        }
7124        if (info.isSelected()) {
7125            structure.setSelected(true);
7126        }
7127        if (info.isLongClickable()) {
7128            structure.setLongClickable(true);
7129        }
7130        if (info.isCheckable()) {
7131            structure.setCheckable(true);
7132            if (info.isChecked()) {
7133                structure.setChecked(true);
7134            }
7135        }
7136        if (info.isContextClickable()) {
7137            structure.setContextClickable(true);
7138        }
7139        CharSequence cname = info.getClassName();
7140        structure.setClassName(cname != null ? cname.toString() : null);
7141        structure.setContentDescription(info.getContentDescription());
7142        if (!sanitized && (info.getText() != null || info.getError() != null)) {
7143            // TODO(b/33197203) (b/33269702): when sanitized, try to use the Accessibility API to
7144            // just set sanitized values (like text coming from resource files), rather than not
7145            // setting it at all.
7146            structure.setText(info.getText(), info.getTextSelectionStart(),
7147                    info.getTextSelectionEnd());
7148        }
7149        final int NCHILDREN = info.getChildCount();
7150        if (NCHILDREN > 0) {
7151            structure.setChildCount(NCHILDREN);
7152            for (int i=0; i<NCHILDREN; i++) {
7153                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
7154                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
7155                ViewStructure child = structure.newChild(i);
7156                populateVirtualStructure(child, provider, cinfo, flags);
7157                cinfo.recycle();
7158            }
7159        }
7160    }
7161
7162    /**
7163     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
7164     * implementation calls {@link #onProvideStructure} and
7165     * {@link #onProvideVirtualStructure}.
7166     */
7167    public void dispatchProvideStructure(ViewStructure structure) {
7168        dispatchProvideStructureForAssistOrAutoFill(structure, 0);
7169    }
7170
7171    /**
7172     * Dispatch creation of {@link ViewStructure} down the hierarchy.
7173     *
7174     * <p>The structure must be filled according to the request type, which is set in the
7175     * {@code flags} parameter - see the documentation on each flag for more details.
7176     *
7177     * <p>The default implementation calls {@link #onProvideAutoFillStructure(ViewStructure, int)}
7178     * and {@link #onProvideAutoFillVirtualStructure(ViewStructure, int)}.
7179     *
7180     * @param structure Fill in with structured view data.
7181     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7182     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
7183     */
7184    public void dispatchProvideAutoFillStructure(ViewStructure structure, int flags) {
7185        dispatchProvideStructureForAssistOrAutoFill(structure, flags);
7186    }
7187
7188    private void dispatchProvideStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
7189        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7190        // this method should take a boolean with the type of request.
7191        boolean forAutoFill = (flags
7192                & (View.AUTO_FILL_FLAG_TYPE_FILL
7193                        | View.AUTO_FILL_FLAG_TYPE_SAVE)) != 0;
7194
7195        boolean blocked = forAutoFill ? isAutoFillBlocked() : isAssistBlocked();
7196        if (!blocked) {
7197            if (forAutoFill) {
7198                onProvideAutoFillStructure(structure, flags);
7199                onProvideAutoFillVirtualStructure(structure, flags);
7200            } else {
7201                onProvideStructure(structure);
7202                onProvideVirtualStructure(structure);
7203            }
7204        } else {
7205            structure.setClassName(getAccessibilityClassName().toString());
7206            structure.setAssistBlocked(true);
7207        }
7208    }
7209
7210    /**
7211     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
7212     *
7213     * Note: Called from the default {@link AccessibilityDelegate}.
7214     *
7215     * @hide
7216     */
7217    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
7218        if (mAttachInfo == null) {
7219            return;
7220        }
7221
7222        Rect bounds = mAttachInfo.mTmpInvalRect;
7223
7224        getDrawingRect(bounds);
7225        info.setBoundsInParent(bounds);
7226
7227        getBoundsOnScreen(bounds, true);
7228        info.setBoundsInScreen(bounds);
7229
7230        ViewParent parent = getParentForAccessibility();
7231        if (parent instanceof View) {
7232            info.setParent((View) parent);
7233        }
7234
7235        if (mID != View.NO_ID) {
7236            View rootView = getRootView();
7237            if (rootView == null) {
7238                rootView = this;
7239            }
7240
7241            View label = rootView.findLabelForView(this, mID);
7242            if (label != null) {
7243                info.setLabeledBy(label);
7244            }
7245
7246            if ((mAttachInfo.mAccessibilityFetchFlags
7247                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
7248                    && Resources.resourceHasPackage(mID)) {
7249                try {
7250                    String viewId = getResources().getResourceName(mID);
7251                    info.setViewIdResourceName(viewId);
7252                } catch (Resources.NotFoundException nfe) {
7253                    /* ignore */
7254                }
7255            }
7256        }
7257
7258        if (mLabelForId != View.NO_ID) {
7259            View rootView = getRootView();
7260            if (rootView == null) {
7261                rootView = this;
7262            }
7263            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
7264            if (labeled != null) {
7265                info.setLabelFor(labeled);
7266            }
7267        }
7268
7269        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
7270            View rootView = getRootView();
7271            if (rootView == null) {
7272                rootView = this;
7273            }
7274            View next = rootView.findViewInsideOutShouldExist(this,
7275                    mAccessibilityTraversalBeforeId);
7276            if (next != null && next.includeForAccessibility()) {
7277                info.setTraversalBefore(next);
7278            }
7279        }
7280
7281        if (mAccessibilityTraversalAfterId != View.NO_ID) {
7282            View rootView = getRootView();
7283            if (rootView == null) {
7284                rootView = this;
7285            }
7286            View next = rootView.findViewInsideOutShouldExist(this,
7287                    mAccessibilityTraversalAfterId);
7288            if (next != null && next.includeForAccessibility()) {
7289                info.setTraversalAfter(next);
7290            }
7291        }
7292
7293        info.setVisibleToUser(isVisibleToUser());
7294
7295        info.setImportantForAccessibility(isImportantForAccessibility());
7296        info.setPackageName(mContext.getPackageName());
7297        info.setClassName(getAccessibilityClassName());
7298        info.setContentDescription(getContentDescription());
7299
7300        info.setEnabled(isEnabled());
7301        info.setClickable(isClickable());
7302        info.setFocusable(isFocusable());
7303        info.setFocused(isFocused());
7304        info.setAccessibilityFocused(isAccessibilityFocused());
7305        info.setSelected(isSelected());
7306        info.setLongClickable(isLongClickable());
7307        info.setContextClickable(isContextClickable());
7308        info.setLiveRegion(getAccessibilityLiveRegion());
7309
7310        // TODO: These make sense only if we are in an AdapterView but all
7311        // views can be selected. Maybe from accessibility perspective
7312        // we should report as selectable view in an AdapterView.
7313        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
7314        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
7315
7316        if (isFocusable()) {
7317            if (isFocused()) {
7318                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
7319            } else {
7320                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
7321            }
7322        }
7323
7324        if (!isAccessibilityFocused()) {
7325            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
7326        } else {
7327            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
7328        }
7329
7330        if (isClickable() && isEnabled()) {
7331            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
7332        }
7333
7334        if (isLongClickable() && isEnabled()) {
7335            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
7336        }
7337
7338        if (isContextClickable() && isEnabled()) {
7339            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
7340        }
7341
7342        CharSequence text = getIterableTextForAccessibility();
7343        if (text != null && text.length() > 0) {
7344            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
7345
7346            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
7347            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
7348            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
7349            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
7350                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
7351                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
7352        }
7353
7354        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
7355        populateAccessibilityNodeInfoDrawingOrderInParent(info);
7356    }
7357
7358    /**
7359     * Determine the order in which this view will be drawn relative to its siblings for a11y
7360     *
7361     * @param info The info whose drawing order should be populated
7362     */
7363    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
7364        /*
7365         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7366         * drawing order may not be well-defined, and some Views with custom drawing order may
7367         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7368         */
7369        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7370            info.setDrawingOrder(0);
7371            return;
7372        }
7373        int drawingOrderInParent = 1;
7374        // Iterate up the hierarchy if parents are not important for a11y
7375        View viewAtDrawingLevel = this;
7376        final ViewParent parent = getParentForAccessibility();
7377        while (viewAtDrawingLevel != parent) {
7378            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7379            if (!(currentParent instanceof ViewGroup)) {
7380                // Should only happen for the Decor
7381                drawingOrderInParent = 0;
7382                break;
7383            } else {
7384                final ViewGroup parentGroup = (ViewGroup) currentParent;
7385                final int childCount = parentGroup.getChildCount();
7386                if (childCount > 1) {
7387                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7388                    if (preorderedList != null) {
7389                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7390                        for (int i = 0; i < childDrawIndex; i++) {
7391                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7392                        }
7393                    } else {
7394                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7395                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7396                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7397                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7398                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
7399                        if (childDrawIndex != 0) {
7400                            for (int i = 0; i < numChildrenToIterate; i++) {
7401                                final int otherDrawIndex = (customOrder ?
7402                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
7403                                if (otherDrawIndex < childDrawIndex) {
7404                                    drawingOrderInParent +=
7405                                            numViewsForAccessibility(parentGroup.getChildAt(i));
7406                                }
7407                            }
7408                        }
7409                    }
7410                }
7411            }
7412            viewAtDrawingLevel = (View) currentParent;
7413        }
7414        info.setDrawingOrder(drawingOrderInParent);
7415    }
7416
7417    private static int numViewsForAccessibility(View view) {
7418        if (view != null) {
7419            if (view.includeForAccessibility()) {
7420                return 1;
7421            } else if (view instanceof ViewGroup) {
7422                return ((ViewGroup) view).getNumChildrenForAccessibility();
7423            }
7424        }
7425        return 0;
7426    }
7427
7428    private View findLabelForView(View view, int labeledId) {
7429        if (mMatchLabelForPredicate == null) {
7430            mMatchLabelForPredicate = new MatchLabelForPredicate();
7431        }
7432        mMatchLabelForPredicate.mLabeledId = labeledId;
7433        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7434    }
7435
7436    /**
7437     * Computes whether this view is visible to the user. Such a view is
7438     * attached, visible, all its predecessors are visible, it is not clipped
7439     * entirely by its predecessors, and has an alpha greater than zero.
7440     *
7441     * @return Whether the view is visible on the screen.
7442     *
7443     * @hide
7444     */
7445    protected boolean isVisibleToUser() {
7446        return isVisibleToUser(null);
7447    }
7448
7449    /**
7450     * Computes whether the given portion of this view is visible to the user.
7451     * Such a view is attached, visible, all its predecessors are visible,
7452     * has an alpha greater than zero, and the specified portion is not
7453     * clipped entirely by its predecessors.
7454     *
7455     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7456     *                    <code>null</code>, and the entire view will be tested in this case.
7457     *                    When <code>true</code> is returned by the function, the actual visible
7458     *                    region will be stored in this parameter; that is, if boundInView is fully
7459     *                    contained within the view, no modification will be made, otherwise regions
7460     *                    outside of the visible area of the view will be clipped.
7461     *
7462     * @return Whether the specified portion of the view is visible on the screen.
7463     *
7464     * @hide
7465     */
7466    protected boolean isVisibleToUser(Rect boundInView) {
7467        if (mAttachInfo != null) {
7468            // Attached to invisible window means this view is not visible.
7469            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7470                return false;
7471            }
7472            // An invisible predecessor or one with alpha zero means
7473            // that this view is not visible to the user.
7474            Object current = this;
7475            while (current instanceof View) {
7476                View view = (View) current;
7477                // We have attach info so this view is attached and there is no
7478                // need to check whether we reach to ViewRootImpl on the way up.
7479                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7480                        view.getVisibility() != VISIBLE) {
7481                    return false;
7482                }
7483                current = view.mParent;
7484            }
7485            // Check if the view is entirely covered by its predecessors.
7486            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7487            Point offset = mAttachInfo.mPoint;
7488            if (!getGlobalVisibleRect(visibleRect, offset)) {
7489                return false;
7490            }
7491            // Check if the visible portion intersects the rectangle of interest.
7492            if (boundInView != null) {
7493                visibleRect.offset(-offset.x, -offset.y);
7494                return boundInView.intersect(visibleRect);
7495            }
7496            return true;
7497        }
7498        return false;
7499    }
7500
7501    /**
7502     * Returns the delegate for implementing accessibility support via
7503     * composition. For more details see {@link AccessibilityDelegate}.
7504     *
7505     * @return The delegate, or null if none set.
7506     *
7507     * @hide
7508     */
7509    public AccessibilityDelegate getAccessibilityDelegate() {
7510        return mAccessibilityDelegate;
7511    }
7512
7513    /**
7514     * Sets a delegate for implementing accessibility support via composition
7515     * (as opposed to inheritance). For more details, see
7516     * {@link AccessibilityDelegate}.
7517     * <p>
7518     * <strong>Note:</strong> On platform versions prior to
7519     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7520     * views in the {@code android.widget.*} package are called <i>before</i>
7521     * host methods. This prevents certain properties such as class name from
7522     * being modified by overriding
7523     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7524     * as any changes will be overwritten by the host class.
7525     * <p>
7526     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7527     * methods are called <i>after</i> host methods, which all properties to be
7528     * modified without being overwritten by the host class.
7529     *
7530     * @param delegate the object to which accessibility method calls should be
7531     *                 delegated
7532     * @see AccessibilityDelegate
7533     */
7534    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7535        mAccessibilityDelegate = delegate;
7536    }
7537
7538    /**
7539     * Gets the provider for managing a virtual view hierarchy rooted at this View
7540     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7541     * that explore the window content.
7542     * <p>
7543     * If this method returns an instance, this instance is responsible for managing
7544     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7545     * View including the one representing the View itself. Similarly the returned
7546     * instance is responsible for performing accessibility actions on any virtual
7547     * view or the root view itself.
7548     * </p>
7549     * <p>
7550     * If an {@link AccessibilityDelegate} has been specified via calling
7551     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7552     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7553     * is responsible for handling this call.
7554     * </p>
7555     *
7556     * @return The provider.
7557     *
7558     * @see AccessibilityNodeProvider
7559     */
7560    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7561        if (mAccessibilityDelegate != null) {
7562            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7563        } else {
7564            return null;
7565        }
7566    }
7567
7568    /**
7569     * Gets the unique identifier of this view on the screen for accessibility purposes.
7570     *
7571     * @return The view accessibility id.
7572     *
7573     * @hide
7574     */
7575    public int getAccessibilityViewId() {
7576        if (mAccessibilityViewId == NO_ID) {
7577            mAccessibilityViewId = sNextAccessibilityViewId++;
7578        }
7579        return mAccessibilityViewId;
7580    }
7581
7582    /**
7583     * Gets the unique identifier of the window in which this View reseides.
7584     *
7585     * @return The window accessibility id.
7586     *
7587     * @hide
7588     */
7589    public int getAccessibilityWindowId() {
7590        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7591                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7592    }
7593
7594    /**
7595     * Returns the {@link View}'s content description.
7596     * <p>
7597     * <strong>Note:</strong> Do not override this method, as it will have no
7598     * effect on the content description presented to accessibility services.
7599     * You must call {@link #setContentDescription(CharSequence)} to modify the
7600     * content description.
7601     *
7602     * @return the content description
7603     * @see #setContentDescription(CharSequence)
7604     * @attr ref android.R.styleable#View_contentDescription
7605     */
7606    @ViewDebug.ExportedProperty(category = "accessibility")
7607    public CharSequence getContentDescription() {
7608        return mContentDescription;
7609    }
7610
7611    /**
7612     * Sets the {@link View}'s content description.
7613     * <p>
7614     * A content description briefly describes the view and is primarily used
7615     * for accessibility support to determine how a view should be presented to
7616     * the user. In the case of a view with no textual representation, such as
7617     * {@link android.widget.ImageButton}, a useful content description
7618     * explains what the view does. For example, an image button with a phone
7619     * icon that is used to place a call may use "Call" as its content
7620     * description. An image of a floppy disk that is used to save a file may
7621     * use "Save".
7622     *
7623     * @param contentDescription The content description.
7624     * @see #getContentDescription()
7625     * @attr ref android.R.styleable#View_contentDescription
7626     */
7627    @RemotableViewMethod
7628    public void setContentDescription(CharSequence contentDescription) {
7629        if (mContentDescription == null) {
7630            if (contentDescription == null) {
7631                return;
7632            }
7633        } else if (mContentDescription.equals(contentDescription)) {
7634            return;
7635        }
7636        mContentDescription = contentDescription;
7637        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7638        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7639            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7640            notifySubtreeAccessibilityStateChangedIfNeeded();
7641        } else {
7642            notifyViewAccessibilityStateChangedIfNeeded(
7643                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7644        }
7645    }
7646
7647    /**
7648     * Sets the id of a view before which this one is visited in accessibility traversal.
7649     * A screen-reader must visit the content of this view before the content of the one
7650     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7651     * will traverse the entire content of B before traversing the entire content of A,
7652     * regardles of what traversal strategy it is using.
7653     * <p>
7654     * Views that do not have specified before/after relationships are traversed in order
7655     * determined by the screen-reader.
7656     * </p>
7657     * <p>
7658     * Setting that this view is before a view that is not important for accessibility
7659     * or if this view is not important for accessibility will have no effect as the
7660     * screen-reader is not aware of unimportant views.
7661     * </p>
7662     *
7663     * @param beforeId The id of a view this one precedes in accessibility traversal.
7664     *
7665     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7666     *
7667     * @see #setImportantForAccessibility(int)
7668     */
7669    @RemotableViewMethod
7670    public void setAccessibilityTraversalBefore(int beforeId) {
7671        if (mAccessibilityTraversalBeforeId == beforeId) {
7672            return;
7673        }
7674        mAccessibilityTraversalBeforeId = beforeId;
7675        notifyViewAccessibilityStateChangedIfNeeded(
7676                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7677    }
7678
7679    /**
7680     * Gets the id of a view before which this one is visited in accessibility traversal.
7681     *
7682     * @return The id of a view this one precedes in accessibility traversal if
7683     *         specified, otherwise {@link #NO_ID}.
7684     *
7685     * @see #setAccessibilityTraversalBefore(int)
7686     */
7687    public int getAccessibilityTraversalBefore() {
7688        return mAccessibilityTraversalBeforeId;
7689    }
7690
7691    /**
7692     * Sets the id of a view after which this one is visited in accessibility traversal.
7693     * A screen-reader must visit the content of the other view before the content of this
7694     * one. For example, if view B is set to be after view A, then a screen-reader
7695     * will traverse the entire content of A before traversing the entire content of B,
7696     * regardles of what traversal strategy it is using.
7697     * <p>
7698     * Views that do not have specified before/after relationships are traversed in order
7699     * determined by the screen-reader.
7700     * </p>
7701     * <p>
7702     * Setting that this view is after a view that is not important for accessibility
7703     * or if this view is not important for accessibility will have no effect as the
7704     * screen-reader is not aware of unimportant views.
7705     * </p>
7706     *
7707     * @param afterId The id of a view this one succedees in accessibility traversal.
7708     *
7709     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7710     *
7711     * @see #setImportantForAccessibility(int)
7712     */
7713    @RemotableViewMethod
7714    public void setAccessibilityTraversalAfter(int afterId) {
7715        if (mAccessibilityTraversalAfterId == afterId) {
7716            return;
7717        }
7718        mAccessibilityTraversalAfterId = afterId;
7719        notifyViewAccessibilityStateChangedIfNeeded(
7720                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7721    }
7722
7723    /**
7724     * Gets the id of a view after which this one is visited in accessibility traversal.
7725     *
7726     * @return The id of a view this one succeedes in accessibility traversal if
7727     *         specified, otherwise {@link #NO_ID}.
7728     *
7729     * @see #setAccessibilityTraversalAfter(int)
7730     */
7731    public int getAccessibilityTraversalAfter() {
7732        return mAccessibilityTraversalAfterId;
7733    }
7734
7735    /**
7736     * Gets the id of a view for which this view serves as a label for
7737     * accessibility purposes.
7738     *
7739     * @return The labeled view id.
7740     */
7741    @ViewDebug.ExportedProperty(category = "accessibility")
7742    public int getLabelFor() {
7743        return mLabelForId;
7744    }
7745
7746    /**
7747     * Sets the id of a view for which this view serves as a label for
7748     * accessibility purposes.
7749     *
7750     * @param id The labeled view id.
7751     */
7752    @RemotableViewMethod
7753    public void setLabelFor(@IdRes int id) {
7754        if (mLabelForId == id) {
7755            return;
7756        }
7757        mLabelForId = id;
7758        if (mLabelForId != View.NO_ID
7759                && mID == View.NO_ID) {
7760            mID = generateViewId();
7761        }
7762        notifyViewAccessibilityStateChangedIfNeeded(
7763                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7764    }
7765
7766    /**
7767     * Invoked whenever this view loses focus, either by losing window focus or by losing
7768     * focus within its window. This method can be used to clear any state tied to the
7769     * focus. For instance, if a button is held pressed with the trackball and the window
7770     * loses focus, this method can be used to cancel the press.
7771     *
7772     * Subclasses of View overriding this method should always call super.onFocusLost().
7773     *
7774     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7775     * @see #onWindowFocusChanged(boolean)
7776     *
7777     * @hide pending API council approval
7778     */
7779    @CallSuper
7780    protected void onFocusLost() {
7781        resetPressedState();
7782    }
7783
7784    private void resetPressedState() {
7785        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7786            return;
7787        }
7788
7789        if (isPressed()) {
7790            setPressed(false);
7791
7792            if (!mHasPerformedLongPress) {
7793                removeLongPressCallback();
7794            }
7795        }
7796    }
7797
7798    /**
7799     * Returns true if this view has focus
7800     *
7801     * @return True if this view has focus, false otherwise.
7802     */
7803    @ViewDebug.ExportedProperty(category = "focus")
7804    public boolean isFocused() {
7805        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7806    }
7807
7808    /**
7809     * Find the view in the hierarchy rooted at this view that currently has
7810     * focus.
7811     *
7812     * @return The view that currently has focus, or null if no focused view can
7813     *         be found.
7814     */
7815    public View findFocus() {
7816        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7817    }
7818
7819    /**
7820     * Indicates whether this view is one of the set of scrollable containers in
7821     * its window.
7822     *
7823     * @return whether this view is one of the set of scrollable containers in
7824     * its window
7825     *
7826     * @attr ref android.R.styleable#View_isScrollContainer
7827     */
7828    public boolean isScrollContainer() {
7829        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7830    }
7831
7832    /**
7833     * Change whether this view is one of the set of scrollable containers in
7834     * its window.  This will be used to determine whether the window can
7835     * resize or must pan when a soft input area is open -- scrollable
7836     * containers allow the window to use resize mode since the container
7837     * will appropriately shrink.
7838     *
7839     * @attr ref android.R.styleable#View_isScrollContainer
7840     */
7841    public void setScrollContainer(boolean isScrollContainer) {
7842        if (isScrollContainer) {
7843            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7844                mAttachInfo.mScrollContainers.add(this);
7845                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7846            }
7847            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7848        } else {
7849            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7850                mAttachInfo.mScrollContainers.remove(this);
7851            }
7852            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7853        }
7854    }
7855
7856    /**
7857     * Returns the quality of the drawing cache.
7858     *
7859     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7860     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7861     *
7862     * @see #setDrawingCacheQuality(int)
7863     * @see #setDrawingCacheEnabled(boolean)
7864     * @see #isDrawingCacheEnabled()
7865     *
7866     * @attr ref android.R.styleable#View_drawingCacheQuality
7867     */
7868    @DrawingCacheQuality
7869    public int getDrawingCacheQuality() {
7870        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7871    }
7872
7873    /**
7874     * Set the drawing cache quality of this view. This value is used only when the
7875     * drawing cache is enabled
7876     *
7877     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7878     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7879     *
7880     * @see #getDrawingCacheQuality()
7881     * @see #setDrawingCacheEnabled(boolean)
7882     * @see #isDrawingCacheEnabled()
7883     *
7884     * @attr ref android.R.styleable#View_drawingCacheQuality
7885     */
7886    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7887        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7888    }
7889
7890    /**
7891     * Returns whether the screen should remain on, corresponding to the current
7892     * value of {@link #KEEP_SCREEN_ON}.
7893     *
7894     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7895     *
7896     * @see #setKeepScreenOn(boolean)
7897     *
7898     * @attr ref android.R.styleable#View_keepScreenOn
7899     */
7900    public boolean getKeepScreenOn() {
7901        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7902    }
7903
7904    /**
7905     * Controls whether the screen should remain on, modifying the
7906     * value of {@link #KEEP_SCREEN_ON}.
7907     *
7908     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7909     *
7910     * @see #getKeepScreenOn()
7911     *
7912     * @attr ref android.R.styleable#View_keepScreenOn
7913     */
7914    public void setKeepScreenOn(boolean keepScreenOn) {
7915        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7916    }
7917
7918    /**
7919     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7920     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7921     *
7922     * @attr ref android.R.styleable#View_nextFocusLeft
7923     */
7924    public int getNextFocusLeftId() {
7925        return mNextFocusLeftId;
7926    }
7927
7928    /**
7929     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7930     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7931     * decide automatically.
7932     *
7933     * @attr ref android.R.styleable#View_nextFocusLeft
7934     */
7935    public void setNextFocusLeftId(int nextFocusLeftId) {
7936        mNextFocusLeftId = nextFocusLeftId;
7937    }
7938
7939    /**
7940     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7941     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7942     *
7943     * @attr ref android.R.styleable#View_nextFocusRight
7944     */
7945    public int getNextFocusRightId() {
7946        return mNextFocusRightId;
7947    }
7948
7949    /**
7950     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7951     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7952     * decide automatically.
7953     *
7954     * @attr ref android.R.styleable#View_nextFocusRight
7955     */
7956    public void setNextFocusRightId(int nextFocusRightId) {
7957        mNextFocusRightId = nextFocusRightId;
7958    }
7959
7960    /**
7961     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7962     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7963     *
7964     * @attr ref android.R.styleable#View_nextFocusUp
7965     */
7966    public int getNextFocusUpId() {
7967        return mNextFocusUpId;
7968    }
7969
7970    /**
7971     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7972     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7973     * decide automatically.
7974     *
7975     * @attr ref android.R.styleable#View_nextFocusUp
7976     */
7977    public void setNextFocusUpId(int nextFocusUpId) {
7978        mNextFocusUpId = nextFocusUpId;
7979    }
7980
7981    /**
7982     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7983     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7984     *
7985     * @attr ref android.R.styleable#View_nextFocusDown
7986     */
7987    public int getNextFocusDownId() {
7988        return mNextFocusDownId;
7989    }
7990
7991    /**
7992     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7993     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7994     * decide automatically.
7995     *
7996     * @attr ref android.R.styleable#View_nextFocusDown
7997     */
7998    public void setNextFocusDownId(int nextFocusDownId) {
7999        mNextFocusDownId = nextFocusDownId;
8000    }
8001
8002    /**
8003     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8004     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8005     *
8006     * @attr ref android.R.styleable#View_nextFocusForward
8007     */
8008    public int getNextFocusForwardId() {
8009        return mNextFocusForwardId;
8010    }
8011
8012    /**
8013     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8014     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
8015     * decide automatically.
8016     *
8017     * @attr ref android.R.styleable#View_nextFocusForward
8018     */
8019    public void setNextFocusForwardId(int nextFocusForwardId) {
8020        mNextFocusForwardId = nextFocusForwardId;
8021    }
8022
8023    /**
8024     * Gets the id of the root of the next keyboard navigation cluster.
8025     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
8026     * decide automatically.
8027     *
8028     * @attr ref android.R.styleable#View_nextClusterForward
8029     */
8030    public int getNextClusterForwardId() {
8031        return mNextClusterForwardId;
8032    }
8033
8034    /**
8035     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
8036     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
8037     * decide automatically.
8038     *
8039     * @attr ref android.R.styleable#View_nextClusterForward
8040     */
8041    public void setNextClusterForwardId(int nextClusterForwardId) {
8042        mNextClusterForwardId = nextClusterForwardId;
8043    }
8044
8045    /**
8046     * Returns the visibility of this view and all of its ancestors
8047     *
8048     * @return True if this view and all of its ancestors are {@link #VISIBLE}
8049     */
8050    public boolean isShown() {
8051        View current = this;
8052        //noinspection ConstantConditions
8053        do {
8054            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8055                return false;
8056            }
8057            ViewParent parent = current.mParent;
8058            if (parent == null) {
8059                return false; // We are not attached to the view root
8060            }
8061            if (!(parent instanceof View)) {
8062                return true;
8063            }
8064            current = (View) parent;
8065        } while (current != null);
8066
8067        return false;
8068    }
8069
8070    /**
8071     * Called by the view hierarchy when the content insets for a window have
8072     * changed, to allow it to adjust its content to fit within those windows.
8073     * The content insets tell you the space that the status bar, input method,
8074     * and other system windows infringe on the application's window.
8075     *
8076     * <p>You do not normally need to deal with this function, since the default
8077     * window decoration given to applications takes care of applying it to the
8078     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
8079     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
8080     * and your content can be placed under those system elements.  You can then
8081     * use this method within your view hierarchy if you have parts of your UI
8082     * which you would like to ensure are not being covered.
8083     *
8084     * <p>The default implementation of this method simply applies the content
8085     * insets to the view's padding, consuming that content (modifying the
8086     * insets to be 0), and returning true.  This behavior is off by default, but can
8087     * be enabled through {@link #setFitsSystemWindows(boolean)}.
8088     *
8089     * <p>This function's traversal down the hierarchy is depth-first.  The same content
8090     * insets object is propagated down the hierarchy, so any changes made to it will
8091     * be seen by all following views (including potentially ones above in
8092     * the hierarchy since this is a depth-first traversal).  The first view
8093     * that returns true will abort the entire traversal.
8094     *
8095     * <p>The default implementation works well for a situation where it is
8096     * used with a container that covers the entire window, allowing it to
8097     * apply the appropriate insets to its content on all edges.  If you need
8098     * a more complicated layout (such as two different views fitting system
8099     * windows, one on the top of the window, and one on the bottom),
8100     * you can override the method and handle the insets however you would like.
8101     * Note that the insets provided by the framework are always relative to the
8102     * far edges of the window, not accounting for the location of the called view
8103     * within that window.  (In fact when this method is called you do not yet know
8104     * where the layout will place the view, as it is done before layout happens.)
8105     *
8106     * <p>Note: unlike many View methods, there is no dispatch phase to this
8107     * call.  If you are overriding it in a ViewGroup and want to allow the
8108     * call to continue to your children, you must be sure to call the super
8109     * implementation.
8110     *
8111     * <p>Here is a sample layout that makes use of fitting system windows
8112     * to have controls for a video view placed inside of the window decorations
8113     * that it hides and shows.  This can be used with code like the second
8114     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
8115     *
8116     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
8117     *
8118     * @param insets Current content insets of the window.  Prior to
8119     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
8120     * the insets or else you and Android will be unhappy.
8121     *
8122     * @return {@code true} if this view applied the insets and it should not
8123     * continue propagating further down the hierarchy, {@code false} otherwise.
8124     * @see #getFitsSystemWindows()
8125     * @see #setFitsSystemWindows(boolean)
8126     * @see #setSystemUiVisibility(int)
8127     *
8128     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
8129     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
8130     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
8131     * to implement handling their own insets.
8132     */
8133    @Deprecated
8134    protected boolean fitSystemWindows(Rect insets) {
8135        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
8136            if (insets == null) {
8137                // Null insets by definition have already been consumed.
8138                // This call cannot apply insets since there are none to apply,
8139                // so return false.
8140                return false;
8141            }
8142            // If we're not in the process of dispatching the newer apply insets call,
8143            // that means we're not in the compatibility path. Dispatch into the newer
8144            // apply insets path and take things from there.
8145            try {
8146                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
8147                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
8148            } finally {
8149                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
8150            }
8151        } else {
8152            // We're being called from the newer apply insets path.
8153            // Perform the standard fallback behavior.
8154            return fitSystemWindowsInt(insets);
8155        }
8156    }
8157
8158    private boolean fitSystemWindowsInt(Rect insets) {
8159        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
8160            mUserPaddingStart = UNDEFINED_PADDING;
8161            mUserPaddingEnd = UNDEFINED_PADDING;
8162            Rect localInsets = sThreadLocal.get();
8163            if (localInsets == null) {
8164                localInsets = new Rect();
8165                sThreadLocal.set(localInsets);
8166            }
8167            boolean res = computeFitSystemWindows(insets, localInsets);
8168            mUserPaddingLeftInitial = localInsets.left;
8169            mUserPaddingRightInitial = localInsets.right;
8170            internalSetPadding(localInsets.left, localInsets.top,
8171                    localInsets.right, localInsets.bottom);
8172            return res;
8173        }
8174        return false;
8175    }
8176
8177    /**
8178     * Called when the view should apply {@link WindowInsets} according to its internal policy.
8179     *
8180     * <p>This method should be overridden by views that wish to apply a policy different from or
8181     * in addition to the default behavior. Clients that wish to force a view subtree
8182     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
8183     *
8184     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
8185     * it will be called during dispatch instead of this method. The listener may optionally
8186     * call this method from its own implementation if it wishes to apply the view's default
8187     * insets policy in addition to its own.</p>
8188     *
8189     * <p>Implementations of this method should either return the insets parameter unchanged
8190     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
8191     * that this view applied itself. This allows new inset types added in future platform
8192     * versions to pass through existing implementations unchanged without being erroneously
8193     * consumed.</p>
8194     *
8195     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
8196     * property is set then the view will consume the system window insets and apply them
8197     * as padding for the view.</p>
8198     *
8199     * @param insets Insets to apply
8200     * @return The supplied insets with any applied insets consumed
8201     */
8202    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
8203        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
8204            // We weren't called from within a direct call to fitSystemWindows,
8205            // call into it as a fallback in case we're in a class that overrides it
8206            // and has logic to perform.
8207            if (fitSystemWindows(insets.getSystemWindowInsets())) {
8208                return insets.consumeSystemWindowInsets();
8209            }
8210        } else {
8211            // We were called from within a direct call to fitSystemWindows.
8212            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
8213                return insets.consumeSystemWindowInsets();
8214            }
8215        }
8216        return insets;
8217    }
8218
8219    /**
8220     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
8221     * window insets to this view. The listener's
8222     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
8223     * method will be called instead of the view's
8224     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
8225     *
8226     * @param listener Listener to set
8227     *
8228     * @see #onApplyWindowInsets(WindowInsets)
8229     */
8230    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
8231        getListenerInfo().mOnApplyWindowInsetsListener = listener;
8232    }
8233
8234    /**
8235     * Request to apply the given window insets to this view or another view in its subtree.
8236     *
8237     * <p>This method should be called by clients wishing to apply insets corresponding to areas
8238     * obscured by window decorations or overlays. This can include the status and navigation bars,
8239     * action bars, input methods and more. New inset categories may be added in the future.
8240     * The method returns the insets provided minus any that were applied by this view or its
8241     * children.</p>
8242     *
8243     * <p>Clients wishing to provide custom behavior should override the
8244     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
8245     * {@link OnApplyWindowInsetsListener} via the
8246     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
8247     * method.</p>
8248     *
8249     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
8250     * </p>
8251     *
8252     * @param insets Insets to apply
8253     * @return The provided insets minus the insets that were consumed
8254     */
8255    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
8256        try {
8257            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
8258            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
8259                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
8260            } else {
8261                return onApplyWindowInsets(insets);
8262            }
8263        } finally {
8264            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
8265        }
8266    }
8267
8268    /**
8269     * Compute the view's coordinate within the surface.
8270     *
8271     * <p>Computes the coordinates of this view in its surface. The argument
8272     * must be an array of two integers. After the method returns, the array
8273     * contains the x and y location in that order.</p>
8274     * @hide
8275     * @param location an array of two integers in which to hold the coordinates
8276     */
8277    public void getLocationInSurface(@Size(2) int[] location) {
8278        getLocationInWindow(location);
8279        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
8280            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
8281            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
8282        }
8283    }
8284
8285    /**
8286     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
8287     * only available if the view is attached.
8288     *
8289     * @return WindowInsets from the top of the view hierarchy or null if View is detached
8290     */
8291    public WindowInsets getRootWindowInsets() {
8292        if (mAttachInfo != null) {
8293            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
8294        }
8295        return null;
8296    }
8297
8298    /**
8299     * @hide Compute the insets that should be consumed by this view and the ones
8300     * that should propagate to those under it.
8301     */
8302    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
8303        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8304                || mAttachInfo == null
8305                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
8306                        && !mAttachInfo.mOverscanRequested)) {
8307            outLocalInsets.set(inoutInsets);
8308            inoutInsets.set(0, 0, 0, 0);
8309            return true;
8310        } else {
8311            // The application wants to take care of fitting system window for
8312            // the content...  however we still need to take care of any overscan here.
8313            final Rect overscan = mAttachInfo.mOverscanInsets;
8314            outLocalInsets.set(overscan);
8315            inoutInsets.left -= overscan.left;
8316            inoutInsets.top -= overscan.top;
8317            inoutInsets.right -= overscan.right;
8318            inoutInsets.bottom -= overscan.bottom;
8319            return false;
8320        }
8321    }
8322
8323    /**
8324     * Compute insets that should be consumed by this view and the ones that should propagate
8325     * to those under it.
8326     *
8327     * @param in Insets currently being processed by this View, likely received as a parameter
8328     *           to {@link #onApplyWindowInsets(WindowInsets)}.
8329     * @param outLocalInsets A Rect that will receive the insets that should be consumed
8330     *                       by this view
8331     * @return Insets that should be passed along to views under this one
8332     */
8333    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
8334        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8335                || mAttachInfo == null
8336                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
8337            outLocalInsets.set(in.getSystemWindowInsets());
8338            return in.consumeSystemWindowInsets();
8339        } else {
8340            outLocalInsets.set(0, 0, 0, 0);
8341            return in;
8342        }
8343    }
8344
8345    /**
8346     * Sets whether or not this view should account for system screen decorations
8347     * such as the status bar and inset its content; that is, controlling whether
8348     * the default implementation of {@link #fitSystemWindows(Rect)} will be
8349     * executed.  See that method for more details.
8350     *
8351     * <p>Note that if you are providing your own implementation of
8352     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
8353     * flag to true -- your implementation will be overriding the default
8354     * implementation that checks this flag.
8355     *
8356     * @param fitSystemWindows If true, then the default implementation of
8357     * {@link #fitSystemWindows(Rect)} will be executed.
8358     *
8359     * @attr ref android.R.styleable#View_fitsSystemWindows
8360     * @see #getFitsSystemWindows()
8361     * @see #fitSystemWindows(Rect)
8362     * @see #setSystemUiVisibility(int)
8363     */
8364    public void setFitsSystemWindows(boolean fitSystemWindows) {
8365        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
8366    }
8367
8368    /**
8369     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
8370     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
8371     * will be executed.
8372     *
8373     * @return {@code true} if the default implementation of
8374     * {@link #fitSystemWindows(Rect)} will be executed.
8375     *
8376     * @attr ref android.R.styleable#View_fitsSystemWindows
8377     * @see #setFitsSystemWindows(boolean)
8378     * @see #fitSystemWindows(Rect)
8379     * @see #setSystemUiVisibility(int)
8380     */
8381    @ViewDebug.ExportedProperty
8382    public boolean getFitsSystemWindows() {
8383        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
8384    }
8385
8386    /** @hide */
8387    public boolean fitsSystemWindows() {
8388        return getFitsSystemWindows();
8389    }
8390
8391    /**
8392     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8393     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8394     */
8395    @Deprecated
8396    public void requestFitSystemWindows() {
8397        if (mParent != null) {
8398            mParent.requestFitSystemWindows();
8399        }
8400    }
8401
8402    /**
8403     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
8404     */
8405    public void requestApplyInsets() {
8406        requestFitSystemWindows();
8407    }
8408
8409    /**
8410     * For use by PhoneWindow to make its own system window fitting optional.
8411     * @hide
8412     */
8413    public void makeOptionalFitsSystemWindows() {
8414        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
8415    }
8416
8417    /**
8418     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
8419     * treat them as such.
8420     * @hide
8421     */
8422    public void getOutsets(Rect outOutsetRect) {
8423        if (mAttachInfo != null) {
8424            outOutsetRect.set(mAttachInfo.mOutsets);
8425        } else {
8426            outOutsetRect.setEmpty();
8427        }
8428    }
8429
8430    /**
8431     * Returns the visibility status for this view.
8432     *
8433     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8434     * @attr ref android.R.styleable#View_visibility
8435     */
8436    @ViewDebug.ExportedProperty(mapping = {
8437        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
8438        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
8439        @ViewDebug.IntToString(from = GONE,      to = "GONE")
8440    })
8441    @Visibility
8442    public int getVisibility() {
8443        return mViewFlags & VISIBILITY_MASK;
8444    }
8445
8446    /**
8447     * Set the visibility state of this view.
8448     *
8449     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8450     * @attr ref android.R.styleable#View_visibility
8451     */
8452    @RemotableViewMethod
8453    public void setVisibility(@Visibility int visibility) {
8454        setFlags(visibility, VISIBILITY_MASK);
8455    }
8456
8457    /**
8458     * Returns the enabled status for this view. The interpretation of the
8459     * enabled state varies by subclass.
8460     *
8461     * @return True if this view is enabled, false otherwise.
8462     */
8463    @ViewDebug.ExportedProperty
8464    public boolean isEnabled() {
8465        return (mViewFlags & ENABLED_MASK) == ENABLED;
8466    }
8467
8468    /**
8469     * Set the enabled state of this view. The interpretation of the enabled
8470     * state varies by subclass.
8471     *
8472     * @param enabled True if this view is enabled, false otherwise.
8473     */
8474    @RemotableViewMethod
8475    public void setEnabled(boolean enabled) {
8476        if (enabled == isEnabled()) return;
8477
8478        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8479
8480        /*
8481         * The View most likely has to change its appearance, so refresh
8482         * the drawable state.
8483         */
8484        refreshDrawableState();
8485
8486        // Invalidate too, since the default behavior for views is to be
8487        // be drawn at 50% alpha rather than to change the drawable.
8488        invalidate(true);
8489
8490        if (!enabled) {
8491            cancelPendingInputEvents();
8492        }
8493    }
8494
8495    /**
8496     * Set whether this view can receive the focus.
8497     * <p>
8498     * Setting this to false will also ensure that this view is not focusable
8499     * in touch mode.
8500     *
8501     * @param focusable If true, this view can receive the focus.
8502     *
8503     * @see #setFocusableInTouchMode(boolean)
8504     * @see #setFocusable(int)
8505     * @attr ref android.R.styleable#View_focusable
8506     */
8507    public void setFocusable(boolean focusable) {
8508        setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
8509    }
8510
8511    /**
8512     * Sets whether this view can receive focus.
8513     * <p>
8514     * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
8515     * automatically based on the view's interactivity. This is the default.
8516     * <p>
8517     * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
8518     * in touch mode.
8519     *
8520     * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
8521     *                  or {@link #FOCUSABLE_AUTO}.
8522     * @see #setFocusableInTouchMode(boolean)
8523     * @attr ref android.R.styleable#View_focusable
8524     */
8525    public void setFocusable(@Focusable int focusable) {
8526        if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
8527            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8528        }
8529        setFlags(focusable, FOCUSABLE_MASK);
8530    }
8531
8532    /**
8533     * Set whether this view can receive focus while in touch mode.
8534     *
8535     * Setting this to true will also ensure that this view is focusable.
8536     *
8537     * @param focusableInTouchMode If true, this view can receive the focus while
8538     *   in touch mode.
8539     *
8540     * @see #setFocusable(boolean)
8541     * @attr ref android.R.styleable#View_focusableInTouchMode
8542     */
8543    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8544        // Focusable in touch mode should always be set before the focusable flag
8545        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8546        // which, in touch mode, will not successfully request focus on this view
8547        // because the focusable in touch mode flag is not set
8548        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8549        if (focusableInTouchMode) {
8550            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8551        }
8552    }
8553
8554    /**
8555     * Set whether this view should have sound effects enabled for events such as
8556     * clicking and touching.
8557     *
8558     * <p>You may wish to disable sound effects for a view if you already play sounds,
8559     * for instance, a dial key that plays dtmf tones.
8560     *
8561     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8562     * @see #isSoundEffectsEnabled()
8563     * @see #playSoundEffect(int)
8564     * @attr ref android.R.styleable#View_soundEffectsEnabled
8565     */
8566    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8567        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8568    }
8569
8570    /**
8571     * @return whether this view should have sound effects enabled for events such as
8572     *     clicking and touching.
8573     *
8574     * @see #setSoundEffectsEnabled(boolean)
8575     * @see #playSoundEffect(int)
8576     * @attr ref android.R.styleable#View_soundEffectsEnabled
8577     */
8578    @ViewDebug.ExportedProperty
8579    public boolean isSoundEffectsEnabled() {
8580        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8581    }
8582
8583    /**
8584     * Set whether this view should have haptic feedback for events such as
8585     * long presses.
8586     *
8587     * <p>You may wish to disable haptic feedback if your view already controls
8588     * its own haptic feedback.
8589     *
8590     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8591     * @see #isHapticFeedbackEnabled()
8592     * @see #performHapticFeedback(int)
8593     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8594     */
8595    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8596        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8597    }
8598
8599    /**
8600     * @return whether this view should have haptic feedback enabled for events
8601     * long presses.
8602     *
8603     * @see #setHapticFeedbackEnabled(boolean)
8604     * @see #performHapticFeedback(int)
8605     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8606     */
8607    @ViewDebug.ExportedProperty
8608    public boolean isHapticFeedbackEnabled() {
8609        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8610    }
8611
8612    /**
8613     * Returns the layout direction for this view.
8614     *
8615     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8616     *   {@link #LAYOUT_DIRECTION_RTL},
8617     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8618     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8619     *
8620     * @attr ref android.R.styleable#View_layoutDirection
8621     *
8622     * @hide
8623     */
8624    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8625        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8626        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8627        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8628        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8629    })
8630    @LayoutDir
8631    public int getRawLayoutDirection() {
8632        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8633    }
8634
8635    /**
8636     * Set the layout direction for this view. This will propagate a reset of layout direction
8637     * resolution to the view's children and resolve layout direction for this view.
8638     *
8639     * @param layoutDirection the layout direction to set. Should be one of:
8640     *
8641     * {@link #LAYOUT_DIRECTION_LTR},
8642     * {@link #LAYOUT_DIRECTION_RTL},
8643     * {@link #LAYOUT_DIRECTION_INHERIT},
8644     * {@link #LAYOUT_DIRECTION_LOCALE}.
8645     *
8646     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8647     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8648     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8649     *
8650     * @attr ref android.R.styleable#View_layoutDirection
8651     */
8652    @RemotableViewMethod
8653    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8654        if (getRawLayoutDirection() != layoutDirection) {
8655            // Reset the current layout direction and the resolved one
8656            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8657            resetRtlProperties();
8658            // Set the new layout direction (filtered)
8659            mPrivateFlags2 |=
8660                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8661            // We need to resolve all RTL properties as they all depend on layout direction
8662            resolveRtlPropertiesIfNeeded();
8663            requestLayout();
8664            invalidate(true);
8665        }
8666    }
8667
8668    /**
8669     * Returns the resolved layout direction for this view.
8670     *
8671     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8672     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8673     *
8674     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8675     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8676     *
8677     * @attr ref android.R.styleable#View_layoutDirection
8678     */
8679    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8680        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8681        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8682    })
8683    @ResolvedLayoutDir
8684    public int getLayoutDirection() {
8685        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8686        if (targetSdkVersion < JELLY_BEAN_MR1) {
8687            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8688            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8689        }
8690        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8691                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8692    }
8693
8694    /**
8695     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8696     * layout attribute and/or the inherited value from the parent
8697     *
8698     * @return true if the layout is right-to-left.
8699     *
8700     * @hide
8701     */
8702    @ViewDebug.ExportedProperty(category = "layout")
8703    public boolean isLayoutRtl() {
8704        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8705    }
8706
8707    /**
8708     * Indicates whether the view is currently tracking transient state that the
8709     * app should not need to concern itself with saving and restoring, but that
8710     * the framework should take special note to preserve when possible.
8711     *
8712     * <p>A view with transient state cannot be trivially rebound from an external
8713     * data source, such as an adapter binding item views in a list. This may be
8714     * because the view is performing an animation, tracking user selection
8715     * of content, or similar.</p>
8716     *
8717     * @return true if the view has transient state
8718     */
8719    @ViewDebug.ExportedProperty(category = "layout")
8720    public boolean hasTransientState() {
8721        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8722    }
8723
8724    /**
8725     * Set whether this view is currently tracking transient state that the
8726     * framework should attempt to preserve when possible. This flag is reference counted,
8727     * so every call to setHasTransientState(true) should be paired with a later call
8728     * to setHasTransientState(false).
8729     *
8730     * <p>A view with transient state cannot be trivially rebound from an external
8731     * data source, such as an adapter binding item views in a list. This may be
8732     * because the view is performing an animation, tracking user selection
8733     * of content, or similar.</p>
8734     *
8735     * @param hasTransientState true if this view has transient state
8736     */
8737    public void setHasTransientState(boolean hasTransientState) {
8738        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8739                mTransientStateCount - 1;
8740        if (mTransientStateCount < 0) {
8741            mTransientStateCount = 0;
8742            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8743                    "unmatched pair of setHasTransientState calls");
8744        } else if ((hasTransientState && mTransientStateCount == 1) ||
8745                (!hasTransientState && mTransientStateCount == 0)) {
8746            // update flag if we've just incremented up from 0 or decremented down to 0
8747            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8748                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8749            if (mParent != null) {
8750                try {
8751                    mParent.childHasTransientStateChanged(this, hasTransientState);
8752                } catch (AbstractMethodError e) {
8753                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8754                            " does not fully implement ViewParent", e);
8755                }
8756            }
8757        }
8758    }
8759
8760    /**
8761     * Returns true if this view is currently attached to a window.
8762     */
8763    public boolean isAttachedToWindow() {
8764        return mAttachInfo != null;
8765    }
8766
8767    /**
8768     * Returns true if this view has been through at least one layout since it
8769     * was last attached to or detached from a window.
8770     */
8771    public boolean isLaidOut() {
8772        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8773    }
8774
8775    /**
8776     * If this view doesn't do any drawing on its own, set this flag to
8777     * allow further optimizations. By default, this flag is not set on
8778     * View, but could be set on some View subclasses such as ViewGroup.
8779     *
8780     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8781     * you should clear this flag.
8782     *
8783     * @param willNotDraw whether or not this View draw on its own
8784     */
8785    public void setWillNotDraw(boolean willNotDraw) {
8786        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8787    }
8788
8789    /**
8790     * Returns whether or not this View draws on its own.
8791     *
8792     * @return true if this view has nothing to draw, false otherwise
8793     */
8794    @ViewDebug.ExportedProperty(category = "drawing")
8795    public boolean willNotDraw() {
8796        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8797    }
8798
8799    /**
8800     * When a View's drawing cache is enabled, drawing is redirected to an
8801     * offscreen bitmap. Some views, like an ImageView, must be able to
8802     * bypass this mechanism if they already draw a single bitmap, to avoid
8803     * unnecessary usage of the memory.
8804     *
8805     * @param willNotCacheDrawing true if this view does not cache its
8806     *        drawing, false otherwise
8807     */
8808    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8809        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8810    }
8811
8812    /**
8813     * Returns whether or not this View can cache its drawing or not.
8814     *
8815     * @return true if this view does not cache its drawing, false otherwise
8816     */
8817    @ViewDebug.ExportedProperty(category = "drawing")
8818    public boolean willNotCacheDrawing() {
8819        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8820    }
8821
8822    /**
8823     * Indicates whether this view reacts to click events or not.
8824     *
8825     * @return true if the view is clickable, false otherwise
8826     *
8827     * @see #setClickable(boolean)
8828     * @attr ref android.R.styleable#View_clickable
8829     */
8830    @ViewDebug.ExportedProperty
8831    public boolean isClickable() {
8832        return (mViewFlags & CLICKABLE) == CLICKABLE;
8833    }
8834
8835    /**
8836     * Enables or disables click events for this view. When a view
8837     * is clickable it will change its state to "pressed" on every click.
8838     * Subclasses should set the view clickable to visually react to
8839     * user's clicks.
8840     *
8841     * @param clickable true to make the view clickable, false otherwise
8842     *
8843     * @see #isClickable()
8844     * @attr ref android.R.styleable#View_clickable
8845     */
8846    public void setClickable(boolean clickable) {
8847        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8848    }
8849
8850    /**
8851     * Indicates whether this view reacts to long click events or not.
8852     *
8853     * @return true if the view is long clickable, false otherwise
8854     *
8855     * @see #setLongClickable(boolean)
8856     * @attr ref android.R.styleable#View_longClickable
8857     */
8858    public boolean isLongClickable() {
8859        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8860    }
8861
8862    /**
8863     * Enables or disables long click events for this view. When a view is long
8864     * clickable it reacts to the user holding down the button for a longer
8865     * duration than a tap. This event can either launch the listener or a
8866     * context menu.
8867     *
8868     * @param longClickable true to make the view long clickable, false otherwise
8869     * @see #isLongClickable()
8870     * @attr ref android.R.styleable#View_longClickable
8871     */
8872    public void setLongClickable(boolean longClickable) {
8873        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8874    }
8875
8876    /**
8877     * Indicates whether this view reacts to context clicks or not.
8878     *
8879     * @return true if the view is context clickable, false otherwise
8880     * @see #setContextClickable(boolean)
8881     * @attr ref android.R.styleable#View_contextClickable
8882     */
8883    public boolean isContextClickable() {
8884        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8885    }
8886
8887    /**
8888     * Enables or disables context clicking for this view. This event can launch the listener.
8889     *
8890     * @param contextClickable true to make the view react to a context click, false otherwise
8891     * @see #isContextClickable()
8892     * @attr ref android.R.styleable#View_contextClickable
8893     */
8894    public void setContextClickable(boolean contextClickable) {
8895        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8896    }
8897
8898    /**
8899     * Sets the pressed state for this view and provides a touch coordinate for
8900     * animation hinting.
8901     *
8902     * @param pressed Pass true to set the View's internal state to "pressed",
8903     *            or false to reverts the View's internal state from a
8904     *            previously set "pressed" state.
8905     * @param x The x coordinate of the touch that caused the press
8906     * @param y The y coordinate of the touch that caused the press
8907     */
8908    private void setPressed(boolean pressed, float x, float y) {
8909        if (pressed) {
8910            drawableHotspotChanged(x, y);
8911        }
8912
8913        setPressed(pressed);
8914    }
8915
8916    /**
8917     * Sets the pressed state for this view.
8918     *
8919     * @see #isClickable()
8920     * @see #setClickable(boolean)
8921     *
8922     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8923     *        the View's internal state from a previously set "pressed" state.
8924     */
8925    public void setPressed(boolean pressed) {
8926        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8927
8928        if (pressed) {
8929            mPrivateFlags |= PFLAG_PRESSED;
8930        } else {
8931            mPrivateFlags &= ~PFLAG_PRESSED;
8932        }
8933
8934        if (needsRefresh) {
8935            refreshDrawableState();
8936        }
8937        dispatchSetPressed(pressed);
8938    }
8939
8940    /**
8941     * Dispatch setPressed to all of this View's children.
8942     *
8943     * @see #setPressed(boolean)
8944     *
8945     * @param pressed The new pressed state
8946     */
8947    protected void dispatchSetPressed(boolean pressed) {
8948    }
8949
8950    /**
8951     * Indicates whether the view is currently in pressed state. Unless
8952     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8953     * the pressed state.
8954     *
8955     * @see #setPressed(boolean)
8956     * @see #isClickable()
8957     * @see #setClickable(boolean)
8958     *
8959     * @return true if the view is currently pressed, false otherwise
8960     */
8961    @ViewDebug.ExportedProperty
8962    public boolean isPressed() {
8963        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8964    }
8965
8966    /**
8967     * @hide
8968     * Indicates whether this view will participate in data collection through
8969     * {@link ViewStructure}.  If true, it will not provide any data
8970     * for itself or its children.  If false, the normal data collection will be allowed.
8971     *
8972     * @return Returns false if assist data collection is not blocked, else true.
8973     *
8974     * @see #setAssistBlocked(boolean)
8975     * @attr ref android.R.styleable#View_assistBlocked
8976     */
8977    public boolean isAssistBlocked() {
8978        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8979    }
8980
8981    /**
8982     * @hide
8983     * Indicates whether this view will participate in data collection through
8984     * {@link ViewStructure} for auto-fill purposes.
8985     *
8986     * <p>If {@code true}, it will not provide any data for itself or its children.
8987     * <p>If {@code false}, the normal data collection will be allowed.
8988     *
8989     * @return Returns {@code false} if assist data collection for auto-fill is not blocked,
8990     * else {@code true}.
8991     *
8992     * TODO(b/33197203): update / remove javadoc tags below
8993     * @see #setAssistBlocked(boolean)
8994     * @attr ref android.R.styleable#View_assistBlocked
8995     */
8996    public boolean isAutoFillBlocked() {
8997        return false; // TODO(b/33197203): properly implement it
8998    }
8999
9000    /**
9001     * @hide
9002     * Controls whether assist data collection from this view and its children is enabled
9003     * (that is, whether {@link #onProvideStructure} and
9004     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
9005     * allowing normal assist collection.  Setting this to false will disable assist collection.
9006     *
9007     * @param enabled Set to true to <em>disable</em> assist data collection, or false
9008     * (the default) to allow it.
9009     *
9010     * @see #isAssistBlocked()
9011     * @see #onProvideStructure
9012     * @see #onProvideVirtualStructure
9013     * @attr ref android.R.styleable#View_assistBlocked
9014     */
9015    public void setAssistBlocked(boolean enabled) {
9016        if (enabled) {
9017            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
9018        } else {
9019            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
9020        }
9021    }
9022
9023    /**
9024     * Indicates whether this view will save its state (that is,
9025     * whether its {@link #onSaveInstanceState} method will be called).
9026     *
9027     * @return Returns true if the view state saving is enabled, else false.
9028     *
9029     * @see #setSaveEnabled(boolean)
9030     * @attr ref android.R.styleable#View_saveEnabled
9031     */
9032    public boolean isSaveEnabled() {
9033        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
9034    }
9035
9036    /**
9037     * Controls whether the saving of this view's state is
9038     * enabled (that is, whether its {@link #onSaveInstanceState} method
9039     * will be called).  Note that even if freezing is enabled, the
9040     * view still must have an id assigned to it (via {@link #setId(int)})
9041     * for its state to be saved.  This flag can only disable the
9042     * saving of this view; any child views may still have their state saved.
9043     *
9044     * @param enabled Set to false to <em>disable</em> state saving, or true
9045     * (the default) to allow it.
9046     *
9047     * @see #isSaveEnabled()
9048     * @see #setId(int)
9049     * @see #onSaveInstanceState()
9050     * @attr ref android.R.styleable#View_saveEnabled
9051     */
9052    public void setSaveEnabled(boolean enabled) {
9053        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
9054    }
9055
9056    /**
9057     * Gets whether the framework should discard touches when the view's
9058     * window is obscured by another visible window.
9059     * Refer to the {@link View} security documentation for more details.
9060     *
9061     * @return True if touch filtering is enabled.
9062     *
9063     * @see #setFilterTouchesWhenObscured(boolean)
9064     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9065     */
9066    @ViewDebug.ExportedProperty
9067    public boolean getFilterTouchesWhenObscured() {
9068        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
9069    }
9070
9071    /**
9072     * Sets whether the framework should discard touches when the view's
9073     * window is obscured by another visible window.
9074     * Refer to the {@link View} security documentation for more details.
9075     *
9076     * @param enabled True if touch filtering should be enabled.
9077     *
9078     * @see #getFilterTouchesWhenObscured
9079     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9080     */
9081    public void setFilterTouchesWhenObscured(boolean enabled) {
9082        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
9083                FILTER_TOUCHES_WHEN_OBSCURED);
9084    }
9085
9086    /**
9087     * Indicates whether the entire hierarchy under this view will save its
9088     * state when a state saving traversal occurs from its parent.  The default
9089     * is true; if false, these views will not be saved unless
9090     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9091     *
9092     * @return Returns true if the view state saving from parent is enabled, else false.
9093     *
9094     * @see #setSaveFromParentEnabled(boolean)
9095     */
9096    public boolean isSaveFromParentEnabled() {
9097        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
9098    }
9099
9100    /**
9101     * Controls whether the entire hierarchy under this view will save its
9102     * state when a state saving traversal occurs from its parent.  The default
9103     * is true; if false, these views will not be saved unless
9104     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9105     *
9106     * @param enabled Set to false to <em>disable</em> state saving, or true
9107     * (the default) to allow it.
9108     *
9109     * @see #isSaveFromParentEnabled()
9110     * @see #setId(int)
9111     * @see #onSaveInstanceState()
9112     */
9113    public void setSaveFromParentEnabled(boolean enabled) {
9114        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
9115    }
9116
9117
9118    /**
9119     * Returns whether this View is currently able to take focus.
9120     *
9121     * @return True if this view can take focus, or false otherwise.
9122     */
9123    @ViewDebug.ExportedProperty(category = "focus")
9124    public final boolean isFocusable() {
9125        return FOCUSABLE == (mViewFlags & FOCUSABLE);
9126    }
9127
9128    /**
9129     * Returns the focusable setting for this view.
9130     *
9131     * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}.
9132     * @attr ref android.R.styleable#View_focusable
9133     */
9134    @ViewDebug.ExportedProperty(mapping = {
9135            @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"),
9136            @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"),
9137            @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO")
9138            })
9139    @Focusable
9140    public int getFocusable() {
9141        return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
9142    }
9143
9144    /**
9145     * When a view is focusable, it may not want to take focus when in touch mode.
9146     * For example, a button would like focus when the user is navigating via a D-pad
9147     * so that the user can click on it, but once the user starts touching the screen,
9148     * the button shouldn't take focus
9149     * @return Whether the view is focusable in touch mode.
9150     * @attr ref android.R.styleable#View_focusableInTouchMode
9151     */
9152    @ViewDebug.ExportedProperty
9153    public final boolean isFocusableInTouchMode() {
9154        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
9155    }
9156
9157    /**
9158     * Find the nearest view in the specified direction that can take focus.
9159     * This does not actually give focus to that view.
9160     *
9161     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9162     *
9163     * @return The nearest focusable in the specified direction, or null if none
9164     *         can be found.
9165     */
9166    public View focusSearch(@FocusRealDirection int direction) {
9167        if (mParent != null) {
9168            return mParent.focusSearch(this, direction);
9169        } else {
9170            return null;
9171        }
9172    }
9173
9174    /**
9175     * Returns whether this View is a root of a keyboard navigation cluster.
9176     *
9177     * @return True if this view is a root of a cluster, or false otherwise.
9178     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9179     */
9180    @ViewDebug.ExportedProperty(category = "keyboardNavigationCluster")
9181    public final boolean isKeyboardNavigationCluster() {
9182        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
9183    }
9184
9185    /**
9186     * Set whether this view is a root of a keyboard navigation cluster.
9187     *
9188     * @param isCluster If true, this view is a root of a cluster.
9189     *
9190     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9191     */
9192    public void setKeyboardNavigationCluster(boolean isCluster) {
9193        if (isCluster) {
9194            mPrivateFlags3 |= PFLAG3_CLUSTER;
9195        } else {
9196            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
9197        }
9198    }
9199
9200    /**
9201     * Returns whether this View should receive focus when the focus is restored for the view
9202     * hierarchy containing this view.
9203     * <p>
9204     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9205     * window or serves as a target of cluster navigation.
9206     *
9207     * @see #restoreDefaultFocus(int)
9208     *
9209     * @return {@code true} if this view is the default-focus view, {@code false} otherwise
9210     * @attr ref android.R.styleable#View_focusedByDefault
9211     */
9212    @ViewDebug.ExportedProperty(category = "focusedByDefault")
9213    public final boolean isFocusedByDefault() {
9214        return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
9215    }
9216
9217    /**
9218     * Sets whether this View should receive focus when the focus is restored for the view
9219     * hierarchy containing this view.
9220     * <p>
9221     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9222     * window or serves as a target of cluster navigation.
9223     *
9224     * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
9225     *                           {@code false} otherwise.
9226     *
9227     * @see #restoreDefaultFocus(int)
9228     *
9229     * @attr ref android.R.styleable#View_focusedByDefault
9230     */
9231    public void setFocusedByDefault(boolean isFocusedByDefault) {
9232        if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
9233            return;
9234        }
9235
9236        if (isFocusedByDefault) {
9237            mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
9238        } else {
9239            mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
9240        }
9241
9242        if (mParent instanceof ViewGroup) {
9243            if (isFocusedByDefault) {
9244                ((ViewGroup) mParent).setDefaultFocus(this);
9245            } else {
9246                ((ViewGroup) mParent).cleanDefaultFocus(this);
9247            }
9248        }
9249    }
9250
9251    /**
9252     * Returns whether the view hierarchy with this view as a root contain a default-focus view.
9253     *
9254     * @return {@code true} if this view has default focus, {@code false} otherwise
9255     */
9256    boolean hasDefaultFocus() {
9257        return isFocusedByDefault();
9258    }
9259
9260    /**
9261     * Find the nearest keyboard navigation cluster in the specified direction.
9262     * This does not actually give focus to that cluster.
9263     *
9264     * @param currentCluster The starting point of the search. Null means the current cluster is not
9265     *                       found yet
9266     * @param direction Direction to look
9267     *
9268     * @return The nearest keyboard navigation cluster in the specified direction, or null if none
9269     *         can be found
9270     */
9271    public View keyboardNavigationClusterSearch(View currentCluster, int direction) {
9272        if (isKeyboardNavigationCluster()) {
9273            currentCluster = this;
9274        }
9275        if (isRootNamespace()) {
9276            // Root namespace means we should consider ourselves the top of the
9277            // tree for group searching; otherwise we could be group searching
9278            // into other tabs.  see LocalActivityManager and TabHost for more info.
9279            return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
9280                    this, currentCluster, direction);
9281        } else if (mParent != null) {
9282            return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
9283        }
9284        return null;
9285    }
9286
9287    /**
9288     * This method is the last chance for the focused view and its ancestors to
9289     * respond to an arrow key. This is called when the focused view did not
9290     * consume the key internally, nor could the view system find a new view in
9291     * the requested direction to give focus to.
9292     *
9293     * @param focused The currently focused view.
9294     * @param direction The direction focus wants to move. One of FOCUS_UP,
9295     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
9296     * @return True if the this view consumed this unhandled move.
9297     */
9298    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
9299        return false;
9300    }
9301
9302    /**
9303     * If a user manually specified the next view id for a particular direction,
9304     * use the root to look up the view.
9305     * @param root The root view of the hierarchy containing this view.
9306     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
9307     * or FOCUS_BACKWARD.
9308     * @return The user specified next view, or null if there is none.
9309     */
9310    View findUserSetNextFocus(View root, @FocusDirection int direction) {
9311        switch (direction) {
9312            case FOCUS_LEFT:
9313                if (mNextFocusLeftId == View.NO_ID) return null;
9314                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
9315            case FOCUS_RIGHT:
9316                if (mNextFocusRightId == View.NO_ID) return null;
9317                return findViewInsideOutShouldExist(root, mNextFocusRightId);
9318            case FOCUS_UP:
9319                if (mNextFocusUpId == View.NO_ID) return null;
9320                return findViewInsideOutShouldExist(root, mNextFocusUpId);
9321            case FOCUS_DOWN:
9322                if (mNextFocusDownId == View.NO_ID) return null;
9323                return findViewInsideOutShouldExist(root, mNextFocusDownId);
9324            case FOCUS_FORWARD:
9325                if (mNextFocusForwardId == View.NO_ID) return null;
9326                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
9327            case FOCUS_BACKWARD: {
9328                if (mID == View.NO_ID) return null;
9329                final int id = mID;
9330                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
9331                    @Override
9332                    public boolean apply(View t) {
9333                        return t.mNextFocusForwardId == id;
9334                    }
9335                });
9336            }
9337        }
9338        return null;
9339    }
9340
9341    private View findViewInsideOutShouldExist(View root, int id) {
9342        if (mMatchIdPredicate == null) {
9343            mMatchIdPredicate = new MatchIdPredicate();
9344        }
9345        mMatchIdPredicate.mId = id;
9346        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
9347        if (result == null) {
9348            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
9349        }
9350        return result;
9351    }
9352
9353    /**
9354     * Find and return all focusable views that are descendants of this view,
9355     * possibly including this view if it is focusable itself.
9356     *
9357     * @param direction The direction of the focus
9358     * @return A list of focusable views
9359     */
9360    public ArrayList<View> getFocusables(@FocusDirection int direction) {
9361        ArrayList<View> result = new ArrayList<View>(24);
9362        addFocusables(result, direction);
9363        return result;
9364    }
9365
9366    /**
9367     * Add any focusable views that are descendants of this view (possibly
9368     * including this view if it is focusable itself) to views.  If we are in touch mode,
9369     * only add views that are also focusable in touch mode.
9370     *
9371     * @param views Focusable views found so far
9372     * @param direction The direction of the focus
9373     */
9374    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
9375        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
9376    }
9377
9378    /**
9379     * Adds any focusable views that are descendants of this view (possibly
9380     * including this view if it is focusable itself) to views. This method
9381     * adds all focusable views regardless if we are in touch mode or
9382     * only views focusable in touch mode if we are in touch mode or
9383     * only views that can take accessibility focus if accessibility is enabled
9384     * depending on the focusable mode parameter.
9385     *
9386     * @param views Focusable views found so far or null if all we are interested is
9387     *        the number of focusables.
9388     * @param direction The direction of the focus.
9389     * @param focusableMode The type of focusables to be added.
9390     *
9391     * @see #FOCUSABLES_ALL
9392     * @see #FOCUSABLES_TOUCH_MODE
9393     */
9394    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
9395            @FocusableMode int focusableMode) {
9396        if (views == null) {
9397            return;
9398        }
9399        if (!isFocusable()) {
9400            return;
9401        }
9402        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
9403                && !isFocusableInTouchMode()) {
9404            return;
9405        }
9406        views.add(this);
9407    }
9408
9409    /**
9410     * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
9411     * including this view if it is a cluster root itself) to views.
9412     *
9413     * @param views Keyboard navigation cluster roots found so far
9414     * @param direction Direction to look
9415     */
9416    public void addKeyboardNavigationClusters(
9417            @NonNull Collection<View> views,
9418            int direction) {
9419        if (!(isKeyboardNavigationCluster())) {
9420            return;
9421        }
9422        views.add(this);
9423    }
9424
9425    /**
9426     * Finds the Views that contain given text. The containment is case insensitive.
9427     * The search is performed by either the text that the View renders or the content
9428     * description that describes the view for accessibility purposes and the view does
9429     * not render or both. Clients can specify how the search is to be performed via
9430     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
9431     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
9432     *
9433     * @param outViews The output list of matching Views.
9434     * @param searched The text to match against.
9435     *
9436     * @see #FIND_VIEWS_WITH_TEXT
9437     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
9438     * @see #setContentDescription(CharSequence)
9439     */
9440    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
9441            @FindViewFlags int flags) {
9442        if (getAccessibilityNodeProvider() != null) {
9443            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
9444                outViews.add(this);
9445            }
9446        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
9447                && (searched != null && searched.length() > 0)
9448                && (mContentDescription != null && mContentDescription.length() > 0)) {
9449            String searchedLowerCase = searched.toString().toLowerCase();
9450            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
9451            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
9452                outViews.add(this);
9453            }
9454        }
9455    }
9456
9457    /**
9458     * Find and return all touchable views that are descendants of this view,
9459     * possibly including this view if it is touchable itself.
9460     *
9461     * @return A list of touchable views
9462     */
9463    public ArrayList<View> getTouchables() {
9464        ArrayList<View> result = new ArrayList<View>();
9465        addTouchables(result);
9466        return result;
9467    }
9468
9469    /**
9470     * Add any touchable views that are descendants of this view (possibly
9471     * including this view if it is touchable itself) to views.
9472     *
9473     * @param views Touchable views found so far
9474     */
9475    public void addTouchables(ArrayList<View> views) {
9476        final int viewFlags = mViewFlags;
9477
9478        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
9479                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
9480                && (viewFlags & ENABLED_MASK) == ENABLED) {
9481            views.add(this);
9482        }
9483    }
9484
9485    /**
9486     * Returns whether this View is accessibility focused.
9487     *
9488     * @return True if this View is accessibility focused.
9489     */
9490    public boolean isAccessibilityFocused() {
9491        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
9492    }
9493
9494    /**
9495     * Call this to try to give accessibility focus to this view.
9496     *
9497     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
9498     * returns false or the view is no visible or the view already has accessibility
9499     * focus.
9500     *
9501     * See also {@link #focusSearch(int)}, which is what you call to say that you
9502     * have focus, and you want your parent to look for the next one.
9503     *
9504     * @return Whether this view actually took accessibility focus.
9505     *
9506     * @hide
9507     */
9508    public boolean requestAccessibilityFocus() {
9509        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
9510        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
9511            return false;
9512        }
9513        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9514            return false;
9515        }
9516        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
9517            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
9518            ViewRootImpl viewRootImpl = getViewRootImpl();
9519            if (viewRootImpl != null) {
9520                viewRootImpl.setAccessibilityFocus(this, null);
9521            }
9522            invalidate();
9523            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
9524            return true;
9525        }
9526        return false;
9527    }
9528
9529    /**
9530     * Call this to try to clear accessibility focus of this view.
9531     *
9532     * See also {@link #focusSearch(int)}, which is what you call to say that you
9533     * have focus, and you want your parent to look for the next one.
9534     *
9535     * @hide
9536     */
9537    public void clearAccessibilityFocus() {
9538        clearAccessibilityFocusNoCallbacks(0);
9539
9540        // Clear the global reference of accessibility focus if this view or
9541        // any of its descendants had accessibility focus. This will NOT send
9542        // an event or update internal state if focus is cleared from a
9543        // descendant view, which may leave views in inconsistent states.
9544        final ViewRootImpl viewRootImpl = getViewRootImpl();
9545        if (viewRootImpl != null) {
9546            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
9547            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9548                viewRootImpl.setAccessibilityFocus(null, null);
9549            }
9550        }
9551    }
9552
9553    private void sendAccessibilityHoverEvent(int eventType) {
9554        // Since we are not delivering to a client accessibility events from not
9555        // important views (unless the clinet request that) we need to fire the
9556        // event from the deepest view exposed to the client. As a consequence if
9557        // the user crosses a not exposed view the client will see enter and exit
9558        // of the exposed predecessor followed by and enter and exit of that same
9559        // predecessor when entering and exiting the not exposed descendant. This
9560        // is fine since the client has a clear idea which view is hovered at the
9561        // price of a couple more events being sent. This is a simple and
9562        // working solution.
9563        View source = this;
9564        while (true) {
9565            if (source.includeForAccessibility()) {
9566                source.sendAccessibilityEvent(eventType);
9567                return;
9568            }
9569            ViewParent parent = source.getParent();
9570            if (parent instanceof View) {
9571                source = (View) parent;
9572            } else {
9573                return;
9574            }
9575        }
9576    }
9577
9578    /**
9579     * Clears accessibility focus without calling any callback methods
9580     * normally invoked in {@link #clearAccessibilityFocus()}. This method
9581     * is used separately from that one for clearing accessibility focus when
9582     * giving this focus to another view.
9583     *
9584     * @param action The action, if any, that led to focus being cleared. Set to
9585     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
9586     * the window.
9587     */
9588    void clearAccessibilityFocusNoCallbacks(int action) {
9589        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
9590            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
9591            invalidate();
9592            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9593                AccessibilityEvent event = AccessibilityEvent.obtain(
9594                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
9595                event.setAction(action);
9596                if (mAccessibilityDelegate != null) {
9597                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
9598                } else {
9599                    sendAccessibilityEventUnchecked(event);
9600                }
9601            }
9602        }
9603    }
9604
9605    /**
9606     * Call this to try to give focus to a specific view or to one of its
9607     * descendants.
9608     *
9609     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9610     * false), or if it is focusable and it is not focusable in touch mode
9611     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9612     *
9613     * See also {@link #focusSearch(int)}, which is what you call to say that you
9614     * have focus, and you want your parent to look for the next one.
9615     *
9616     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
9617     * {@link #FOCUS_DOWN} and <code>null</code>.
9618     *
9619     * @return Whether this view or one of its descendants actually took focus.
9620     */
9621    public final boolean requestFocus() {
9622        return requestFocus(View.FOCUS_DOWN);
9623    }
9624
9625    /**
9626     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
9627     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
9628     * Nested keyboard navigation clusters are excluded from the hierarchy.
9629     *
9630     * @param direction The direction of the focus
9631     * @return Whether this view or one of its descendants actually took focus
9632     */
9633    public boolean restoreDefaultFocus(@FocusDirection int direction) {
9634        return requestFocus(direction);
9635    }
9636
9637    /**
9638     * Call this to try to give focus to a specific view or to one of its
9639     * descendants and give it a hint about what direction focus is heading.
9640     *
9641     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9642     * false), or if it is focusable and it is not focusable in touch mode
9643     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9644     *
9645     * See also {@link #focusSearch(int)}, which is what you call to say that you
9646     * have focus, and you want your parent to look for the next one.
9647     *
9648     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9649     * <code>null</code> set for the previously focused rectangle.
9650     *
9651     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9652     * @return Whether this view or one of its descendants actually took focus.
9653     */
9654    public final boolean requestFocus(int direction) {
9655        return requestFocus(direction, null);
9656    }
9657
9658    /**
9659     * Call this to try to give focus to a specific view or to one of its descendants
9660     * and give it hints about the direction and a specific rectangle that the focus
9661     * is coming from.  The rectangle can help give larger views a finer grained hint
9662     * about where focus is coming from, and therefore, where to show selection, or
9663     * forward focus change internally.
9664     *
9665     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9666     * false), or if it is focusable and it is not focusable in touch mode
9667     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9668     *
9669     * A View will not take focus if it is not visible.
9670     *
9671     * A View will not take focus if one of its parents has
9672     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9673     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9674     *
9675     * See also {@link #focusSearch(int)}, which is what you call to say that you
9676     * have focus, and you want your parent to look for the next one.
9677     *
9678     * You may wish to override this method if your custom {@link View} has an internal
9679     * {@link View} that it wishes to forward the request to.
9680     *
9681     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9682     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9683     *        to give a finer grained hint about where focus is coming from.  May be null
9684     *        if there is no hint.
9685     * @return Whether this view or one of its descendants actually took focus.
9686     */
9687    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9688        return requestFocusNoSearch(direction, previouslyFocusedRect);
9689    }
9690
9691    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9692        // need to be focusable
9693        if ((mViewFlags & FOCUSABLE) != FOCUSABLE
9694                || (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9695            return false;
9696        }
9697
9698        // need to be focusable in touch mode if in touch mode
9699        if (isInTouchMode() &&
9700            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9701               return false;
9702        }
9703
9704        // need to not have any parents blocking us
9705        if (hasAncestorThatBlocksDescendantFocus()) {
9706            return false;
9707        }
9708
9709        handleFocusGainInternal(direction, previouslyFocusedRect);
9710        return true;
9711    }
9712
9713    /**
9714     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9715     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9716     * touch mode to request focus when they are touched.
9717     *
9718     * @return Whether this view or one of its descendants actually took focus.
9719     *
9720     * @see #isInTouchMode()
9721     *
9722     */
9723    public final boolean requestFocusFromTouch() {
9724        // Leave touch mode if we need to
9725        if (isInTouchMode()) {
9726            ViewRootImpl viewRoot = getViewRootImpl();
9727            if (viewRoot != null) {
9728                viewRoot.ensureTouchMode(false);
9729            }
9730        }
9731        return requestFocus(View.FOCUS_DOWN);
9732    }
9733
9734    /**
9735     * @return Whether any ancestor of this view blocks descendant focus.
9736     */
9737    private boolean hasAncestorThatBlocksDescendantFocus() {
9738        final boolean focusableInTouchMode = isFocusableInTouchMode();
9739        ViewParent ancestor = mParent;
9740        while (ancestor instanceof ViewGroup) {
9741            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9742            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9743                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9744                return true;
9745            } else {
9746                ancestor = vgAncestor.getParent();
9747            }
9748        }
9749        return false;
9750    }
9751
9752    /**
9753     * Gets the mode for determining whether this View is important for accessibility.
9754     * A view is important for accessibility if it fires accessibility events and if it
9755     * is reported to accessibility services that query the screen.
9756     *
9757     * @return The mode for determining whether a view is important for accessibility, one
9758     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
9759     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
9760     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
9761     *
9762     * @attr ref android.R.styleable#View_importantForAccessibility
9763     *
9764     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9765     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9766     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9767     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9768     */
9769    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9770            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9771            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9772            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9773            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9774                    to = "noHideDescendants")
9775        })
9776    public int getImportantForAccessibility() {
9777        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9778                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9779    }
9780
9781    /**
9782     * Sets the live region mode for this view. This indicates to accessibility
9783     * services whether they should automatically notify the user about changes
9784     * to the view's content description or text, or to the content descriptions
9785     * or text of the view's children (where applicable).
9786     * <p>
9787     * For example, in a login screen with a TextView that displays an "incorrect
9788     * password" notification, that view should be marked as a live region with
9789     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9790     * <p>
9791     * To disable change notifications for this view, use
9792     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9793     * mode for most views.
9794     * <p>
9795     * To indicate that the user should be notified of changes, use
9796     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9797     * <p>
9798     * If the view's changes should interrupt ongoing speech and notify the user
9799     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9800     *
9801     * @param mode The live region mode for this view, one of:
9802     *        <ul>
9803     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9804     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9805     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9806     *        </ul>
9807     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9808     */
9809    public void setAccessibilityLiveRegion(int mode) {
9810        if (mode != getAccessibilityLiveRegion()) {
9811            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9812            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9813                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9814            notifyViewAccessibilityStateChangedIfNeeded(
9815                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9816        }
9817    }
9818
9819    /**
9820     * Gets the live region mode for this View.
9821     *
9822     * @return The live region mode for the view.
9823     *
9824     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9825     *
9826     * @see #setAccessibilityLiveRegion(int)
9827     */
9828    public int getAccessibilityLiveRegion() {
9829        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9830                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9831    }
9832
9833    /**
9834     * Sets how to determine whether this view is important for accessibility
9835     * which is if it fires accessibility events and if it is reported to
9836     * accessibility services that query the screen.
9837     *
9838     * @param mode How to determine whether this view is important for accessibility.
9839     *
9840     * @attr ref android.R.styleable#View_importantForAccessibility
9841     *
9842     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9843     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9844     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9845     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9846     */
9847    public void setImportantForAccessibility(int mode) {
9848        final int oldMode = getImportantForAccessibility();
9849        if (mode != oldMode) {
9850            final boolean hideDescendants =
9851                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9852
9853            // If this node or its descendants are no longer important, try to
9854            // clear accessibility focus.
9855            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9856                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9857                if (focusHost != null) {
9858                    focusHost.clearAccessibilityFocus();
9859                }
9860            }
9861
9862            // If we're moving between AUTO and another state, we might not need
9863            // to send a subtree changed notification. We'll store the computed
9864            // importance, since we'll need to check it later to make sure.
9865            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9866                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9867            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9868            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9869            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9870                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9871            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9872                notifySubtreeAccessibilityStateChangedIfNeeded();
9873            } else {
9874                notifyViewAccessibilityStateChangedIfNeeded(
9875                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9876            }
9877        }
9878    }
9879
9880    /**
9881     * Returns the view within this view's hierarchy that is hosting
9882     * accessibility focus.
9883     *
9884     * @param searchDescendants whether to search for focus in descendant views
9885     * @return the view hosting accessibility focus, or {@code null}
9886     */
9887    private View findAccessibilityFocusHost(boolean searchDescendants) {
9888        if (isAccessibilityFocusedViewOrHost()) {
9889            return this;
9890        }
9891
9892        if (searchDescendants) {
9893            final ViewRootImpl viewRoot = getViewRootImpl();
9894            if (viewRoot != null) {
9895                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9896                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9897                    return focusHost;
9898                }
9899            }
9900        }
9901
9902        return null;
9903    }
9904
9905    /**
9906     * Computes whether this view should be exposed for accessibility. In
9907     * general, views that are interactive or provide information are exposed
9908     * while views that serve only as containers are hidden.
9909     * <p>
9910     * If an ancestor of this view has importance
9911     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9912     * returns <code>false</code>.
9913     * <p>
9914     * Otherwise, the value is computed according to the view's
9915     * {@link #getImportantForAccessibility()} value:
9916     * <ol>
9917     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9918     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9919     * </code>
9920     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9921     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9922     * view satisfies any of the following:
9923     * <ul>
9924     * <li>Is actionable, e.g. {@link #isClickable()},
9925     * {@link #isLongClickable()}, or {@link #isFocusable()}
9926     * <li>Has an {@link AccessibilityDelegate}
9927     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9928     * {@link OnKeyListener}, etc.
9929     * <li>Is an accessibility live region, e.g.
9930     * {@link #getAccessibilityLiveRegion()} is not
9931     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9932     * </ul>
9933     * </ol>
9934     *
9935     * @return Whether the view is exposed for accessibility.
9936     * @see #setImportantForAccessibility(int)
9937     * @see #getImportantForAccessibility()
9938     */
9939    public boolean isImportantForAccessibility() {
9940        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9941                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9942        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9943                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9944            return false;
9945        }
9946
9947        // Check parent mode to ensure we're not hidden.
9948        ViewParent parent = mParent;
9949        while (parent instanceof View) {
9950            if (((View) parent).getImportantForAccessibility()
9951                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9952                return false;
9953            }
9954            parent = parent.getParent();
9955        }
9956
9957        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9958                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9959                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9960    }
9961
9962    /**
9963     * Gets the parent for accessibility purposes. Note that the parent for
9964     * accessibility is not necessary the immediate parent. It is the first
9965     * predecessor that is important for accessibility.
9966     *
9967     * @return The parent for accessibility purposes.
9968     */
9969    public ViewParent getParentForAccessibility() {
9970        if (mParent instanceof View) {
9971            View parentView = (View) mParent;
9972            if (parentView.includeForAccessibility()) {
9973                return mParent;
9974            } else {
9975                return mParent.getParentForAccessibility();
9976            }
9977        }
9978        return null;
9979    }
9980
9981    /**
9982     * Adds the children of this View relevant for accessibility to the given list
9983     * as output. Since some Views are not important for accessibility the added
9984     * child views are not necessarily direct children of this view, rather they are
9985     * the first level of descendants important for accessibility.
9986     *
9987     * @param outChildren The output list that will receive children for accessibility.
9988     */
9989    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9990
9991    }
9992
9993    /**
9994     * Whether to regard this view for accessibility. A view is regarded for
9995     * accessibility if it is important for accessibility or the querying
9996     * accessibility service has explicitly requested that view not
9997     * important for accessibility are regarded.
9998     *
9999     * @return Whether to regard the view for accessibility.
10000     *
10001     * @hide
10002     */
10003    public boolean includeForAccessibility() {
10004        if (mAttachInfo != null) {
10005            return (mAttachInfo.mAccessibilityFetchFlags
10006                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
10007                    || isImportantForAccessibility();
10008        }
10009        return false;
10010    }
10011
10012    /**
10013     * Returns whether the View is considered actionable from
10014     * accessibility perspective. Such view are important for
10015     * accessibility.
10016     *
10017     * @return True if the view is actionable for accessibility.
10018     *
10019     * @hide
10020     */
10021    public boolean isActionableForAccessibility() {
10022        return (isClickable() || isLongClickable() || isFocusable());
10023    }
10024
10025    /**
10026     * Returns whether the View has registered callbacks which makes it
10027     * important for accessibility.
10028     *
10029     * @return True if the view is actionable for accessibility.
10030     */
10031    private boolean hasListenersForAccessibility() {
10032        ListenerInfo info = getListenerInfo();
10033        return mTouchDelegate != null || info.mOnKeyListener != null
10034                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
10035                || info.mOnHoverListener != null || info.mOnDragListener != null;
10036    }
10037
10038    /**
10039     * Notifies that the accessibility state of this view changed. The change
10040     * is local to this view and does not represent structural changes such
10041     * as children and parent. For example, the view became focusable. The
10042     * notification is at at most once every
10043     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10044     * to avoid unnecessary load to the system. Also once a view has a pending
10045     * notification this method is a NOP until the notification has been sent.
10046     *
10047     * @hide
10048     */
10049    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
10050        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10051            return;
10052        }
10053        if (mSendViewStateChangedAccessibilityEvent == null) {
10054            mSendViewStateChangedAccessibilityEvent =
10055                    new SendViewStateChangedAccessibilityEvent();
10056        }
10057        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
10058    }
10059
10060    /**
10061     * Notifies that the accessibility state of this view changed. The change
10062     * is *not* local to this view and does represent structural changes such
10063     * as children and parent. For example, the view size changed. The
10064     * notification is at at most once every
10065     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10066     * to avoid unnecessary load to the system. Also once a view has a pending
10067     * notification this method is a NOP until the notification has been sent.
10068     *
10069     * @hide
10070     */
10071    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
10072        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10073            return;
10074        }
10075        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
10076            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10077            if (mParent != null) {
10078                try {
10079                    mParent.notifySubtreeAccessibilityStateChanged(
10080                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
10081                } catch (AbstractMethodError e) {
10082                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10083                            " does not fully implement ViewParent", e);
10084                }
10085            }
10086        }
10087    }
10088
10089    /**
10090     * Change the visibility of the View without triggering any other changes. This is
10091     * important for transitions, where visibility changes should not adjust focus or
10092     * trigger a new layout. This is only used when the visibility has already been changed
10093     * and we need a transient value during an animation. When the animation completes,
10094     * the original visibility value is always restored.
10095     *
10096     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
10097     * @hide
10098     */
10099    public void setTransitionVisibility(@Visibility int visibility) {
10100        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
10101    }
10102
10103    /**
10104     * Reset the flag indicating the accessibility state of the subtree rooted
10105     * at this view changed.
10106     */
10107    void resetSubtreeAccessibilityStateChanged() {
10108        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10109    }
10110
10111    /**
10112     * Report an accessibility action to this view's parents for delegated processing.
10113     *
10114     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
10115     * call this method to delegate an accessibility action to a supporting parent. If the parent
10116     * returns true from its
10117     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
10118     * method this method will return true to signify that the action was consumed.</p>
10119     *
10120     * <p>This method is useful for implementing nested scrolling child views. If
10121     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
10122     * a custom view implementation may invoke this method to allow a parent to consume the
10123     * scroll first. If this method returns true the custom view should skip its own scrolling
10124     * behavior.</p>
10125     *
10126     * @param action Accessibility action to delegate
10127     * @param arguments Optional action arguments
10128     * @return true if the action was consumed by a parent
10129     */
10130    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
10131        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
10132            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
10133                return true;
10134            }
10135        }
10136        return false;
10137    }
10138
10139    /**
10140     * Performs the specified accessibility action on the view. For
10141     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
10142     * <p>
10143     * If an {@link AccessibilityDelegate} has been specified via calling
10144     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
10145     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
10146     * is responsible for handling this call.
10147     * </p>
10148     *
10149     * <p>The default implementation will delegate
10150     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
10151     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
10152     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
10153     *
10154     * @param action The action to perform.
10155     * @param arguments Optional action arguments.
10156     * @return Whether the action was performed.
10157     */
10158    public boolean performAccessibilityAction(int action, Bundle arguments) {
10159      if (mAccessibilityDelegate != null) {
10160          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
10161      } else {
10162          return performAccessibilityActionInternal(action, arguments);
10163      }
10164    }
10165
10166   /**
10167    * @see #performAccessibilityAction(int, Bundle)
10168    *
10169    * Note: Called from the default {@link AccessibilityDelegate}.
10170    *
10171    * @hide
10172    */
10173    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
10174        if (isNestedScrollingEnabled()
10175                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
10176                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
10177                || action == R.id.accessibilityActionScrollUp
10178                || action == R.id.accessibilityActionScrollLeft
10179                || action == R.id.accessibilityActionScrollDown
10180                || action == R.id.accessibilityActionScrollRight)) {
10181            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
10182                return true;
10183            }
10184        }
10185
10186        switch (action) {
10187            case AccessibilityNodeInfo.ACTION_CLICK: {
10188                if (isClickable()) {
10189                    performClick();
10190                    return true;
10191                }
10192            } break;
10193            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
10194                if (isLongClickable()) {
10195                    performLongClick();
10196                    return true;
10197                }
10198            } break;
10199            case AccessibilityNodeInfo.ACTION_FOCUS: {
10200                if (!hasFocus()) {
10201                    // Get out of touch mode since accessibility
10202                    // wants to move focus around.
10203                    getViewRootImpl().ensureTouchMode(false);
10204                    return requestFocus();
10205                }
10206            } break;
10207            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
10208                if (hasFocus()) {
10209                    clearFocus();
10210                    return !isFocused();
10211                }
10212            } break;
10213            case AccessibilityNodeInfo.ACTION_SELECT: {
10214                if (!isSelected()) {
10215                    setSelected(true);
10216                    return isSelected();
10217                }
10218            } break;
10219            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
10220                if (isSelected()) {
10221                    setSelected(false);
10222                    return !isSelected();
10223                }
10224            } break;
10225            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
10226                if (!isAccessibilityFocused()) {
10227                    return requestAccessibilityFocus();
10228                }
10229            } break;
10230            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
10231                if (isAccessibilityFocused()) {
10232                    clearAccessibilityFocus();
10233                    return true;
10234                }
10235            } break;
10236            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
10237                if (arguments != null) {
10238                    final int granularity = arguments.getInt(
10239                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10240                    final boolean extendSelection = arguments.getBoolean(
10241                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10242                    return traverseAtGranularity(granularity, true, extendSelection);
10243                }
10244            } break;
10245            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
10246                if (arguments != null) {
10247                    final int granularity = arguments.getInt(
10248                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10249                    final boolean extendSelection = arguments.getBoolean(
10250                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10251                    return traverseAtGranularity(granularity, false, extendSelection);
10252                }
10253            } break;
10254            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
10255                CharSequence text = getIterableTextForAccessibility();
10256                if (text == null) {
10257                    return false;
10258                }
10259                final int start = (arguments != null) ? arguments.getInt(
10260                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
10261                final int end = (arguments != null) ? arguments.getInt(
10262                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
10263                // Only cursor position can be specified (selection length == 0)
10264                if ((getAccessibilitySelectionStart() != start
10265                        || getAccessibilitySelectionEnd() != end)
10266                        && (start == end)) {
10267                    setAccessibilitySelection(start, end);
10268                    notifyViewAccessibilityStateChangedIfNeeded(
10269                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10270                    return true;
10271                }
10272            } break;
10273            case R.id.accessibilityActionShowOnScreen: {
10274                if (mAttachInfo != null) {
10275                    final Rect r = mAttachInfo.mTmpInvalRect;
10276                    getDrawingRect(r);
10277                    return requestRectangleOnScreen(r, true);
10278                }
10279            } break;
10280            case R.id.accessibilityActionContextClick: {
10281                if (isContextClickable()) {
10282                    performContextClick();
10283                    return true;
10284                }
10285            } break;
10286        }
10287        return false;
10288    }
10289
10290    private boolean traverseAtGranularity(int granularity, boolean forward,
10291            boolean extendSelection) {
10292        CharSequence text = getIterableTextForAccessibility();
10293        if (text == null || text.length() == 0) {
10294            return false;
10295        }
10296        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
10297        if (iterator == null) {
10298            return false;
10299        }
10300        int current = getAccessibilitySelectionEnd();
10301        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10302            current = forward ? 0 : text.length();
10303        }
10304        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
10305        if (range == null) {
10306            return false;
10307        }
10308        final int segmentStart = range[0];
10309        final int segmentEnd = range[1];
10310        int selectionStart;
10311        int selectionEnd;
10312        if (extendSelection && isAccessibilitySelectionExtendable()) {
10313            selectionStart = getAccessibilitySelectionStart();
10314            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10315                selectionStart = forward ? segmentStart : segmentEnd;
10316            }
10317            selectionEnd = forward ? segmentEnd : segmentStart;
10318        } else {
10319            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
10320        }
10321        setAccessibilitySelection(selectionStart, selectionEnd);
10322        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
10323                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
10324        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
10325        return true;
10326    }
10327
10328    /**
10329     * Gets the text reported for accessibility purposes.
10330     *
10331     * @return The accessibility text.
10332     *
10333     * @hide
10334     */
10335    public CharSequence getIterableTextForAccessibility() {
10336        return getContentDescription();
10337    }
10338
10339    /**
10340     * Gets whether accessibility selection can be extended.
10341     *
10342     * @return If selection is extensible.
10343     *
10344     * @hide
10345     */
10346    public boolean isAccessibilitySelectionExtendable() {
10347        return false;
10348    }
10349
10350    /**
10351     * @hide
10352     */
10353    public int getAccessibilitySelectionStart() {
10354        return mAccessibilityCursorPosition;
10355    }
10356
10357    /**
10358     * @hide
10359     */
10360    public int getAccessibilitySelectionEnd() {
10361        return getAccessibilitySelectionStart();
10362    }
10363
10364    /**
10365     * @hide
10366     */
10367    public void setAccessibilitySelection(int start, int end) {
10368        if (start ==  end && end == mAccessibilityCursorPosition) {
10369            return;
10370        }
10371        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
10372            mAccessibilityCursorPosition = start;
10373        } else {
10374            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
10375        }
10376        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
10377    }
10378
10379    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
10380            int fromIndex, int toIndex) {
10381        if (mParent == null) {
10382            return;
10383        }
10384        AccessibilityEvent event = AccessibilityEvent.obtain(
10385                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
10386        onInitializeAccessibilityEvent(event);
10387        onPopulateAccessibilityEvent(event);
10388        event.setFromIndex(fromIndex);
10389        event.setToIndex(toIndex);
10390        event.setAction(action);
10391        event.setMovementGranularity(granularity);
10392        mParent.requestSendAccessibilityEvent(this, event);
10393    }
10394
10395    /**
10396     * @hide
10397     */
10398    public TextSegmentIterator getIteratorForGranularity(int granularity) {
10399        switch (granularity) {
10400            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
10401                CharSequence text = getIterableTextForAccessibility();
10402                if (text != null && text.length() > 0) {
10403                    CharacterTextSegmentIterator iterator =
10404                        CharacterTextSegmentIterator.getInstance(
10405                                mContext.getResources().getConfiguration().locale);
10406                    iterator.initialize(text.toString());
10407                    return iterator;
10408                }
10409            } break;
10410            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
10411                CharSequence text = getIterableTextForAccessibility();
10412                if (text != null && text.length() > 0) {
10413                    WordTextSegmentIterator iterator =
10414                        WordTextSegmentIterator.getInstance(
10415                                mContext.getResources().getConfiguration().locale);
10416                    iterator.initialize(text.toString());
10417                    return iterator;
10418                }
10419            } break;
10420            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
10421                CharSequence text = getIterableTextForAccessibility();
10422                if (text != null && text.length() > 0) {
10423                    ParagraphTextSegmentIterator iterator =
10424                        ParagraphTextSegmentIterator.getInstance();
10425                    iterator.initialize(text.toString());
10426                    return iterator;
10427                }
10428            } break;
10429        }
10430        return null;
10431    }
10432
10433    /**
10434     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
10435     * and {@link #onFinishTemporaryDetach()}.
10436     *
10437     * <p>This method always returns {@code true} when called directly or indirectly from
10438     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
10439     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
10440     * <ul>
10441     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
10442     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
10443     * </ul>
10444     * </p>
10445     *
10446     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
10447     * and {@link #onFinishTemporaryDetach()}.
10448     */
10449    public final boolean isTemporarilyDetached() {
10450        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
10451    }
10452
10453    /**
10454     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
10455     * a container View.
10456     */
10457    @CallSuper
10458    public void dispatchStartTemporaryDetach() {
10459        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
10460        onStartTemporaryDetach();
10461    }
10462
10463    /**
10464     * This is called when a container is going to temporarily detach a child, with
10465     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
10466     * It will either be followed by {@link #onFinishTemporaryDetach()} or
10467     * {@link #onDetachedFromWindow()} when the container is done.
10468     */
10469    public void onStartTemporaryDetach() {
10470        removeUnsetPressCallback();
10471        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
10472    }
10473
10474    /**
10475     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
10476     * a container View.
10477     */
10478    @CallSuper
10479    public void dispatchFinishTemporaryDetach() {
10480        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
10481        onFinishTemporaryDetach();
10482        if (hasWindowFocus() && hasFocus()) {
10483            InputMethodManager.getInstance().focusIn(this);
10484        }
10485    }
10486
10487    /**
10488     * Called after {@link #onStartTemporaryDetach} when the container is done
10489     * changing the view.
10490     */
10491    public void onFinishTemporaryDetach() {
10492    }
10493
10494    /**
10495     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
10496     * for this view's window.  Returns null if the view is not currently attached
10497     * to the window.  Normally you will not need to use this directly, but
10498     * just use the standard high-level event callbacks like
10499     * {@link #onKeyDown(int, KeyEvent)}.
10500     */
10501    public KeyEvent.DispatcherState getKeyDispatcherState() {
10502        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
10503    }
10504
10505    /**
10506     * Dispatch a key event before it is processed by any input method
10507     * associated with the view hierarchy.  This can be used to intercept
10508     * key events in special situations before the IME consumes them; a
10509     * typical example would be handling the BACK key to update the application's
10510     * UI instead of allowing the IME to see it and close itself.
10511     *
10512     * @param event The key event to be dispatched.
10513     * @return True if the event was handled, false otherwise.
10514     */
10515    public boolean dispatchKeyEventPreIme(KeyEvent event) {
10516        return onKeyPreIme(event.getKeyCode(), event);
10517    }
10518
10519    /**
10520     * Dispatch a key event to the next view on the focus path. This path runs
10521     * from the top of the view tree down to the currently focused view. If this
10522     * view has focus, it will dispatch to itself. Otherwise it will dispatch
10523     * the next node down the focus path. This method also fires any key
10524     * listeners.
10525     *
10526     * @param event The key event to be dispatched.
10527     * @return True if the event was handled, false otherwise.
10528     */
10529    public boolean dispatchKeyEvent(KeyEvent event) {
10530        if (mInputEventConsistencyVerifier != null) {
10531            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
10532        }
10533
10534        // Give any attached key listener a first crack at the event.
10535        //noinspection SimplifiableIfStatement
10536        ListenerInfo li = mListenerInfo;
10537        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10538                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
10539            return true;
10540        }
10541
10542        if (event.dispatch(this, mAttachInfo != null
10543                ? mAttachInfo.mKeyDispatchState : null, this)) {
10544            return true;
10545        }
10546
10547        if (mInputEventConsistencyVerifier != null) {
10548            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10549        }
10550        return false;
10551    }
10552
10553    /**
10554     * Dispatches a key shortcut event.
10555     *
10556     * @param event The key event to be dispatched.
10557     * @return True if the event was handled by the view, false otherwise.
10558     */
10559    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
10560        return onKeyShortcut(event.getKeyCode(), event);
10561    }
10562
10563    /**
10564     * Pass the touch screen motion event down to the target view, or this
10565     * view if it is the target.
10566     *
10567     * @param event The motion event to be dispatched.
10568     * @return True if the event was handled by the view, false otherwise.
10569     */
10570    public boolean dispatchTouchEvent(MotionEvent event) {
10571        // If the event should be handled by accessibility focus first.
10572        if (event.isTargetAccessibilityFocus()) {
10573            // We don't have focus or no virtual descendant has it, do not handle the event.
10574            if (!isAccessibilityFocusedViewOrHost()) {
10575                return false;
10576            }
10577            // We have focus and got the event, then use normal event dispatch.
10578            event.setTargetAccessibilityFocus(false);
10579        }
10580
10581        boolean result = false;
10582
10583        if (mInputEventConsistencyVerifier != null) {
10584            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
10585        }
10586
10587        final int actionMasked = event.getActionMasked();
10588        if (actionMasked == MotionEvent.ACTION_DOWN) {
10589            // Defensive cleanup for new gesture
10590            stopNestedScroll();
10591        }
10592
10593        if (onFilterTouchEventForSecurity(event)) {
10594            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
10595                result = true;
10596            }
10597            //noinspection SimplifiableIfStatement
10598            ListenerInfo li = mListenerInfo;
10599            if (li != null && li.mOnTouchListener != null
10600                    && (mViewFlags & ENABLED_MASK) == ENABLED
10601                    && li.mOnTouchListener.onTouch(this, event)) {
10602                result = true;
10603            }
10604
10605            if (!result && onTouchEvent(event)) {
10606                result = true;
10607            }
10608        }
10609
10610        if (!result && mInputEventConsistencyVerifier != null) {
10611            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10612        }
10613
10614        // Clean up after nested scrolls if this is the end of a gesture;
10615        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
10616        // of the gesture.
10617        if (actionMasked == MotionEvent.ACTION_UP ||
10618                actionMasked == MotionEvent.ACTION_CANCEL ||
10619                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
10620            stopNestedScroll();
10621        }
10622
10623        return result;
10624    }
10625
10626    boolean isAccessibilityFocusedViewOrHost() {
10627        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
10628                .getAccessibilityFocusedHost() == this);
10629    }
10630
10631    /**
10632     * Filter the touch event to apply security policies.
10633     *
10634     * @param event The motion event to be filtered.
10635     * @return True if the event should be dispatched, false if the event should be dropped.
10636     *
10637     * @see #getFilterTouchesWhenObscured
10638     */
10639    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
10640        //noinspection RedundantIfStatement
10641        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
10642                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
10643            // Window is obscured, drop this touch.
10644            return false;
10645        }
10646        return true;
10647    }
10648
10649    /**
10650     * Pass a trackball motion event down to the focused view.
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 dispatchTrackballEvent(MotionEvent event) {
10656        if (mInputEventConsistencyVerifier != null) {
10657            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
10658        }
10659
10660        return onTrackballEvent(event);
10661    }
10662
10663    /**
10664     * Pass a captured pointer event down to the focused view.
10665     *
10666     * @param event The motion event to be dispatched.
10667     * @return True if the event was handled by the view, false otherwise.
10668     */
10669    public boolean dispatchCapturedPointerEvent(MotionEvent event) {
10670        if (!hasPointerCapture()) {
10671            return false;
10672        }
10673        //noinspection SimplifiableIfStatement
10674        ListenerInfo li = mListenerInfo;
10675        if (li != null && li.mOnCapturedPointerListener != null
10676                && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) {
10677            return true;
10678        }
10679        return onCapturedPointerEvent(event);
10680    }
10681
10682    /**
10683     * Dispatch a generic motion event.
10684     * <p>
10685     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10686     * are delivered to the view under the pointer.  All other generic motion events are
10687     * delivered to the focused view.  Hover events are handled specially and are delivered
10688     * to {@link #onHoverEvent(MotionEvent)}.
10689     * </p>
10690     *
10691     * @param event The motion event to be dispatched.
10692     * @return True if the event was handled by the view, false otherwise.
10693     */
10694    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10695        if (mInputEventConsistencyVerifier != null) {
10696            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10697        }
10698
10699        final int source = event.getSource();
10700        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10701            final int action = event.getAction();
10702            if (action == MotionEvent.ACTION_HOVER_ENTER
10703                    || action == MotionEvent.ACTION_HOVER_MOVE
10704                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10705                if (dispatchHoverEvent(event)) {
10706                    return true;
10707                }
10708            } else if (dispatchGenericPointerEvent(event)) {
10709                return true;
10710            }
10711        } else if (dispatchGenericFocusedEvent(event)) {
10712            return true;
10713        }
10714
10715        if (dispatchGenericMotionEventInternal(event)) {
10716            return true;
10717        }
10718
10719        if (mInputEventConsistencyVerifier != null) {
10720            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10721        }
10722        return false;
10723    }
10724
10725    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10726        //noinspection SimplifiableIfStatement
10727        ListenerInfo li = mListenerInfo;
10728        if (li != null && li.mOnGenericMotionListener != null
10729                && (mViewFlags & ENABLED_MASK) == ENABLED
10730                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10731            return true;
10732        }
10733
10734        if (onGenericMotionEvent(event)) {
10735            return true;
10736        }
10737
10738        final int actionButton = event.getActionButton();
10739        switch (event.getActionMasked()) {
10740            case MotionEvent.ACTION_BUTTON_PRESS:
10741                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10742                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10743                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10744                    if (performContextClick(event.getX(), event.getY())) {
10745                        mInContextButtonPress = true;
10746                        setPressed(true, event.getX(), event.getY());
10747                        removeTapCallback();
10748                        removeLongPressCallback();
10749                        return true;
10750                    }
10751                }
10752                break;
10753
10754            case MotionEvent.ACTION_BUTTON_RELEASE:
10755                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10756                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10757                    mInContextButtonPress = false;
10758                    mIgnoreNextUpEvent = true;
10759                }
10760                break;
10761        }
10762
10763        if (mInputEventConsistencyVerifier != null) {
10764            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10765        }
10766        return false;
10767    }
10768
10769    /**
10770     * Dispatch a hover event.
10771     * <p>
10772     * Do not call this method directly.
10773     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10774     * </p>
10775     *
10776     * @param event The motion event to be dispatched.
10777     * @return True if the event was handled by the view, false otherwise.
10778     */
10779    protected boolean dispatchHoverEvent(MotionEvent event) {
10780        ListenerInfo li = mListenerInfo;
10781        //noinspection SimplifiableIfStatement
10782        if (li != null && li.mOnHoverListener != null
10783                && (mViewFlags & ENABLED_MASK) == ENABLED
10784                && li.mOnHoverListener.onHover(this, event)) {
10785            return true;
10786        }
10787
10788        return onHoverEvent(event);
10789    }
10790
10791    /**
10792     * Returns true if the view has a child to which it has recently sent
10793     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10794     * it does not have a hovered child, then it must be the innermost hovered view.
10795     * @hide
10796     */
10797    protected boolean hasHoveredChild() {
10798        return false;
10799    }
10800
10801    /**
10802     * Dispatch a generic motion event to the view under the first pointer.
10803     * <p>
10804     * Do not call this method directly.
10805     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10806     * </p>
10807     *
10808     * @param event The motion event to be dispatched.
10809     * @return True if the event was handled by the view, false otherwise.
10810     */
10811    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10812        return false;
10813    }
10814
10815    /**
10816     * Dispatch a generic motion event to the currently focused view.
10817     * <p>
10818     * Do not call this method directly.
10819     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10820     * </p>
10821     *
10822     * @param event The motion event to be dispatched.
10823     * @return True if the event was handled by the view, false otherwise.
10824     */
10825    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10826        return false;
10827    }
10828
10829    /**
10830     * Dispatch a pointer event.
10831     * <p>
10832     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10833     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10834     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10835     * and should not be expected to handle other pointing device features.
10836     * </p>
10837     *
10838     * @param event The motion event to be dispatched.
10839     * @return True if the event was handled by the view, false otherwise.
10840     * @hide
10841     */
10842    public final boolean dispatchPointerEvent(MotionEvent event) {
10843        if (event.isTouchEvent()) {
10844            return dispatchTouchEvent(event);
10845        } else {
10846            return dispatchGenericMotionEvent(event);
10847        }
10848    }
10849
10850    /**
10851     * Called when the window containing this view gains or loses window focus.
10852     * ViewGroups should override to route to their children.
10853     *
10854     * @param hasFocus True if the window containing this view now has focus,
10855     *        false otherwise.
10856     */
10857    public void dispatchWindowFocusChanged(boolean hasFocus) {
10858        onWindowFocusChanged(hasFocus);
10859    }
10860
10861    /**
10862     * Called when the window containing this view gains or loses focus.  Note
10863     * that this is separate from view focus: to receive key events, both
10864     * your view and its window must have focus.  If a window is displayed
10865     * on top of yours that takes input focus, then your own window will lose
10866     * focus but the view focus will remain unchanged.
10867     *
10868     * @param hasWindowFocus True if the window containing this view now has
10869     *        focus, false otherwise.
10870     */
10871    public void onWindowFocusChanged(boolean hasWindowFocus) {
10872        InputMethodManager imm = InputMethodManager.peekInstance();
10873        if (!hasWindowFocus) {
10874            if (isPressed()) {
10875                setPressed(false);
10876            }
10877            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
10878            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10879                imm.focusOut(this);
10880            }
10881            removeLongPressCallback();
10882            removeTapCallback();
10883            onFocusLost();
10884        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10885            imm.focusIn(this);
10886        }
10887        refreshDrawableState();
10888    }
10889
10890    /**
10891     * Returns true if this view is in a window that currently has window focus.
10892     * Note that this is not the same as the view itself having focus.
10893     *
10894     * @return True if this view is in a window that currently has window focus.
10895     */
10896    public boolean hasWindowFocus() {
10897        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10898    }
10899
10900    /**
10901     * Dispatch a view visibility change down the view hierarchy.
10902     * ViewGroups should override to route to their children.
10903     * @param changedView The view whose visibility changed. Could be 'this' or
10904     * an ancestor view.
10905     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10906     * {@link #INVISIBLE} or {@link #GONE}.
10907     */
10908    protected void dispatchVisibilityChanged(@NonNull View changedView,
10909            @Visibility int visibility) {
10910        onVisibilityChanged(changedView, visibility);
10911    }
10912
10913    /**
10914     * Called when the visibility of the view or an ancestor of the view has
10915     * changed.
10916     *
10917     * @param changedView The view whose visibility changed. May be
10918     *                    {@code this} or an ancestor view.
10919     * @param visibility The new visibility, one of {@link #VISIBLE},
10920     *                   {@link #INVISIBLE} or {@link #GONE}.
10921     */
10922    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10923    }
10924
10925    /**
10926     * Dispatch a hint about whether this view is displayed. For instance, when
10927     * a View moves out of the screen, it might receives a display hint indicating
10928     * the view is not displayed. Applications should not <em>rely</em> on this hint
10929     * as there is no guarantee that they will receive one.
10930     *
10931     * @param hint A hint about whether or not this view is displayed:
10932     * {@link #VISIBLE} or {@link #INVISIBLE}.
10933     */
10934    public void dispatchDisplayHint(@Visibility int hint) {
10935        onDisplayHint(hint);
10936    }
10937
10938    /**
10939     * Gives this view a hint about whether is displayed or not. For instance, when
10940     * a View moves out of the screen, it might receives a display hint indicating
10941     * the view is not displayed. Applications should not <em>rely</em> on this hint
10942     * as there is no guarantee that they will receive one.
10943     *
10944     * @param hint A hint about whether or not this view is displayed:
10945     * {@link #VISIBLE} or {@link #INVISIBLE}.
10946     */
10947    protected void onDisplayHint(@Visibility int hint) {
10948    }
10949
10950    /**
10951     * Dispatch a window visibility change down the view hierarchy.
10952     * ViewGroups should override to route to their children.
10953     *
10954     * @param visibility The new visibility of the window.
10955     *
10956     * @see #onWindowVisibilityChanged(int)
10957     */
10958    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10959        onWindowVisibilityChanged(visibility);
10960    }
10961
10962    /**
10963     * Called when the window containing has change its visibility
10964     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10965     * that this tells you whether or not your window is being made visible
10966     * to the window manager; this does <em>not</em> tell you whether or not
10967     * your window is obscured by other windows on the screen, even if it
10968     * is itself visible.
10969     *
10970     * @param visibility The new visibility of the window.
10971     */
10972    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10973        if (visibility == VISIBLE) {
10974            initialAwakenScrollBars();
10975        }
10976    }
10977
10978    /**
10979     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10980     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10981     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10982     *
10983     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10984     *                  ancestors or by window visibility
10985     * @return true if this view is visible to the user, not counting clipping or overlapping
10986     */
10987    boolean dispatchVisibilityAggregated(boolean isVisible) {
10988        final boolean thisVisible = getVisibility() == VISIBLE;
10989        // If we're not visible but something is telling us we are, ignore it.
10990        if (thisVisible || !isVisible) {
10991            onVisibilityAggregated(isVisible);
10992        }
10993        return thisVisible && isVisible;
10994    }
10995
10996    /**
10997     * Called when the user-visibility of this View is potentially affected by a change
10998     * to this view itself, an ancestor view or the window this view is attached to.
10999     *
11000     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
11001     *                  and this view's window is also visible
11002     */
11003    @CallSuper
11004    public void onVisibilityAggregated(boolean isVisible) {
11005        if (isVisible && mAttachInfo != null) {
11006            initialAwakenScrollBars();
11007        }
11008
11009        final Drawable dr = mBackground;
11010        if (dr != null && isVisible != dr.isVisible()) {
11011            dr.setVisible(isVisible, false);
11012        }
11013        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
11014        if (fg != null && isVisible != fg.isVisible()) {
11015            fg.setVisible(isVisible, false);
11016        }
11017    }
11018
11019    /**
11020     * Returns the current visibility of the window this view is attached to
11021     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
11022     *
11023     * @return Returns the current visibility of the view's window.
11024     */
11025    @Visibility
11026    public int getWindowVisibility() {
11027        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
11028    }
11029
11030    /**
11031     * Retrieve the overall visible display size in which the window this view is
11032     * attached to has been positioned in.  This takes into account screen
11033     * decorations above the window, for both cases where the window itself
11034     * is being position inside of them or the window is being placed under
11035     * then and covered insets are used for the window to position its content
11036     * inside.  In effect, this tells you the available area where content can
11037     * be placed and remain visible to users.
11038     *
11039     * <p>This function requires an IPC back to the window manager to retrieve
11040     * the requested information, so should not be used in performance critical
11041     * code like drawing.
11042     *
11043     * @param outRect Filled in with the visible display frame.  If the view
11044     * is not attached to a window, this is simply the raw display size.
11045     */
11046    public void getWindowVisibleDisplayFrame(Rect outRect) {
11047        if (mAttachInfo != null) {
11048            try {
11049                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11050            } catch (RemoteException e) {
11051                return;
11052            }
11053            // XXX This is really broken, and probably all needs to be done
11054            // in the window manager, and we need to know more about whether
11055            // we want the area behind or in front of the IME.
11056            final Rect insets = mAttachInfo.mVisibleInsets;
11057            outRect.left += insets.left;
11058            outRect.top += insets.top;
11059            outRect.right -= insets.right;
11060            outRect.bottom -= insets.bottom;
11061            return;
11062        }
11063        // The view is not attached to a display so we don't have a context.
11064        // Make a best guess about the display size.
11065        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11066        d.getRectSize(outRect);
11067    }
11068
11069    /**
11070     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
11071     * is currently in without any insets.
11072     *
11073     * @hide
11074     */
11075    public void getWindowDisplayFrame(Rect outRect) {
11076        if (mAttachInfo != null) {
11077            try {
11078                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11079            } catch (RemoteException e) {
11080                return;
11081            }
11082            return;
11083        }
11084        // The view is not attached to a display so we don't have a context.
11085        // Make a best guess about the display size.
11086        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11087        d.getRectSize(outRect);
11088    }
11089
11090    /**
11091     * Dispatch a notification about a resource configuration change down
11092     * the view hierarchy.
11093     * ViewGroups should override to route to their children.
11094     *
11095     * @param newConfig The new resource configuration.
11096     *
11097     * @see #onConfigurationChanged(android.content.res.Configuration)
11098     */
11099    public void dispatchConfigurationChanged(Configuration newConfig) {
11100        onConfigurationChanged(newConfig);
11101    }
11102
11103    /**
11104     * Called when the current configuration of the resources being used
11105     * by the application have changed.  You can use this to decide when
11106     * to reload resources that can changed based on orientation and other
11107     * configuration characteristics.  You only need to use this if you are
11108     * not relying on the normal {@link android.app.Activity} mechanism of
11109     * recreating the activity instance upon a configuration change.
11110     *
11111     * @param newConfig The new resource configuration.
11112     */
11113    protected void onConfigurationChanged(Configuration newConfig) {
11114    }
11115
11116    /**
11117     * Private function to aggregate all per-view attributes in to the view
11118     * root.
11119     */
11120    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11121        performCollectViewAttributes(attachInfo, visibility);
11122    }
11123
11124    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11125        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
11126            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
11127                attachInfo.mKeepScreenOn = true;
11128            }
11129            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
11130            ListenerInfo li = mListenerInfo;
11131            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
11132                attachInfo.mHasSystemUiListeners = true;
11133            }
11134        }
11135    }
11136
11137    void needGlobalAttributesUpdate(boolean force) {
11138        final AttachInfo ai = mAttachInfo;
11139        if (ai != null && !ai.mRecomputeGlobalAttributes) {
11140            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
11141                    || ai.mHasSystemUiListeners) {
11142                ai.mRecomputeGlobalAttributes = true;
11143            }
11144        }
11145    }
11146
11147    /**
11148     * Returns whether the device is currently in touch mode.  Touch mode is entered
11149     * once the user begins interacting with the device by touch, and affects various
11150     * things like whether focus is always visible to the user.
11151     *
11152     * @return Whether the device is in touch mode.
11153     */
11154    @ViewDebug.ExportedProperty
11155    public boolean isInTouchMode() {
11156        if (mAttachInfo != null) {
11157            return mAttachInfo.mInTouchMode;
11158        } else {
11159            return ViewRootImpl.isInTouchMode();
11160        }
11161    }
11162
11163    /**
11164     * Returns the context the view is running in, through which it can
11165     * access the current theme, resources, etc.
11166     *
11167     * @return The view's Context.
11168     */
11169    @ViewDebug.CapturedViewProperty
11170    public final Context getContext() {
11171        return mContext;
11172    }
11173
11174    /**
11175     * Handle a key event before it is processed by any input method
11176     * associated with the view hierarchy.  This can be used to intercept
11177     * key events in special situations before the IME consumes them; a
11178     * typical example would be handling the BACK key to update the application's
11179     * UI instead of allowing the IME to see it and close itself.
11180     *
11181     * @param keyCode The value in event.getKeyCode().
11182     * @param event Description of the key event.
11183     * @return If you handled the event, return true. If you want to allow the
11184     *         event to be handled by the next receiver, return false.
11185     */
11186    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
11187        return false;
11188    }
11189
11190    /**
11191     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
11192     * KeyEvent.Callback.onKeyDown()}: perform press of the view
11193     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
11194     * is released, if the view is enabled and clickable.
11195     * <p>
11196     * Key presses in software keyboards will generally NOT trigger this
11197     * listener, although some may elect to do so in some situations. Do not
11198     * rely on this to catch software key presses.
11199     *
11200     * @param keyCode a key code that represents the button pressed, from
11201     *                {@link android.view.KeyEvent}
11202     * @param event the KeyEvent object that defines the button action
11203     */
11204    public boolean onKeyDown(int keyCode, KeyEvent event) {
11205        if (KeyEvent.isConfirmKey(keyCode)) {
11206            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11207                return true;
11208            }
11209
11210            if (event.getRepeatCount() == 0) {
11211                // Long clickable items don't necessarily have to be clickable.
11212                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
11213                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
11214                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
11215                    // For the purposes of menu anchoring and drawable hotspots,
11216                    // key events are considered to be at the center of the view.
11217                    final float x = getWidth() / 2f;
11218                    final float y = getHeight() / 2f;
11219                    if (clickable) {
11220                        setPressed(true, x, y);
11221                    }
11222                    checkForLongClick(0, x, y);
11223                    return true;
11224                }
11225            }
11226        }
11227
11228        return false;
11229    }
11230
11231    /**
11232     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
11233     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
11234     * the event).
11235     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11236     * although some may elect to do so in some situations. Do not rely on this to
11237     * catch software key presses.
11238     */
11239    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
11240        return false;
11241    }
11242
11243    /**
11244     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
11245     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
11246     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
11247     * or {@link KeyEvent#KEYCODE_SPACE} is released.
11248     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11249     * although some may elect to do so in some situations. Do not rely on this to
11250     * catch software key presses.
11251     *
11252     * @param keyCode A key code that represents the button pressed, from
11253     *                {@link android.view.KeyEvent}.
11254     * @param event   The KeyEvent object that defines the button action.
11255     */
11256    public boolean onKeyUp(int keyCode, KeyEvent event) {
11257        if (KeyEvent.isConfirmKey(keyCode)) {
11258            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11259                return true;
11260            }
11261            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
11262                setPressed(false);
11263
11264                if (!mHasPerformedLongPress) {
11265                    // This is a tap, so remove the longpress check
11266                    removeLongPressCallback();
11267                    return performClick();
11268                }
11269            }
11270        }
11271        return false;
11272    }
11273
11274    /**
11275     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
11276     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
11277     * the event).
11278     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11279     * although some may elect to do so in some situations. Do not rely on this to
11280     * catch software key presses.
11281     *
11282     * @param keyCode     A key code that represents the button pressed, from
11283     *                    {@link android.view.KeyEvent}.
11284     * @param repeatCount The number of times the action was made.
11285     * @param event       The KeyEvent object that defines the button action.
11286     */
11287    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
11288        return false;
11289    }
11290
11291    /**
11292     * Called on the focused view when a key shortcut event is not handled.
11293     * Override this method to implement local key shortcuts for the View.
11294     * Key shortcuts can also be implemented by setting the
11295     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
11296     *
11297     * @param keyCode The value in event.getKeyCode().
11298     * @param event Description of the key event.
11299     * @return If you handled the event, return true. If you want to allow the
11300     *         event to be handled by the next receiver, return false.
11301     */
11302    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
11303        return false;
11304    }
11305
11306    /**
11307     * Check whether the called view is a text editor, in which case it
11308     * would make sense to automatically display a soft input window for
11309     * it.  Subclasses should override this if they implement
11310     * {@link #onCreateInputConnection(EditorInfo)} to return true if
11311     * a call on that method would return a non-null InputConnection, and
11312     * they are really a first-class editor that the user would normally
11313     * start typing on when the go into a window containing your view.
11314     *
11315     * <p>The default implementation always returns false.  This does
11316     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
11317     * will not be called or the user can not otherwise perform edits on your
11318     * view; it is just a hint to the system that this is not the primary
11319     * purpose of this view.
11320     *
11321     * @return Returns true if this view is a text editor, else false.
11322     */
11323    public boolean onCheckIsTextEditor() {
11324        return false;
11325    }
11326
11327    /**
11328     * Create a new InputConnection for an InputMethod to interact
11329     * with the view.  The default implementation returns null, since it doesn't
11330     * support input methods.  You can override this to implement such support.
11331     * This is only needed for views that take focus and text input.
11332     *
11333     * <p>When implementing this, you probably also want to implement
11334     * {@link #onCheckIsTextEditor()} to indicate you will return a
11335     * non-null InputConnection.</p>
11336     *
11337     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
11338     * object correctly and in its entirety, so that the connected IME can rely
11339     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
11340     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
11341     * must be filled in with the correct cursor position for IMEs to work correctly
11342     * with your application.</p>
11343     *
11344     * @param outAttrs Fill in with attribute information about the connection.
11345     */
11346    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
11347        return null;
11348    }
11349
11350    /**
11351     * Called by the {@link android.view.inputmethod.InputMethodManager}
11352     * when a view who is not the current
11353     * input connection target is trying to make a call on the manager.  The
11354     * default implementation returns false; you can override this to return
11355     * true for certain views if you are performing InputConnection proxying
11356     * to them.
11357     * @param view The View that is making the InputMethodManager call.
11358     * @return Return true to allow the call, false to reject.
11359     */
11360    public boolean checkInputConnectionProxy(View view) {
11361        return false;
11362    }
11363
11364    /**
11365     * Show the context menu for this view. It is not safe to hold on to the
11366     * menu after returning from this method.
11367     *
11368     * You should normally not overload this method. Overload
11369     * {@link #onCreateContextMenu(ContextMenu)} or define an
11370     * {@link OnCreateContextMenuListener} to add items to the context menu.
11371     *
11372     * @param menu The context menu to populate
11373     */
11374    public void createContextMenu(ContextMenu menu) {
11375        ContextMenuInfo menuInfo = getContextMenuInfo();
11376
11377        // Sets the current menu info so all items added to menu will have
11378        // my extra info set.
11379        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
11380
11381        onCreateContextMenu(menu);
11382        ListenerInfo li = mListenerInfo;
11383        if (li != null && li.mOnCreateContextMenuListener != null) {
11384            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
11385        }
11386
11387        // Clear the extra information so subsequent items that aren't mine don't
11388        // have my extra info.
11389        ((MenuBuilder)menu).setCurrentMenuInfo(null);
11390
11391        if (mParent != null) {
11392            mParent.createContextMenu(menu);
11393        }
11394    }
11395
11396    /**
11397     * Views should implement this if they have extra information to associate
11398     * with the context menu. The return result is supplied as a parameter to
11399     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
11400     * callback.
11401     *
11402     * @return Extra information about the item for which the context menu
11403     *         should be shown. This information will vary across different
11404     *         subclasses of View.
11405     */
11406    protected ContextMenuInfo getContextMenuInfo() {
11407        return null;
11408    }
11409
11410    /**
11411     * Views should implement this if the view itself is going to add items to
11412     * the context menu.
11413     *
11414     * @param menu the context menu to populate
11415     */
11416    protected void onCreateContextMenu(ContextMenu menu) {
11417    }
11418
11419    /**
11420     * Implement this method to handle trackball motion events.  The
11421     * <em>relative</em> movement of the trackball since the last event
11422     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
11423     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
11424     * that a movement of 1 corresponds to the user pressing one DPAD key (so
11425     * they will often be fractional values, representing the more fine-grained
11426     * movement information available from a trackball).
11427     *
11428     * @param event The motion event.
11429     * @return True if the event was handled, false otherwise.
11430     */
11431    public boolean onTrackballEvent(MotionEvent event) {
11432        return false;
11433    }
11434
11435    /**
11436     * Implement this method to handle generic motion events.
11437     * <p>
11438     * Generic motion events describe joystick movements, mouse hovers, track pad
11439     * touches, scroll wheel movements and other input events.  The
11440     * {@link MotionEvent#getSource() source} of the motion event specifies
11441     * the class of input that was received.  Implementations of this method
11442     * must examine the bits in the source before processing the event.
11443     * The following code example shows how this is done.
11444     * </p><p>
11445     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
11446     * are delivered to the view under the pointer.  All other generic motion events are
11447     * delivered to the focused view.
11448     * </p>
11449     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
11450     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
11451     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
11452     *             // process the joystick movement...
11453     *             return true;
11454     *         }
11455     *     }
11456     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
11457     *         switch (event.getAction()) {
11458     *             case MotionEvent.ACTION_HOVER_MOVE:
11459     *                 // process the mouse hover movement...
11460     *                 return true;
11461     *             case MotionEvent.ACTION_SCROLL:
11462     *                 // process the scroll wheel movement...
11463     *                 return true;
11464     *         }
11465     *     }
11466     *     return super.onGenericMotionEvent(event);
11467     * }</pre>
11468     *
11469     * @param event The generic motion event being processed.
11470     * @return True if the event was handled, false otherwise.
11471     */
11472    public boolean onGenericMotionEvent(MotionEvent event) {
11473        return false;
11474    }
11475
11476    /**
11477     * Implement this method to handle hover events.
11478     * <p>
11479     * This method is called whenever a pointer is hovering into, over, or out of the
11480     * bounds of a view and the view is not currently being touched.
11481     * Hover events are represented as pointer events with action
11482     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
11483     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
11484     * </p>
11485     * <ul>
11486     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
11487     * when the pointer enters the bounds of the view.</li>
11488     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
11489     * when the pointer has already entered the bounds of the view and has moved.</li>
11490     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
11491     * when the pointer has exited the bounds of the view or when the pointer is
11492     * about to go down due to a button click, tap, or similar user action that
11493     * causes the view to be touched.</li>
11494     * </ul>
11495     * <p>
11496     * The view should implement this method to return true to indicate that it is
11497     * handling the hover event, such as by changing its drawable state.
11498     * </p><p>
11499     * The default implementation calls {@link #setHovered} to update the hovered state
11500     * of the view when a hover enter or hover exit event is received, if the view
11501     * is enabled and is clickable.  The default implementation also sends hover
11502     * accessibility events.
11503     * </p>
11504     *
11505     * @param event The motion event that describes the hover.
11506     * @return True if the view handled the hover event.
11507     *
11508     * @see #isHovered
11509     * @see #setHovered
11510     * @see #onHoverChanged
11511     */
11512    public boolean onHoverEvent(MotionEvent event) {
11513        // The root view may receive hover (or touch) events that are outside the bounds of
11514        // the window.  This code ensures that we only send accessibility events for
11515        // hovers that are actually within the bounds of the root view.
11516        final int action = event.getActionMasked();
11517        if (!mSendingHoverAccessibilityEvents) {
11518            if ((action == MotionEvent.ACTION_HOVER_ENTER
11519                    || action == MotionEvent.ACTION_HOVER_MOVE)
11520                    && !hasHoveredChild()
11521                    && pointInView(event.getX(), event.getY())) {
11522                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
11523                mSendingHoverAccessibilityEvents = true;
11524            }
11525        } else {
11526            if (action == MotionEvent.ACTION_HOVER_EXIT
11527                    || (action == MotionEvent.ACTION_MOVE
11528                            && !pointInView(event.getX(), event.getY()))) {
11529                mSendingHoverAccessibilityEvents = false;
11530                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
11531            }
11532        }
11533
11534        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
11535                && event.isFromSource(InputDevice.SOURCE_MOUSE)
11536                && isOnScrollbar(event.getX(), event.getY())) {
11537            awakenScrollBars();
11538        }
11539        if (isHoverable()) {
11540            switch (action) {
11541                case MotionEvent.ACTION_HOVER_ENTER:
11542                    setHovered(true);
11543                    break;
11544                case MotionEvent.ACTION_HOVER_EXIT:
11545                    setHovered(false);
11546                    break;
11547            }
11548
11549            // Dispatch the event to onGenericMotionEvent before returning true.
11550            // This is to provide compatibility with existing applications that
11551            // handled HOVER_MOVE events in onGenericMotionEvent and that would
11552            // break because of the new default handling for hoverable views
11553            // in onHoverEvent.
11554            // Note that onGenericMotionEvent will be called by default when
11555            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
11556            dispatchGenericMotionEventInternal(event);
11557            // The event was already handled by calling setHovered(), so always
11558            // return true.
11559            return true;
11560        }
11561
11562        return false;
11563    }
11564
11565    /**
11566     * Returns true if the view should handle {@link #onHoverEvent}
11567     * by calling {@link #setHovered} to change its hovered state.
11568     *
11569     * @return True if the view is hoverable.
11570     */
11571    private boolean isHoverable() {
11572        final int viewFlags = mViewFlags;
11573        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11574            return false;
11575        }
11576
11577        return (viewFlags & CLICKABLE) == CLICKABLE
11578                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
11579                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11580    }
11581
11582    /**
11583     * Returns true if the view is currently hovered.
11584     *
11585     * @return True if the view is currently hovered.
11586     *
11587     * @see #setHovered
11588     * @see #onHoverChanged
11589     */
11590    @ViewDebug.ExportedProperty
11591    public boolean isHovered() {
11592        return (mPrivateFlags & PFLAG_HOVERED) != 0;
11593    }
11594
11595    /**
11596     * Sets whether the view is currently hovered.
11597     * <p>
11598     * Calling this method also changes the drawable state of the view.  This
11599     * enables the view to react to hover by using different drawable resources
11600     * to change its appearance.
11601     * </p><p>
11602     * The {@link #onHoverChanged} method is called when the hovered state changes.
11603     * </p>
11604     *
11605     * @param hovered True if the view is hovered.
11606     *
11607     * @see #isHovered
11608     * @see #onHoverChanged
11609     */
11610    public void setHovered(boolean hovered) {
11611        if (hovered) {
11612            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
11613                mPrivateFlags |= PFLAG_HOVERED;
11614                refreshDrawableState();
11615                onHoverChanged(true);
11616            }
11617        } else {
11618            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
11619                mPrivateFlags &= ~PFLAG_HOVERED;
11620                refreshDrawableState();
11621                onHoverChanged(false);
11622            }
11623        }
11624    }
11625
11626    /**
11627     * Implement this method to handle hover state changes.
11628     * <p>
11629     * This method is called whenever the hover state changes as a result of a
11630     * call to {@link #setHovered}.
11631     * </p>
11632     *
11633     * @param hovered The current hover state, as returned by {@link #isHovered}.
11634     *
11635     * @see #isHovered
11636     * @see #setHovered
11637     */
11638    public void onHoverChanged(boolean hovered) {
11639    }
11640
11641    /**
11642     * Handles scroll bar dragging by mouse input.
11643     *
11644     * @hide
11645     * @param event The motion event.
11646     *
11647     * @return true if the event was handled as a scroll bar dragging, false otherwise.
11648     */
11649    protected boolean handleScrollBarDragging(MotionEvent event) {
11650        if (mScrollCache == null) {
11651            return false;
11652        }
11653        final float x = event.getX();
11654        final float y = event.getY();
11655        final int action = event.getAction();
11656        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
11657                && action != MotionEvent.ACTION_DOWN)
11658                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
11659                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
11660            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11661            return false;
11662        }
11663
11664        switch (action) {
11665            case MotionEvent.ACTION_MOVE:
11666                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
11667                    return false;
11668                }
11669                if (mScrollCache.mScrollBarDraggingState
11670                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
11671                    final Rect bounds = mScrollCache.mScrollBarBounds;
11672                    getVerticalScrollBarBounds(bounds);
11673                    final int range = computeVerticalScrollRange();
11674                    final int offset = computeVerticalScrollOffset();
11675                    final int extent = computeVerticalScrollExtent();
11676
11677                    final int thumbLength = ScrollBarUtils.getThumbLength(
11678                            bounds.height(), bounds.width(), extent, range);
11679                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11680                            bounds.height(), thumbLength, extent, range, offset);
11681
11682                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
11683                    final float maxThumbOffset = bounds.height() - thumbLength;
11684                    final float newThumbOffset =
11685                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11686                    final int height = getHeight();
11687                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11688                            && height > 0 && extent > 0) {
11689                        final int newY = Math.round((range - extent)
11690                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11691                        if (newY != getScrollY()) {
11692                            mScrollCache.mScrollBarDraggingPos = y;
11693                            setScrollY(newY);
11694                        }
11695                    }
11696                    return true;
11697                }
11698                if (mScrollCache.mScrollBarDraggingState
11699                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11700                    final Rect bounds = mScrollCache.mScrollBarBounds;
11701                    getHorizontalScrollBarBounds(bounds);
11702                    final int range = computeHorizontalScrollRange();
11703                    final int offset = computeHorizontalScrollOffset();
11704                    final int extent = computeHorizontalScrollExtent();
11705
11706                    final int thumbLength = ScrollBarUtils.getThumbLength(
11707                            bounds.width(), bounds.height(), extent, range);
11708                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11709                            bounds.width(), thumbLength, extent, range, offset);
11710
11711                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11712                    final float maxThumbOffset = bounds.width() - thumbLength;
11713                    final float newThumbOffset =
11714                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11715                    final int width = getWidth();
11716                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11717                            && width > 0 && extent > 0) {
11718                        final int newX = Math.round((range - extent)
11719                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11720                        if (newX != getScrollX()) {
11721                            mScrollCache.mScrollBarDraggingPos = x;
11722                            setScrollX(newX);
11723                        }
11724                    }
11725                    return true;
11726                }
11727            case MotionEvent.ACTION_DOWN:
11728                if (mScrollCache.state == ScrollabilityCache.OFF) {
11729                    return false;
11730                }
11731                if (isOnVerticalScrollbarThumb(x, y)) {
11732                    mScrollCache.mScrollBarDraggingState =
11733                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11734                    mScrollCache.mScrollBarDraggingPos = y;
11735                    return true;
11736                }
11737                if (isOnHorizontalScrollbarThumb(x, y)) {
11738                    mScrollCache.mScrollBarDraggingState =
11739                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11740                    mScrollCache.mScrollBarDraggingPos = x;
11741                    return true;
11742                }
11743        }
11744        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11745        return false;
11746    }
11747
11748    /**
11749     * Implement this method to handle touch screen motion events.
11750     * <p>
11751     * If this method is used to detect click actions, it is recommended that
11752     * the actions be performed by implementing and calling
11753     * {@link #performClick()}. This will ensure consistent system behavior,
11754     * including:
11755     * <ul>
11756     * <li>obeying click sound preferences
11757     * <li>dispatching OnClickListener calls
11758     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11759     * accessibility features are enabled
11760     * </ul>
11761     *
11762     * @param event The motion event.
11763     * @return True if the event was handled, false otherwise.
11764     */
11765    public boolean onTouchEvent(MotionEvent event) {
11766        final float x = event.getX();
11767        final float y = event.getY();
11768        final int viewFlags = mViewFlags;
11769        final int action = event.getAction();
11770
11771        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
11772                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11773                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11774
11775        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11776            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11777                setPressed(false);
11778            }
11779            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11780            // A disabled view that is clickable still consumes the touch
11781            // events, it just doesn't respond to them.
11782            return clickable;
11783        }
11784        if (mTouchDelegate != null) {
11785            if (mTouchDelegate.onTouchEvent(event)) {
11786                return true;
11787            }
11788        }
11789
11790        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
11791            switch (action) {
11792                case MotionEvent.ACTION_UP:
11793                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11794                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
11795                        handleTooltipUp();
11796                    }
11797                    if (!clickable) {
11798                        removeTapCallback();
11799                        removeLongPressCallback();
11800                        mInContextButtonPress = false;
11801                        mHasPerformedLongPress = false;
11802                        mIgnoreNextUpEvent = false;
11803                        break;
11804                    }
11805                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11806                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11807                        // take focus if we don't have it already and we should in
11808                        // touch mode.
11809                        boolean focusTaken = false;
11810                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11811                            focusTaken = requestFocus();
11812                        }
11813
11814                        if (prepressed) {
11815                            // The button is being released before we actually
11816                            // showed it as pressed.  Make it show the pressed
11817                            // state now (before scheduling the click) to ensure
11818                            // the user sees it.
11819                            setPressed(true, x, y);
11820                        }
11821
11822                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11823                            // This is a tap, so remove the longpress check
11824                            removeLongPressCallback();
11825
11826                            // Only perform take click actions if we were in the pressed state
11827                            if (!focusTaken) {
11828                                // Use a Runnable and post this rather than calling
11829                                // performClick directly. This lets other visual state
11830                                // of the view update before click actions start.
11831                                if (mPerformClick == null) {
11832                                    mPerformClick = new PerformClick();
11833                                }
11834                                if (!post(mPerformClick)) {
11835                                    performClick();
11836                                }
11837                            }
11838                        }
11839
11840                        if (mUnsetPressedState == null) {
11841                            mUnsetPressedState = new UnsetPressedState();
11842                        }
11843
11844                        if (prepressed) {
11845                            postDelayed(mUnsetPressedState,
11846                                    ViewConfiguration.getPressedStateDuration());
11847                        } else if (!post(mUnsetPressedState)) {
11848                            // If the post failed, unpress right now
11849                            mUnsetPressedState.run();
11850                        }
11851
11852                        removeTapCallback();
11853                    }
11854                    mIgnoreNextUpEvent = false;
11855                    break;
11856
11857                case MotionEvent.ACTION_DOWN:
11858                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
11859                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
11860                    }
11861                    mHasPerformedLongPress = false;
11862
11863                    if (!clickable) {
11864                        checkForLongClick(0, x, y);
11865                        break;
11866                    }
11867
11868                    if (performButtonActionOnTouchDown(event)) {
11869                        break;
11870                    }
11871
11872                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11873                    boolean isInScrollingContainer = isInScrollingContainer();
11874
11875                    // For views inside a scrolling container, delay the pressed feedback for
11876                    // a short period in case this is a scroll.
11877                    if (isInScrollingContainer) {
11878                        mPrivateFlags |= PFLAG_PREPRESSED;
11879                        if (mPendingCheckForTap == null) {
11880                            mPendingCheckForTap = new CheckForTap();
11881                        }
11882                        mPendingCheckForTap.x = event.getX();
11883                        mPendingCheckForTap.y = event.getY();
11884                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11885                    } else {
11886                        // Not inside a scrolling container, so show the feedback right away
11887                        setPressed(true, x, y);
11888                        checkForLongClick(0, x, y);
11889                    }
11890                    break;
11891
11892                case MotionEvent.ACTION_CANCEL:
11893                    if (clickable) {
11894                        setPressed(false);
11895                    }
11896                    removeTapCallback();
11897                    removeLongPressCallback();
11898                    mInContextButtonPress = false;
11899                    mHasPerformedLongPress = false;
11900                    mIgnoreNextUpEvent = false;
11901                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11902                    break;
11903
11904                case MotionEvent.ACTION_MOVE:
11905                    if (clickable) {
11906                        drawableHotspotChanged(x, y);
11907                    }
11908
11909                    // Be lenient about moving outside of buttons
11910                    if (!pointInView(x, y, mTouchSlop)) {
11911                        // Outside button
11912                        // Remove any future long press/tap checks
11913                        removeTapCallback();
11914                        removeLongPressCallback();
11915                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11916                            setPressed(false);
11917                        }
11918                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11919                    }
11920                    break;
11921            }
11922
11923            return true;
11924        }
11925
11926        return false;
11927    }
11928
11929    /**
11930     * @hide
11931     */
11932    public boolean isInScrollingContainer() {
11933        ViewParent p = getParent();
11934        while (p != null && p instanceof ViewGroup) {
11935            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11936                return true;
11937            }
11938            p = p.getParent();
11939        }
11940        return false;
11941    }
11942
11943    /**
11944     * Remove the longpress detection timer.
11945     */
11946    private void removeLongPressCallback() {
11947        if (mPendingCheckForLongPress != null) {
11948            removeCallbacks(mPendingCheckForLongPress);
11949        }
11950    }
11951
11952    /**
11953     * Remove the pending click action
11954     */
11955    private void removePerformClickCallback() {
11956        if (mPerformClick != null) {
11957            removeCallbacks(mPerformClick);
11958        }
11959    }
11960
11961    /**
11962     * Remove the prepress detection timer.
11963     */
11964    private void removeUnsetPressCallback() {
11965        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11966            setPressed(false);
11967            removeCallbacks(mUnsetPressedState);
11968        }
11969    }
11970
11971    /**
11972     * Remove the tap detection timer.
11973     */
11974    private void removeTapCallback() {
11975        if (mPendingCheckForTap != null) {
11976            mPrivateFlags &= ~PFLAG_PREPRESSED;
11977            removeCallbacks(mPendingCheckForTap);
11978        }
11979    }
11980
11981    /**
11982     * Cancels a pending long press.  Your subclass can use this if you
11983     * want the context menu to come up if the user presses and holds
11984     * at the same place, but you don't want it to come up if they press
11985     * and then move around enough to cause scrolling.
11986     */
11987    public void cancelLongPress() {
11988        removeLongPressCallback();
11989
11990        /*
11991         * The prepressed state handled by the tap callback is a display
11992         * construct, but the tap callback will post a long press callback
11993         * less its own timeout. Remove it here.
11994         */
11995        removeTapCallback();
11996    }
11997
11998    /**
11999     * Remove the pending callback for sending a
12000     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
12001     */
12002    private void removeSendViewScrolledAccessibilityEventCallback() {
12003        if (mSendViewScrolledAccessibilityEvent != null) {
12004            removeCallbacks(mSendViewScrolledAccessibilityEvent);
12005            mSendViewScrolledAccessibilityEvent.mIsPending = false;
12006        }
12007    }
12008
12009    /**
12010     * Sets the TouchDelegate for this View.
12011     */
12012    public void setTouchDelegate(TouchDelegate delegate) {
12013        mTouchDelegate = delegate;
12014    }
12015
12016    /**
12017     * Gets the TouchDelegate for this View.
12018     */
12019    public TouchDelegate getTouchDelegate() {
12020        return mTouchDelegate;
12021    }
12022
12023    /**
12024     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
12025     *
12026     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
12027     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
12028     * available. This method should only be called for touch events.
12029     *
12030     * <p class="note">This api is not intended for most applications. Buffered dispatch
12031     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
12032     * streams will not improve your input latency. Side effects include: increased latency,
12033     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
12034     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
12035     * you.</p>
12036     */
12037    public final void requestUnbufferedDispatch(MotionEvent event) {
12038        final int action = event.getAction();
12039        if (mAttachInfo == null
12040                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
12041                || !event.isTouchEvent()) {
12042            return;
12043        }
12044        mAttachInfo.mUnbufferedDispatchRequested = true;
12045    }
12046
12047    /**
12048     * Set flags controlling behavior of this view.
12049     *
12050     * @param flags Constant indicating the value which should be set
12051     * @param mask Constant indicating the bit range that should be changed
12052     */
12053    void setFlags(int flags, int mask) {
12054        final boolean accessibilityEnabled =
12055                AccessibilityManager.getInstance(mContext).isEnabled();
12056        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
12057
12058        int old = mViewFlags;
12059        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
12060
12061        int changed = mViewFlags ^ old;
12062        if (changed == 0) {
12063            return;
12064        }
12065        int privateFlags = mPrivateFlags;
12066
12067        // If focusable is auto, update the FOCUSABLE bit.
12068        if (((mViewFlags & FOCUSABLE_AUTO) != 0)
12069                && (changed & (FOCUSABLE_MASK | CLICKABLE | FOCUSABLE_IN_TOUCH_MODE)) != 0) {
12070            int newFocus = NOT_FOCUSABLE;
12071            if ((mViewFlags & (CLICKABLE | FOCUSABLE_IN_TOUCH_MODE)) != 0) {
12072                newFocus = FOCUSABLE;
12073            } else {
12074                mViewFlags = (mViewFlags & ~FOCUSABLE_IN_TOUCH_MODE);
12075            }
12076            mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
12077            int focusChanged = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
12078            changed = (changed & ~FOCUSABLE) | focusChanged;
12079        }
12080
12081        /* Check if the FOCUSABLE bit has changed */
12082        if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
12083            if (((old & FOCUSABLE) == FOCUSABLE)
12084                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
12085                /* Give up focus if we are no longer focusable */
12086                clearFocus();
12087            } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
12088                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
12089                /*
12090                 * Tell the view system that we are now available to take focus
12091                 * if no one else already has it.
12092                 */
12093                if (mParent != null) mParent.focusableViewAvailable(this);
12094            }
12095        }
12096
12097        final int newVisibility = flags & VISIBILITY_MASK;
12098        if (newVisibility == VISIBLE) {
12099            if ((changed & VISIBILITY_MASK) != 0) {
12100                /*
12101                 * If this view is becoming visible, invalidate it in case it changed while
12102                 * it was not visible. Marking it drawn ensures that the invalidation will
12103                 * go through.
12104                 */
12105                mPrivateFlags |= PFLAG_DRAWN;
12106                invalidate(true);
12107
12108                needGlobalAttributesUpdate(true);
12109
12110                // a view becoming visible is worth notifying the parent
12111                // about in case nothing has focus.  even if this specific view
12112                // isn't focusable, it may contain something that is, so let
12113                // the root view try to give this focus if nothing else does.
12114                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
12115                    mParent.focusableViewAvailable(this);
12116                }
12117            }
12118        }
12119
12120        /* Check if the GONE bit has changed */
12121        if ((changed & GONE) != 0) {
12122            needGlobalAttributesUpdate(false);
12123            requestLayout();
12124
12125            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
12126                if (hasFocus()) clearFocus();
12127                clearAccessibilityFocus();
12128                destroyDrawingCache();
12129                if (mParent instanceof View) {
12130                    // GONE views noop invalidation, so invalidate the parent
12131                    ((View) mParent).invalidate(true);
12132                }
12133                // Mark the view drawn to ensure that it gets invalidated properly the next
12134                // time it is visible and gets invalidated
12135                mPrivateFlags |= PFLAG_DRAWN;
12136            }
12137            if (mAttachInfo != null) {
12138                mAttachInfo.mViewVisibilityChanged = true;
12139            }
12140        }
12141
12142        /* Check if the VISIBLE bit has changed */
12143        if ((changed & INVISIBLE) != 0) {
12144            needGlobalAttributesUpdate(false);
12145            /*
12146             * If this view is becoming invisible, set the DRAWN flag so that
12147             * the next invalidate() will not be skipped.
12148             */
12149            mPrivateFlags |= PFLAG_DRAWN;
12150
12151            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
12152                // root view becoming invisible shouldn't clear focus and accessibility focus
12153                if (getRootView() != this) {
12154                    if (hasFocus()) clearFocus();
12155                    clearAccessibilityFocus();
12156                }
12157            }
12158            if (mAttachInfo != null) {
12159                mAttachInfo.mViewVisibilityChanged = true;
12160            }
12161        }
12162
12163        if ((changed & VISIBILITY_MASK) != 0) {
12164            // If the view is invisible, cleanup its display list to free up resources
12165            if (newVisibility != VISIBLE && mAttachInfo != null) {
12166                cleanupDraw();
12167            }
12168
12169            if (mParent instanceof ViewGroup) {
12170                ((ViewGroup) mParent).onChildVisibilityChanged(this,
12171                        (changed & VISIBILITY_MASK), newVisibility);
12172                ((View) mParent).invalidate(true);
12173            } else if (mParent != null) {
12174                mParent.invalidateChild(this, null);
12175            }
12176
12177            if (mAttachInfo != null) {
12178                dispatchVisibilityChanged(this, newVisibility);
12179
12180                // Aggregated visibility changes are dispatched to attached views
12181                // in visible windows where the parent is currently shown/drawn
12182                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
12183                // discounting clipping or overlapping. This makes it a good place
12184                // to change animation states.
12185                if (mParent != null && getWindowVisibility() == VISIBLE &&
12186                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
12187                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
12188                }
12189                notifySubtreeAccessibilityStateChangedIfNeeded();
12190            }
12191        }
12192
12193        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
12194            destroyDrawingCache();
12195        }
12196
12197        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
12198            destroyDrawingCache();
12199            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12200            invalidateParentCaches();
12201        }
12202
12203        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
12204            destroyDrawingCache();
12205            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12206        }
12207
12208        if ((changed & DRAW_MASK) != 0) {
12209            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
12210                if (mBackground != null
12211                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
12212                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12213                } else {
12214                    mPrivateFlags |= PFLAG_SKIP_DRAW;
12215                }
12216            } else {
12217                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12218            }
12219            requestLayout();
12220            invalidate(true);
12221        }
12222
12223        if ((changed & KEEP_SCREEN_ON) != 0) {
12224            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12225                mParent.recomputeViewAttributes(this);
12226            }
12227        }
12228
12229        if (accessibilityEnabled) {
12230            if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
12231                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
12232                    || (changed & CONTEXT_CLICKABLE) != 0) {
12233                if (oldIncludeForAccessibility != includeForAccessibility()) {
12234                    notifySubtreeAccessibilityStateChangedIfNeeded();
12235                } else {
12236                    notifyViewAccessibilityStateChangedIfNeeded(
12237                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12238                }
12239            } else if ((changed & ENABLED_MASK) != 0) {
12240                notifyViewAccessibilityStateChangedIfNeeded(
12241                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12242            }
12243        }
12244    }
12245
12246    /**
12247     * Change the view's z order in the tree, so it's on top of other sibling
12248     * views. This ordering change may affect layout, if the parent container
12249     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
12250     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
12251     * method should be followed by calls to {@link #requestLayout()} and
12252     * {@link View#invalidate()} on the view's parent to force the parent to redraw
12253     * with the new child ordering.
12254     *
12255     * @see ViewGroup#bringChildToFront(View)
12256     */
12257    public void bringToFront() {
12258        if (mParent != null) {
12259            mParent.bringChildToFront(this);
12260        }
12261    }
12262
12263    /**
12264     * This is called in response to an internal scroll in this view (i.e., the
12265     * view scrolled its own contents). This is typically as a result of
12266     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
12267     * called.
12268     *
12269     * @param l Current horizontal scroll origin.
12270     * @param t Current vertical scroll origin.
12271     * @param oldl Previous horizontal scroll origin.
12272     * @param oldt Previous vertical scroll origin.
12273     */
12274    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
12275        notifySubtreeAccessibilityStateChangedIfNeeded();
12276
12277        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
12278            postSendViewScrolledAccessibilityEventCallback();
12279        }
12280
12281        mBackgroundSizeChanged = true;
12282        if (mForegroundInfo != null) {
12283            mForegroundInfo.mBoundsChanged = true;
12284        }
12285
12286        final AttachInfo ai = mAttachInfo;
12287        if (ai != null) {
12288            ai.mViewScrollChanged = true;
12289        }
12290
12291        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
12292            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
12293        }
12294    }
12295
12296    /**
12297     * Interface definition for a callback to be invoked when the scroll
12298     * X or Y positions of a view change.
12299     * <p>
12300     * <b>Note:</b> Some views handle scrolling independently from View and may
12301     * have their own separate listeners for scroll-type events. For example,
12302     * {@link android.widget.ListView ListView} allows clients to register an
12303     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
12304     * to listen for changes in list scroll position.
12305     *
12306     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
12307     */
12308    public interface OnScrollChangeListener {
12309        /**
12310         * Called when the scroll position of a view changes.
12311         *
12312         * @param v The view whose scroll position has changed.
12313         * @param scrollX Current horizontal scroll origin.
12314         * @param scrollY Current vertical scroll origin.
12315         * @param oldScrollX Previous horizontal scroll origin.
12316         * @param oldScrollY Previous vertical scroll origin.
12317         */
12318        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
12319    }
12320
12321    /**
12322     * Interface definition for a callback to be invoked when the layout bounds of a view
12323     * changes due to layout processing.
12324     */
12325    public interface OnLayoutChangeListener {
12326        /**
12327         * Called when the layout bounds of a view changes due to layout processing.
12328         *
12329         * @param v The view whose bounds have changed.
12330         * @param left The new value of the view's left property.
12331         * @param top The new value of the view's top property.
12332         * @param right The new value of the view's right property.
12333         * @param bottom The new value of the view's bottom property.
12334         * @param oldLeft The previous value of the view's left property.
12335         * @param oldTop The previous value of the view's top property.
12336         * @param oldRight The previous value of the view's right property.
12337         * @param oldBottom The previous value of the view's bottom property.
12338         */
12339        void onLayoutChange(View v, int left, int top, int right, int bottom,
12340            int oldLeft, int oldTop, int oldRight, int oldBottom);
12341    }
12342
12343    /**
12344     * This is called during layout when the size of this view has changed. If
12345     * you were just added to the view hierarchy, you're called with the old
12346     * values of 0.
12347     *
12348     * @param w Current width of this view.
12349     * @param h Current height of this view.
12350     * @param oldw Old width of this view.
12351     * @param oldh Old height of this view.
12352     */
12353    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
12354    }
12355
12356    /**
12357     * Called by draw to draw the child views. This may be overridden
12358     * by derived classes to gain control just before its children are drawn
12359     * (but after its own view has been drawn).
12360     * @param canvas the canvas on which to draw the view
12361     */
12362    protected void dispatchDraw(Canvas canvas) {
12363
12364    }
12365
12366    /**
12367     * Gets the parent of this view. Note that the parent is a
12368     * ViewParent and not necessarily a View.
12369     *
12370     * @return Parent of this view.
12371     */
12372    public final ViewParent getParent() {
12373        return mParent;
12374    }
12375
12376    /**
12377     * Set the horizontal scrolled position of your view. This will cause a call to
12378     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12379     * invalidated.
12380     * @param value the x position to scroll to
12381     */
12382    public void setScrollX(int value) {
12383        scrollTo(value, mScrollY);
12384    }
12385
12386    /**
12387     * Set the vertical scrolled position of your view. This will cause a call to
12388     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12389     * invalidated.
12390     * @param value the y position to scroll to
12391     */
12392    public void setScrollY(int value) {
12393        scrollTo(mScrollX, value);
12394    }
12395
12396    /**
12397     * Return the scrolled left position of this view. This is the left edge of
12398     * the displayed part of your view. You do not need to draw any pixels
12399     * farther left, since those are outside of the frame of your view on
12400     * screen.
12401     *
12402     * @return The left edge of the displayed part of your view, in pixels.
12403     */
12404    public final int getScrollX() {
12405        return mScrollX;
12406    }
12407
12408    /**
12409     * Return the scrolled top position of this view. This is the top edge of
12410     * the displayed part of your view. You do not need to draw any pixels above
12411     * it, since those are outside of the frame of your view on screen.
12412     *
12413     * @return The top edge of the displayed part of your view, in pixels.
12414     */
12415    public final int getScrollY() {
12416        return mScrollY;
12417    }
12418
12419    /**
12420     * Return the width of the your view.
12421     *
12422     * @return The width of your view, in pixels.
12423     */
12424    @ViewDebug.ExportedProperty(category = "layout")
12425    public final int getWidth() {
12426        return mRight - mLeft;
12427    }
12428
12429    /**
12430     * Return the height of your view.
12431     *
12432     * @return The height of your view, in pixels.
12433     */
12434    @ViewDebug.ExportedProperty(category = "layout")
12435    public final int getHeight() {
12436        return mBottom - mTop;
12437    }
12438
12439    /**
12440     * Return the visible drawing bounds of your view. Fills in the output
12441     * rectangle with the values from getScrollX(), getScrollY(),
12442     * getWidth(), and getHeight(). These bounds do not account for any
12443     * transformation properties currently set on the view, such as
12444     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
12445     *
12446     * @param outRect The (scrolled) drawing bounds of the view.
12447     */
12448    public void getDrawingRect(Rect outRect) {
12449        outRect.left = mScrollX;
12450        outRect.top = mScrollY;
12451        outRect.right = mScrollX + (mRight - mLeft);
12452        outRect.bottom = mScrollY + (mBottom - mTop);
12453    }
12454
12455    /**
12456     * Like {@link #getMeasuredWidthAndState()}, but only returns the
12457     * raw width component (that is the result is masked by
12458     * {@link #MEASURED_SIZE_MASK}).
12459     *
12460     * @return The raw measured width of this view.
12461     */
12462    public final int getMeasuredWidth() {
12463        return mMeasuredWidth & MEASURED_SIZE_MASK;
12464    }
12465
12466    /**
12467     * Return the full width measurement information for this view as computed
12468     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12469     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12470     * This should be used during measurement and layout calculations only. Use
12471     * {@link #getWidth()} to see how wide a view is after layout.
12472     *
12473     * @return The measured width of this view as a bit mask.
12474     */
12475    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12476            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12477                    name = "MEASURED_STATE_TOO_SMALL"),
12478    })
12479    public final int getMeasuredWidthAndState() {
12480        return mMeasuredWidth;
12481    }
12482
12483    /**
12484     * Like {@link #getMeasuredHeightAndState()}, but only returns the
12485     * raw height component (that is the result is masked by
12486     * {@link #MEASURED_SIZE_MASK}).
12487     *
12488     * @return The raw measured height of this view.
12489     */
12490    public final int getMeasuredHeight() {
12491        return mMeasuredHeight & MEASURED_SIZE_MASK;
12492    }
12493
12494    /**
12495     * Return the full height measurement information for this view as computed
12496     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12497     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12498     * This should be used during measurement and layout calculations only. Use
12499     * {@link #getHeight()} to see how wide a view is after layout.
12500     *
12501     * @return The measured height of this view as a bit mask.
12502     */
12503    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12504            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12505                    name = "MEASURED_STATE_TOO_SMALL"),
12506    })
12507    public final int getMeasuredHeightAndState() {
12508        return mMeasuredHeight;
12509    }
12510
12511    /**
12512     * Return only the state bits of {@link #getMeasuredWidthAndState()}
12513     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
12514     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
12515     * and the height component is at the shifted bits
12516     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
12517     */
12518    public final int getMeasuredState() {
12519        return (mMeasuredWidth&MEASURED_STATE_MASK)
12520                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
12521                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
12522    }
12523
12524    /**
12525     * The transform matrix of this view, which is calculated based on the current
12526     * rotation, scale, and pivot properties.
12527     *
12528     * @see #getRotation()
12529     * @see #getScaleX()
12530     * @see #getScaleY()
12531     * @see #getPivotX()
12532     * @see #getPivotY()
12533     * @return The current transform matrix for the view
12534     */
12535    public Matrix getMatrix() {
12536        ensureTransformationInfo();
12537        final Matrix matrix = mTransformationInfo.mMatrix;
12538        mRenderNode.getMatrix(matrix);
12539        return matrix;
12540    }
12541
12542    /**
12543     * Returns true if the transform matrix is the identity matrix.
12544     * Recomputes the matrix if necessary.
12545     *
12546     * @return True if the transform matrix is the identity matrix, false otherwise.
12547     */
12548    final boolean hasIdentityMatrix() {
12549        return mRenderNode.hasIdentityMatrix();
12550    }
12551
12552    void ensureTransformationInfo() {
12553        if (mTransformationInfo == null) {
12554            mTransformationInfo = new TransformationInfo();
12555        }
12556    }
12557
12558    /**
12559     * Utility method to retrieve the inverse of the current mMatrix property.
12560     * We cache the matrix to avoid recalculating it when transform properties
12561     * have not changed.
12562     *
12563     * @return The inverse of the current matrix of this view.
12564     * @hide
12565     */
12566    public final Matrix getInverseMatrix() {
12567        ensureTransformationInfo();
12568        if (mTransformationInfo.mInverseMatrix == null) {
12569            mTransformationInfo.mInverseMatrix = new Matrix();
12570        }
12571        final Matrix matrix = mTransformationInfo.mInverseMatrix;
12572        mRenderNode.getInverseMatrix(matrix);
12573        return matrix;
12574    }
12575
12576    /**
12577     * Gets the distance along the Z axis from the camera to this view.
12578     *
12579     * @see #setCameraDistance(float)
12580     *
12581     * @return The distance along the Z axis.
12582     */
12583    public float getCameraDistance() {
12584        final float dpi = mResources.getDisplayMetrics().densityDpi;
12585        return -(mRenderNode.getCameraDistance() * dpi);
12586    }
12587
12588    /**
12589     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
12590     * views are drawn) from the camera to this view. The camera's distance
12591     * affects 3D transformations, for instance rotations around the X and Y
12592     * axis. If the rotationX or rotationY properties are changed and this view is
12593     * large (more than half the size of the screen), it is recommended to always
12594     * use a camera distance that's greater than the height (X axis rotation) or
12595     * the width (Y axis rotation) of this view.</p>
12596     *
12597     * <p>The distance of the camera from the view plane can have an affect on the
12598     * perspective distortion of the view when it is rotated around the x or y axis.
12599     * For example, a large distance will result in a large viewing angle, and there
12600     * will not be much perspective distortion of the view as it rotates. A short
12601     * distance may cause much more perspective distortion upon rotation, and can
12602     * also result in some drawing artifacts if the rotated view ends up partially
12603     * behind the camera (which is why the recommendation is to use a distance at
12604     * least as far as the size of the view, if the view is to be rotated.)</p>
12605     *
12606     * <p>The distance is expressed in "depth pixels." The default distance depends
12607     * on the screen density. For instance, on a medium density display, the
12608     * default distance is 1280. On a high density display, the default distance
12609     * is 1920.</p>
12610     *
12611     * <p>If you want to specify a distance that leads to visually consistent
12612     * results across various densities, use the following formula:</p>
12613     * <pre>
12614     * float scale = context.getResources().getDisplayMetrics().density;
12615     * view.setCameraDistance(distance * scale);
12616     * </pre>
12617     *
12618     * <p>The density scale factor of a high density display is 1.5,
12619     * and 1920 = 1280 * 1.5.</p>
12620     *
12621     * @param distance The distance in "depth pixels", if negative the opposite
12622     *        value is used
12623     *
12624     * @see #setRotationX(float)
12625     * @see #setRotationY(float)
12626     */
12627    public void setCameraDistance(float distance) {
12628        final float dpi = mResources.getDisplayMetrics().densityDpi;
12629
12630        invalidateViewProperty(true, false);
12631        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
12632        invalidateViewProperty(false, false);
12633
12634        invalidateParentIfNeededAndWasQuickRejected();
12635    }
12636
12637    /**
12638     * The degrees that the view is rotated around the pivot point.
12639     *
12640     * @see #setRotation(float)
12641     * @see #getPivotX()
12642     * @see #getPivotY()
12643     *
12644     * @return The degrees of rotation.
12645     */
12646    @ViewDebug.ExportedProperty(category = "drawing")
12647    public float getRotation() {
12648        return mRenderNode.getRotation();
12649    }
12650
12651    /**
12652     * Sets the degrees that the view is rotated around the pivot point. Increasing values
12653     * result in clockwise rotation.
12654     *
12655     * @param rotation The degrees of rotation.
12656     *
12657     * @see #getRotation()
12658     * @see #getPivotX()
12659     * @see #getPivotY()
12660     * @see #setRotationX(float)
12661     * @see #setRotationY(float)
12662     *
12663     * @attr ref android.R.styleable#View_rotation
12664     */
12665    public void setRotation(float rotation) {
12666        if (rotation != getRotation()) {
12667            // Double-invalidation is necessary to capture view's old and new areas
12668            invalidateViewProperty(true, false);
12669            mRenderNode.setRotation(rotation);
12670            invalidateViewProperty(false, true);
12671
12672            invalidateParentIfNeededAndWasQuickRejected();
12673            notifySubtreeAccessibilityStateChangedIfNeeded();
12674        }
12675    }
12676
12677    /**
12678     * The degrees that the view is rotated around the vertical axis through the pivot point.
12679     *
12680     * @see #getPivotX()
12681     * @see #getPivotY()
12682     * @see #setRotationY(float)
12683     *
12684     * @return The degrees of Y rotation.
12685     */
12686    @ViewDebug.ExportedProperty(category = "drawing")
12687    public float getRotationY() {
12688        return mRenderNode.getRotationY();
12689    }
12690
12691    /**
12692     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
12693     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
12694     * down the y axis.
12695     *
12696     * When rotating large views, it is recommended to adjust the camera distance
12697     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12698     *
12699     * @param rotationY The degrees of Y rotation.
12700     *
12701     * @see #getRotationY()
12702     * @see #getPivotX()
12703     * @see #getPivotY()
12704     * @see #setRotation(float)
12705     * @see #setRotationX(float)
12706     * @see #setCameraDistance(float)
12707     *
12708     * @attr ref android.R.styleable#View_rotationY
12709     */
12710    public void setRotationY(float rotationY) {
12711        if (rotationY != getRotationY()) {
12712            invalidateViewProperty(true, false);
12713            mRenderNode.setRotationY(rotationY);
12714            invalidateViewProperty(false, true);
12715
12716            invalidateParentIfNeededAndWasQuickRejected();
12717            notifySubtreeAccessibilityStateChangedIfNeeded();
12718        }
12719    }
12720
12721    /**
12722     * The degrees that the view is rotated around the horizontal axis through the pivot point.
12723     *
12724     * @see #getPivotX()
12725     * @see #getPivotY()
12726     * @see #setRotationX(float)
12727     *
12728     * @return The degrees of X rotation.
12729     */
12730    @ViewDebug.ExportedProperty(category = "drawing")
12731    public float getRotationX() {
12732        return mRenderNode.getRotationX();
12733    }
12734
12735    /**
12736     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12737     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12738     * x axis.
12739     *
12740     * When rotating large views, it is recommended to adjust the camera distance
12741     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12742     *
12743     * @param rotationX The degrees of X rotation.
12744     *
12745     * @see #getRotationX()
12746     * @see #getPivotX()
12747     * @see #getPivotY()
12748     * @see #setRotation(float)
12749     * @see #setRotationY(float)
12750     * @see #setCameraDistance(float)
12751     *
12752     * @attr ref android.R.styleable#View_rotationX
12753     */
12754    public void setRotationX(float rotationX) {
12755        if (rotationX != getRotationX()) {
12756            invalidateViewProperty(true, false);
12757            mRenderNode.setRotationX(rotationX);
12758            invalidateViewProperty(false, true);
12759
12760            invalidateParentIfNeededAndWasQuickRejected();
12761            notifySubtreeAccessibilityStateChangedIfNeeded();
12762        }
12763    }
12764
12765    /**
12766     * The amount that the view is scaled in x around the pivot point, as a proportion of
12767     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12768     *
12769     * <p>By default, this is 1.0f.
12770     *
12771     * @see #getPivotX()
12772     * @see #getPivotY()
12773     * @return The scaling factor.
12774     */
12775    @ViewDebug.ExportedProperty(category = "drawing")
12776    public float getScaleX() {
12777        return mRenderNode.getScaleX();
12778    }
12779
12780    /**
12781     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12782     * the view's unscaled width. A value of 1 means that no scaling is applied.
12783     *
12784     * @param scaleX The scaling factor.
12785     * @see #getPivotX()
12786     * @see #getPivotY()
12787     *
12788     * @attr ref android.R.styleable#View_scaleX
12789     */
12790    public void setScaleX(float scaleX) {
12791        if (scaleX != getScaleX()) {
12792            invalidateViewProperty(true, false);
12793            mRenderNode.setScaleX(scaleX);
12794            invalidateViewProperty(false, true);
12795
12796            invalidateParentIfNeededAndWasQuickRejected();
12797            notifySubtreeAccessibilityStateChangedIfNeeded();
12798        }
12799    }
12800
12801    /**
12802     * The amount that the view is scaled in y around the pivot point, as a proportion of
12803     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12804     *
12805     * <p>By default, this is 1.0f.
12806     *
12807     * @see #getPivotX()
12808     * @see #getPivotY()
12809     * @return The scaling factor.
12810     */
12811    @ViewDebug.ExportedProperty(category = "drawing")
12812    public float getScaleY() {
12813        return mRenderNode.getScaleY();
12814    }
12815
12816    /**
12817     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12818     * the view's unscaled width. A value of 1 means that no scaling is applied.
12819     *
12820     * @param scaleY The scaling factor.
12821     * @see #getPivotX()
12822     * @see #getPivotY()
12823     *
12824     * @attr ref android.R.styleable#View_scaleY
12825     */
12826    public void setScaleY(float scaleY) {
12827        if (scaleY != getScaleY()) {
12828            invalidateViewProperty(true, false);
12829            mRenderNode.setScaleY(scaleY);
12830            invalidateViewProperty(false, true);
12831
12832            invalidateParentIfNeededAndWasQuickRejected();
12833            notifySubtreeAccessibilityStateChangedIfNeeded();
12834        }
12835    }
12836
12837    /**
12838     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12839     * and {@link #setScaleX(float) scaled}.
12840     *
12841     * @see #getRotation()
12842     * @see #getScaleX()
12843     * @see #getScaleY()
12844     * @see #getPivotY()
12845     * @return The x location of the pivot point.
12846     *
12847     * @attr ref android.R.styleable#View_transformPivotX
12848     */
12849    @ViewDebug.ExportedProperty(category = "drawing")
12850    public float getPivotX() {
12851        return mRenderNode.getPivotX();
12852    }
12853
12854    /**
12855     * Sets the x location of the point around which the view is
12856     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12857     * By default, the pivot point is centered on the object.
12858     * Setting this property disables this behavior and causes the view to use only the
12859     * explicitly set pivotX and pivotY values.
12860     *
12861     * @param pivotX The x location of the pivot point.
12862     * @see #getRotation()
12863     * @see #getScaleX()
12864     * @see #getScaleY()
12865     * @see #getPivotY()
12866     *
12867     * @attr ref android.R.styleable#View_transformPivotX
12868     */
12869    public void setPivotX(float pivotX) {
12870        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12871            invalidateViewProperty(true, false);
12872            mRenderNode.setPivotX(pivotX);
12873            invalidateViewProperty(false, true);
12874
12875            invalidateParentIfNeededAndWasQuickRejected();
12876        }
12877    }
12878
12879    /**
12880     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12881     * and {@link #setScaleY(float) scaled}.
12882     *
12883     * @see #getRotation()
12884     * @see #getScaleX()
12885     * @see #getScaleY()
12886     * @see #getPivotY()
12887     * @return The y location of the pivot point.
12888     *
12889     * @attr ref android.R.styleable#View_transformPivotY
12890     */
12891    @ViewDebug.ExportedProperty(category = "drawing")
12892    public float getPivotY() {
12893        return mRenderNode.getPivotY();
12894    }
12895
12896    /**
12897     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12898     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12899     * Setting this property disables this behavior and causes the view to use only the
12900     * explicitly set pivotX and pivotY values.
12901     *
12902     * @param pivotY The y location of the pivot point.
12903     * @see #getRotation()
12904     * @see #getScaleX()
12905     * @see #getScaleY()
12906     * @see #getPivotY()
12907     *
12908     * @attr ref android.R.styleable#View_transformPivotY
12909     */
12910    public void setPivotY(float pivotY) {
12911        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12912            invalidateViewProperty(true, false);
12913            mRenderNode.setPivotY(pivotY);
12914            invalidateViewProperty(false, true);
12915
12916            invalidateParentIfNeededAndWasQuickRejected();
12917        }
12918    }
12919
12920    /**
12921     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12922     * completely transparent and 1 means the view is completely opaque.
12923     *
12924     * <p>By default this is 1.0f.
12925     * @return The opacity of the view.
12926     */
12927    @ViewDebug.ExportedProperty(category = "drawing")
12928    public float getAlpha() {
12929        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12930    }
12931
12932    /**
12933     * Sets the behavior for overlapping rendering for this view (see {@link
12934     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12935     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12936     * providing the value which is then used internally. That is, when {@link
12937     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12938     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12939     * instead.
12940     *
12941     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12942     * instead of that returned by {@link #hasOverlappingRendering()}.
12943     *
12944     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12945     */
12946    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12947        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12948        if (hasOverlappingRendering) {
12949            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12950        } else {
12951            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12952        }
12953    }
12954
12955    /**
12956     * Returns the value for overlapping rendering that is used internally. This is either
12957     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12958     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12959     *
12960     * @return The value for overlapping rendering being used internally.
12961     */
12962    public final boolean getHasOverlappingRendering() {
12963        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12964                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12965                hasOverlappingRendering();
12966    }
12967
12968    /**
12969     * Returns whether this View has content which overlaps.
12970     *
12971     * <p>This function, intended to be overridden by specific View types, is an optimization when
12972     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12973     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12974     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12975     * directly. An example of overlapping rendering is a TextView with a background image, such as
12976     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12977     * ImageView with only the foreground image. The default implementation returns true; subclasses
12978     * should override if they have cases which can be optimized.</p>
12979     *
12980     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12981     * necessitates that a View return true if it uses the methods internally without passing the
12982     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12983     *
12984     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12985     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12986     *
12987     * @return true if the content in this view might overlap, false otherwise.
12988     */
12989    @ViewDebug.ExportedProperty(category = "drawing")
12990    public boolean hasOverlappingRendering() {
12991        return true;
12992    }
12993
12994    /**
12995     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12996     * completely transparent and 1 means the view is completely opaque.
12997     *
12998     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12999     * can have significant performance implications, especially for large views. It is best to use
13000     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
13001     *
13002     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
13003     * strongly recommended for performance reasons to either override
13004     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
13005     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
13006     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
13007     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
13008     * of rendering cost, even for simple or small views. Starting with
13009     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
13010     * applied to the view at the rendering level.</p>
13011     *
13012     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
13013     * responsible for applying the opacity itself.</p>
13014     *
13015     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
13016     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
13017     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
13018     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
13019     *
13020     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
13021     * value will clip a View to its bounds, unless the View returns <code>false</code> from
13022     * {@link #hasOverlappingRendering}.</p>
13023     *
13024     * @param alpha The opacity of the view.
13025     *
13026     * @see #hasOverlappingRendering()
13027     * @see #setLayerType(int, android.graphics.Paint)
13028     *
13029     * @attr ref android.R.styleable#View_alpha
13030     */
13031    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
13032        ensureTransformationInfo();
13033        if (mTransformationInfo.mAlpha != alpha) {
13034            // Report visibility changes, which can affect children, to accessibility
13035            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
13036                notifySubtreeAccessibilityStateChangedIfNeeded();
13037            }
13038            mTransformationInfo.mAlpha = alpha;
13039            if (onSetAlpha((int) (alpha * 255))) {
13040                mPrivateFlags |= PFLAG_ALPHA_SET;
13041                // subclass is handling alpha - don't optimize rendering cache invalidation
13042                invalidateParentCaches();
13043                invalidate(true);
13044            } else {
13045                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13046                invalidateViewProperty(true, false);
13047                mRenderNode.setAlpha(getFinalAlpha());
13048            }
13049        }
13050    }
13051
13052    /**
13053     * Faster version of setAlpha() which performs the same steps except there are
13054     * no calls to invalidate(). The caller of this function should perform proper invalidation
13055     * on the parent and this object. The return value indicates whether the subclass handles
13056     * alpha (the return value for onSetAlpha()).
13057     *
13058     * @param alpha The new value for the alpha property
13059     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
13060     *         the new value for the alpha property is different from the old value
13061     */
13062    boolean setAlphaNoInvalidation(float alpha) {
13063        ensureTransformationInfo();
13064        if (mTransformationInfo.mAlpha != alpha) {
13065            mTransformationInfo.mAlpha = alpha;
13066            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
13067            if (subclassHandlesAlpha) {
13068                mPrivateFlags |= PFLAG_ALPHA_SET;
13069                return true;
13070            } else {
13071                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13072                mRenderNode.setAlpha(getFinalAlpha());
13073            }
13074        }
13075        return false;
13076    }
13077
13078    /**
13079     * This property is hidden and intended only for use by the Fade transition, which
13080     * animates it to produce a visual translucency that does not side-effect (or get
13081     * affected by) the real alpha property. This value is composited with the other
13082     * alpha value (and the AlphaAnimation value, when that is present) to produce
13083     * a final visual translucency result, which is what is passed into the DisplayList.
13084     *
13085     * @hide
13086     */
13087    public void setTransitionAlpha(float alpha) {
13088        ensureTransformationInfo();
13089        if (mTransformationInfo.mTransitionAlpha != alpha) {
13090            mTransformationInfo.mTransitionAlpha = alpha;
13091            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13092            invalidateViewProperty(true, false);
13093            mRenderNode.setAlpha(getFinalAlpha());
13094        }
13095    }
13096
13097    /**
13098     * Calculates the visual alpha of this view, which is a combination of the actual
13099     * alpha value and the transitionAlpha value (if set).
13100     */
13101    private float getFinalAlpha() {
13102        if (mTransformationInfo != null) {
13103            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
13104        }
13105        return 1;
13106    }
13107
13108    /**
13109     * This property is hidden and intended only for use by the Fade transition, which
13110     * animates it to produce a visual translucency that does not side-effect (or get
13111     * affected by) the real alpha property. This value is composited with the other
13112     * alpha value (and the AlphaAnimation value, when that is present) to produce
13113     * a final visual translucency result, which is what is passed into the DisplayList.
13114     *
13115     * @hide
13116     */
13117    @ViewDebug.ExportedProperty(category = "drawing")
13118    public float getTransitionAlpha() {
13119        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
13120    }
13121
13122    /**
13123     * Top position of this view relative to its parent.
13124     *
13125     * @return The top of this view, in pixels.
13126     */
13127    @ViewDebug.CapturedViewProperty
13128    public final int getTop() {
13129        return mTop;
13130    }
13131
13132    /**
13133     * Sets the top position of this view relative to its parent. This method is meant to be called
13134     * by the layout system and should not generally be called otherwise, because the property
13135     * may be changed at any time by the layout.
13136     *
13137     * @param top The top of this view, in pixels.
13138     */
13139    public final void setTop(int top) {
13140        if (top != mTop) {
13141            final boolean matrixIsIdentity = hasIdentityMatrix();
13142            if (matrixIsIdentity) {
13143                if (mAttachInfo != null) {
13144                    int minTop;
13145                    int yLoc;
13146                    if (top < mTop) {
13147                        minTop = top;
13148                        yLoc = top - mTop;
13149                    } else {
13150                        minTop = mTop;
13151                        yLoc = 0;
13152                    }
13153                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
13154                }
13155            } else {
13156                // Double-invalidation is necessary to capture view's old and new areas
13157                invalidate(true);
13158            }
13159
13160            int width = mRight - mLeft;
13161            int oldHeight = mBottom - mTop;
13162
13163            mTop = top;
13164            mRenderNode.setTop(mTop);
13165
13166            sizeChange(width, mBottom - mTop, width, oldHeight);
13167
13168            if (!matrixIsIdentity) {
13169                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13170                invalidate(true);
13171            }
13172            mBackgroundSizeChanged = true;
13173            if (mForegroundInfo != null) {
13174                mForegroundInfo.mBoundsChanged = true;
13175            }
13176            invalidateParentIfNeeded();
13177            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13178                // View was rejected last time it was drawn by its parent; this may have changed
13179                invalidateParentIfNeeded();
13180            }
13181        }
13182    }
13183
13184    /**
13185     * Bottom position of this view relative to its parent.
13186     *
13187     * @return The bottom of this view, in pixels.
13188     */
13189    @ViewDebug.CapturedViewProperty
13190    public final int getBottom() {
13191        return mBottom;
13192    }
13193
13194    /**
13195     * True if this view has changed since the last time being drawn.
13196     *
13197     * @return The dirty state of this view.
13198     */
13199    public boolean isDirty() {
13200        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
13201    }
13202
13203    /**
13204     * Sets the bottom position of this view relative to its parent. This method is meant to be
13205     * called by the layout system and should not generally be called otherwise, because the
13206     * property may be changed at any time by the layout.
13207     *
13208     * @param bottom The bottom of this view, in pixels.
13209     */
13210    public final void setBottom(int bottom) {
13211        if (bottom != mBottom) {
13212            final boolean matrixIsIdentity = hasIdentityMatrix();
13213            if (matrixIsIdentity) {
13214                if (mAttachInfo != null) {
13215                    int maxBottom;
13216                    if (bottom < mBottom) {
13217                        maxBottom = mBottom;
13218                    } else {
13219                        maxBottom = bottom;
13220                    }
13221                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
13222                }
13223            } else {
13224                // Double-invalidation is necessary to capture view's old and new areas
13225                invalidate(true);
13226            }
13227
13228            int width = mRight - mLeft;
13229            int oldHeight = mBottom - mTop;
13230
13231            mBottom = bottom;
13232            mRenderNode.setBottom(mBottom);
13233
13234            sizeChange(width, mBottom - mTop, width, oldHeight);
13235
13236            if (!matrixIsIdentity) {
13237                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13238                invalidate(true);
13239            }
13240            mBackgroundSizeChanged = true;
13241            if (mForegroundInfo != null) {
13242                mForegroundInfo.mBoundsChanged = true;
13243            }
13244            invalidateParentIfNeeded();
13245            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13246                // View was rejected last time it was drawn by its parent; this may have changed
13247                invalidateParentIfNeeded();
13248            }
13249        }
13250    }
13251
13252    /**
13253     * Left position of this view relative to its parent.
13254     *
13255     * @return The left edge of this view, in pixels.
13256     */
13257    @ViewDebug.CapturedViewProperty
13258    public final int getLeft() {
13259        return mLeft;
13260    }
13261
13262    /**
13263     * Sets the left position of this view relative to its parent. This method is meant to be called
13264     * by the layout system and should not generally be called otherwise, because the property
13265     * may be changed at any time by the layout.
13266     *
13267     * @param left The left of this view, in pixels.
13268     */
13269    public final void setLeft(int left) {
13270        if (left != mLeft) {
13271            final boolean matrixIsIdentity = hasIdentityMatrix();
13272            if (matrixIsIdentity) {
13273                if (mAttachInfo != null) {
13274                    int minLeft;
13275                    int xLoc;
13276                    if (left < mLeft) {
13277                        minLeft = left;
13278                        xLoc = left - mLeft;
13279                    } else {
13280                        minLeft = mLeft;
13281                        xLoc = 0;
13282                    }
13283                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
13284                }
13285            } else {
13286                // Double-invalidation is necessary to capture view's old and new areas
13287                invalidate(true);
13288            }
13289
13290            int oldWidth = mRight - mLeft;
13291            int height = mBottom - mTop;
13292
13293            mLeft = left;
13294            mRenderNode.setLeft(left);
13295
13296            sizeChange(mRight - mLeft, height, oldWidth, height);
13297
13298            if (!matrixIsIdentity) {
13299                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13300                invalidate(true);
13301            }
13302            mBackgroundSizeChanged = true;
13303            if (mForegroundInfo != null) {
13304                mForegroundInfo.mBoundsChanged = true;
13305            }
13306            invalidateParentIfNeeded();
13307            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13308                // View was rejected last time it was drawn by its parent; this may have changed
13309                invalidateParentIfNeeded();
13310            }
13311        }
13312    }
13313
13314    /**
13315     * Right position of this view relative to its parent.
13316     *
13317     * @return The right edge of this view, in pixels.
13318     */
13319    @ViewDebug.CapturedViewProperty
13320    public final int getRight() {
13321        return mRight;
13322    }
13323
13324    /**
13325     * Sets the right position of this view relative to its parent. This method is meant to be called
13326     * by the layout system and should not generally be called otherwise, because the property
13327     * may be changed at any time by the layout.
13328     *
13329     * @param right The right of this view, in pixels.
13330     */
13331    public final void setRight(int right) {
13332        if (right != mRight) {
13333            final boolean matrixIsIdentity = hasIdentityMatrix();
13334            if (matrixIsIdentity) {
13335                if (mAttachInfo != null) {
13336                    int maxRight;
13337                    if (right < mRight) {
13338                        maxRight = mRight;
13339                    } else {
13340                        maxRight = right;
13341                    }
13342                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
13343                }
13344            } else {
13345                // Double-invalidation is necessary to capture view's old and new areas
13346                invalidate(true);
13347            }
13348
13349            int oldWidth = mRight - mLeft;
13350            int height = mBottom - mTop;
13351
13352            mRight = right;
13353            mRenderNode.setRight(mRight);
13354
13355            sizeChange(mRight - mLeft, height, oldWidth, height);
13356
13357            if (!matrixIsIdentity) {
13358                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13359                invalidate(true);
13360            }
13361            mBackgroundSizeChanged = true;
13362            if (mForegroundInfo != null) {
13363                mForegroundInfo.mBoundsChanged = true;
13364            }
13365            invalidateParentIfNeeded();
13366            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13367                // View was rejected last time it was drawn by its parent; this may have changed
13368                invalidateParentIfNeeded();
13369            }
13370        }
13371    }
13372
13373    /**
13374     * The visual x position of this view, in pixels. This is equivalent to the
13375     * {@link #setTranslationX(float) translationX} property plus the current
13376     * {@link #getLeft() left} property.
13377     *
13378     * @return The visual x position of this view, in pixels.
13379     */
13380    @ViewDebug.ExportedProperty(category = "drawing")
13381    public float getX() {
13382        return mLeft + getTranslationX();
13383    }
13384
13385    /**
13386     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
13387     * {@link #setTranslationX(float) translationX} property to be the difference between
13388     * the x value passed in and the current {@link #getLeft() left} property.
13389     *
13390     * @param x The visual x position of this view, in pixels.
13391     */
13392    public void setX(float x) {
13393        setTranslationX(x - mLeft);
13394    }
13395
13396    /**
13397     * The visual y position of this view, in pixels. This is equivalent to the
13398     * {@link #setTranslationY(float) translationY} property plus the current
13399     * {@link #getTop() top} property.
13400     *
13401     * @return The visual y position of this view, in pixels.
13402     */
13403    @ViewDebug.ExportedProperty(category = "drawing")
13404    public float getY() {
13405        return mTop + getTranslationY();
13406    }
13407
13408    /**
13409     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
13410     * {@link #setTranslationY(float) translationY} property to be the difference between
13411     * the y value passed in and the current {@link #getTop() top} property.
13412     *
13413     * @param y The visual y position of this view, in pixels.
13414     */
13415    public void setY(float y) {
13416        setTranslationY(y - mTop);
13417    }
13418
13419    /**
13420     * The visual z position of this view, in pixels. This is equivalent to the
13421     * {@link #setTranslationZ(float) translationZ} property plus the current
13422     * {@link #getElevation() elevation} property.
13423     *
13424     * @return The visual z position of this view, in pixels.
13425     */
13426    @ViewDebug.ExportedProperty(category = "drawing")
13427    public float getZ() {
13428        return getElevation() + getTranslationZ();
13429    }
13430
13431    /**
13432     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
13433     * {@link #setTranslationZ(float) translationZ} property to be the difference between
13434     * the x value passed in and the current {@link #getElevation() elevation} property.
13435     *
13436     * @param z The visual z position of this view, in pixels.
13437     */
13438    public void setZ(float z) {
13439        setTranslationZ(z - getElevation());
13440    }
13441
13442    /**
13443     * The base elevation of this view relative to its parent, in pixels.
13444     *
13445     * @return The base depth position of the view, in pixels.
13446     */
13447    @ViewDebug.ExportedProperty(category = "drawing")
13448    public float getElevation() {
13449        return mRenderNode.getElevation();
13450    }
13451
13452    /**
13453     * Sets the base elevation of this view, in pixels.
13454     *
13455     * @attr ref android.R.styleable#View_elevation
13456     */
13457    public void setElevation(float elevation) {
13458        if (elevation != getElevation()) {
13459            invalidateViewProperty(true, false);
13460            mRenderNode.setElevation(elevation);
13461            invalidateViewProperty(false, true);
13462
13463            invalidateParentIfNeededAndWasQuickRejected();
13464        }
13465    }
13466
13467    /**
13468     * The horizontal location of this view relative to its {@link #getLeft() left} position.
13469     * This position is post-layout, in addition to wherever the object's
13470     * layout placed it.
13471     *
13472     * @return The horizontal position of this view relative to its left position, in pixels.
13473     */
13474    @ViewDebug.ExportedProperty(category = "drawing")
13475    public float getTranslationX() {
13476        return mRenderNode.getTranslationX();
13477    }
13478
13479    /**
13480     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
13481     * This effectively positions the object post-layout, in addition to wherever the object's
13482     * layout placed it.
13483     *
13484     * @param translationX The horizontal position of this view relative to its left position,
13485     * in pixels.
13486     *
13487     * @attr ref android.R.styleable#View_translationX
13488     */
13489    public void setTranslationX(float translationX) {
13490        if (translationX != getTranslationX()) {
13491            invalidateViewProperty(true, false);
13492            mRenderNode.setTranslationX(translationX);
13493            invalidateViewProperty(false, true);
13494
13495            invalidateParentIfNeededAndWasQuickRejected();
13496            notifySubtreeAccessibilityStateChangedIfNeeded();
13497        }
13498    }
13499
13500    /**
13501     * The vertical location of this view relative to its {@link #getTop() top} position.
13502     * This position is post-layout, in addition to wherever the object's
13503     * layout placed it.
13504     *
13505     * @return The vertical position of this view relative to its top position,
13506     * in pixels.
13507     */
13508    @ViewDebug.ExportedProperty(category = "drawing")
13509    public float getTranslationY() {
13510        return mRenderNode.getTranslationY();
13511    }
13512
13513    /**
13514     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
13515     * This effectively positions the object post-layout, in addition to wherever the object's
13516     * layout placed it.
13517     *
13518     * @param translationY The vertical position of this view relative to its top position,
13519     * in pixels.
13520     *
13521     * @attr ref android.R.styleable#View_translationY
13522     */
13523    public void setTranslationY(float translationY) {
13524        if (translationY != getTranslationY()) {
13525            invalidateViewProperty(true, false);
13526            mRenderNode.setTranslationY(translationY);
13527            invalidateViewProperty(false, true);
13528
13529            invalidateParentIfNeededAndWasQuickRejected();
13530            notifySubtreeAccessibilityStateChangedIfNeeded();
13531        }
13532    }
13533
13534    /**
13535     * The depth location of this view relative to its {@link #getElevation() elevation}.
13536     *
13537     * @return The depth of this view relative to its elevation.
13538     */
13539    @ViewDebug.ExportedProperty(category = "drawing")
13540    public float getTranslationZ() {
13541        return mRenderNode.getTranslationZ();
13542    }
13543
13544    /**
13545     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
13546     *
13547     * @attr ref android.R.styleable#View_translationZ
13548     */
13549    public void setTranslationZ(float translationZ) {
13550        if (translationZ != getTranslationZ()) {
13551            invalidateViewProperty(true, false);
13552            mRenderNode.setTranslationZ(translationZ);
13553            invalidateViewProperty(false, true);
13554
13555            invalidateParentIfNeededAndWasQuickRejected();
13556        }
13557    }
13558
13559    /** @hide */
13560    public void setAnimationMatrix(Matrix matrix) {
13561        invalidateViewProperty(true, false);
13562        mRenderNode.setAnimationMatrix(matrix);
13563        invalidateViewProperty(false, true);
13564
13565        invalidateParentIfNeededAndWasQuickRejected();
13566    }
13567
13568    /**
13569     * Returns the current StateListAnimator if exists.
13570     *
13571     * @return StateListAnimator or null if it does not exists
13572     * @see    #setStateListAnimator(android.animation.StateListAnimator)
13573     */
13574    public StateListAnimator getStateListAnimator() {
13575        return mStateListAnimator;
13576    }
13577
13578    /**
13579     * Attaches the provided StateListAnimator to this View.
13580     * <p>
13581     * Any previously attached StateListAnimator will be detached.
13582     *
13583     * @param stateListAnimator The StateListAnimator to update the view
13584     * @see android.animation.StateListAnimator
13585     */
13586    public void setStateListAnimator(StateListAnimator stateListAnimator) {
13587        if (mStateListAnimator == stateListAnimator) {
13588            return;
13589        }
13590        if (mStateListAnimator != null) {
13591            mStateListAnimator.setTarget(null);
13592        }
13593        mStateListAnimator = stateListAnimator;
13594        if (stateListAnimator != null) {
13595            stateListAnimator.setTarget(this);
13596            if (isAttachedToWindow()) {
13597                stateListAnimator.setState(getDrawableState());
13598            }
13599        }
13600    }
13601
13602    /**
13603     * Returns whether the Outline should be used to clip the contents of the View.
13604     * <p>
13605     * Note that this flag will only be respected if the View's Outline returns true from
13606     * {@link Outline#canClip()}.
13607     *
13608     * @see #setOutlineProvider(ViewOutlineProvider)
13609     * @see #setClipToOutline(boolean)
13610     */
13611    public final boolean getClipToOutline() {
13612        return mRenderNode.getClipToOutline();
13613    }
13614
13615    /**
13616     * Sets whether the View's Outline should be used to clip the contents of the View.
13617     * <p>
13618     * Only a single non-rectangular clip can be applied on a View at any time.
13619     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
13620     * circular reveal} animation take priority over Outline clipping, and
13621     * child Outline clipping takes priority over Outline clipping done by a
13622     * parent.
13623     * <p>
13624     * Note that this flag will only be respected if the View's Outline returns true from
13625     * {@link Outline#canClip()}.
13626     *
13627     * @see #setOutlineProvider(ViewOutlineProvider)
13628     * @see #getClipToOutline()
13629     */
13630    public void setClipToOutline(boolean clipToOutline) {
13631        damageInParent();
13632        if (getClipToOutline() != clipToOutline) {
13633            mRenderNode.setClipToOutline(clipToOutline);
13634        }
13635    }
13636
13637    // correspond to the enum values of View_outlineProvider
13638    private static final int PROVIDER_BACKGROUND = 0;
13639    private static final int PROVIDER_NONE = 1;
13640    private static final int PROVIDER_BOUNDS = 2;
13641    private static final int PROVIDER_PADDED_BOUNDS = 3;
13642    private void setOutlineProviderFromAttribute(int providerInt) {
13643        switch (providerInt) {
13644            case PROVIDER_BACKGROUND:
13645                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
13646                break;
13647            case PROVIDER_NONE:
13648                setOutlineProvider(null);
13649                break;
13650            case PROVIDER_BOUNDS:
13651                setOutlineProvider(ViewOutlineProvider.BOUNDS);
13652                break;
13653            case PROVIDER_PADDED_BOUNDS:
13654                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
13655                break;
13656        }
13657    }
13658
13659    /**
13660     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
13661     * the shape of the shadow it casts, and enables outline clipping.
13662     * <p>
13663     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
13664     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
13665     * outline provider with this method allows this behavior to be overridden.
13666     * <p>
13667     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
13668     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
13669     * <p>
13670     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
13671     *
13672     * @see #setClipToOutline(boolean)
13673     * @see #getClipToOutline()
13674     * @see #getOutlineProvider()
13675     */
13676    public void setOutlineProvider(ViewOutlineProvider provider) {
13677        mOutlineProvider = provider;
13678        invalidateOutline();
13679    }
13680
13681    /**
13682     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
13683     * that defines the shape of the shadow it casts, and enables outline clipping.
13684     *
13685     * @see #setOutlineProvider(ViewOutlineProvider)
13686     */
13687    public ViewOutlineProvider getOutlineProvider() {
13688        return mOutlineProvider;
13689    }
13690
13691    /**
13692     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
13693     *
13694     * @see #setOutlineProvider(ViewOutlineProvider)
13695     */
13696    public void invalidateOutline() {
13697        rebuildOutline();
13698
13699        notifySubtreeAccessibilityStateChangedIfNeeded();
13700        invalidateViewProperty(false, false);
13701    }
13702
13703    /**
13704     * Internal version of {@link #invalidateOutline()} which invalidates the
13705     * outline without invalidating the view itself. This is intended to be called from
13706     * within methods in the View class itself which are the result of the view being
13707     * invalidated already. For example, when we are drawing the background of a View,
13708     * we invalidate the outline in case it changed in the meantime, but we do not
13709     * need to invalidate the view because we're already drawing the background as part
13710     * of drawing the view in response to an earlier invalidation of the view.
13711     */
13712    private void rebuildOutline() {
13713        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
13714        if (mAttachInfo == null) return;
13715
13716        if (mOutlineProvider == null) {
13717            // no provider, remove outline
13718            mRenderNode.setOutline(null);
13719        } else {
13720            final Outline outline = mAttachInfo.mTmpOutline;
13721            outline.setEmpty();
13722            outline.setAlpha(1.0f);
13723
13724            mOutlineProvider.getOutline(this, outline);
13725            mRenderNode.setOutline(outline);
13726        }
13727    }
13728
13729    /**
13730     * HierarchyViewer only
13731     *
13732     * @hide
13733     */
13734    @ViewDebug.ExportedProperty(category = "drawing")
13735    public boolean hasShadow() {
13736        return mRenderNode.hasShadow();
13737    }
13738
13739
13740    /** @hide */
13741    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13742        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13743        invalidateViewProperty(false, false);
13744    }
13745
13746    /**
13747     * Hit rectangle in parent's coordinates
13748     *
13749     * @param outRect The hit rectangle of the view.
13750     */
13751    public void getHitRect(Rect outRect) {
13752        if (hasIdentityMatrix() || mAttachInfo == null) {
13753            outRect.set(mLeft, mTop, mRight, mBottom);
13754        } else {
13755            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13756            tmpRect.set(0, 0, getWidth(), getHeight());
13757            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13758            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13759                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13760        }
13761    }
13762
13763    /**
13764     * Determines whether the given point, in local coordinates is inside the view.
13765     */
13766    /*package*/ final boolean pointInView(float localX, float localY) {
13767        return pointInView(localX, localY, 0);
13768    }
13769
13770    /**
13771     * Utility method to determine whether the given point, in local coordinates,
13772     * is inside the view, where the area of the view is expanded by the slop factor.
13773     * This method is called while processing touch-move events to determine if the event
13774     * is still within the view.
13775     *
13776     * @hide
13777     */
13778    public boolean pointInView(float localX, float localY, float slop) {
13779        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13780                localY < ((mBottom - mTop) + slop);
13781    }
13782
13783    /**
13784     * When a view has focus and the user navigates away from it, the next view is searched for
13785     * starting from the rectangle filled in by this method.
13786     *
13787     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13788     * of the view.  However, if your view maintains some idea of internal selection,
13789     * such as a cursor, or a selected row or column, you should override this method and
13790     * fill in a more specific rectangle.
13791     *
13792     * @param r The rectangle to fill in, in this view's coordinates.
13793     */
13794    public void getFocusedRect(Rect r) {
13795        getDrawingRect(r);
13796    }
13797
13798    /**
13799     * If some part of this view is not clipped by any of its parents, then
13800     * return that area in r in global (root) coordinates. To convert r to local
13801     * coordinates (without taking possible View rotations into account), offset
13802     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13803     * If the view is completely clipped or translated out, return false.
13804     *
13805     * @param r If true is returned, r holds the global coordinates of the
13806     *        visible portion of this view.
13807     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13808     *        between this view and its root. globalOffet may be null.
13809     * @return true if r is non-empty (i.e. part of the view is visible at the
13810     *         root level.
13811     */
13812    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13813        int width = mRight - mLeft;
13814        int height = mBottom - mTop;
13815        if (width > 0 && height > 0) {
13816            r.set(0, 0, width, height);
13817            if (globalOffset != null) {
13818                globalOffset.set(-mScrollX, -mScrollY);
13819            }
13820            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13821        }
13822        return false;
13823    }
13824
13825    public final boolean getGlobalVisibleRect(Rect r) {
13826        return getGlobalVisibleRect(r, null);
13827    }
13828
13829    public final boolean getLocalVisibleRect(Rect r) {
13830        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13831        if (getGlobalVisibleRect(r, offset)) {
13832            r.offset(-offset.x, -offset.y); // make r local
13833            return true;
13834        }
13835        return false;
13836    }
13837
13838    /**
13839     * Offset this view's vertical location by the specified number of pixels.
13840     *
13841     * @param offset the number of pixels to offset the view by
13842     */
13843    public void offsetTopAndBottom(int offset) {
13844        if (offset != 0) {
13845            final boolean matrixIsIdentity = hasIdentityMatrix();
13846            if (matrixIsIdentity) {
13847                if (isHardwareAccelerated()) {
13848                    invalidateViewProperty(false, false);
13849                } else {
13850                    final ViewParent p = mParent;
13851                    if (p != null && mAttachInfo != null) {
13852                        final Rect r = mAttachInfo.mTmpInvalRect;
13853                        int minTop;
13854                        int maxBottom;
13855                        int yLoc;
13856                        if (offset < 0) {
13857                            minTop = mTop + offset;
13858                            maxBottom = mBottom;
13859                            yLoc = offset;
13860                        } else {
13861                            minTop = mTop;
13862                            maxBottom = mBottom + offset;
13863                            yLoc = 0;
13864                        }
13865                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13866                        p.invalidateChild(this, r);
13867                    }
13868                }
13869            } else {
13870                invalidateViewProperty(false, false);
13871            }
13872
13873            mTop += offset;
13874            mBottom += offset;
13875            mRenderNode.offsetTopAndBottom(offset);
13876            if (isHardwareAccelerated()) {
13877                invalidateViewProperty(false, false);
13878                invalidateParentIfNeededAndWasQuickRejected();
13879            } else {
13880                if (!matrixIsIdentity) {
13881                    invalidateViewProperty(false, true);
13882                }
13883                invalidateParentIfNeeded();
13884            }
13885            notifySubtreeAccessibilityStateChangedIfNeeded();
13886        }
13887    }
13888
13889    /**
13890     * Offset this view's horizontal location by the specified amount of pixels.
13891     *
13892     * @param offset the number of pixels to offset the view by
13893     */
13894    public void offsetLeftAndRight(int offset) {
13895        if (offset != 0) {
13896            final boolean matrixIsIdentity = hasIdentityMatrix();
13897            if (matrixIsIdentity) {
13898                if (isHardwareAccelerated()) {
13899                    invalidateViewProperty(false, false);
13900                } else {
13901                    final ViewParent p = mParent;
13902                    if (p != null && mAttachInfo != null) {
13903                        final Rect r = mAttachInfo.mTmpInvalRect;
13904                        int minLeft;
13905                        int maxRight;
13906                        if (offset < 0) {
13907                            minLeft = mLeft + offset;
13908                            maxRight = mRight;
13909                        } else {
13910                            minLeft = mLeft;
13911                            maxRight = mRight + offset;
13912                        }
13913                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13914                        p.invalidateChild(this, r);
13915                    }
13916                }
13917            } else {
13918                invalidateViewProperty(false, false);
13919            }
13920
13921            mLeft += offset;
13922            mRight += offset;
13923            mRenderNode.offsetLeftAndRight(offset);
13924            if (isHardwareAccelerated()) {
13925                invalidateViewProperty(false, false);
13926                invalidateParentIfNeededAndWasQuickRejected();
13927            } else {
13928                if (!matrixIsIdentity) {
13929                    invalidateViewProperty(false, true);
13930                }
13931                invalidateParentIfNeeded();
13932            }
13933            notifySubtreeAccessibilityStateChangedIfNeeded();
13934        }
13935    }
13936
13937    /**
13938     * Get the LayoutParams associated with this view. All views should have
13939     * layout parameters. These supply parameters to the <i>parent</i> of this
13940     * view specifying how it should be arranged. There are many subclasses of
13941     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13942     * of ViewGroup that are responsible for arranging their children.
13943     *
13944     * This method may return null if this View is not attached to a parent
13945     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13946     * was not invoked successfully. When a View is attached to a parent
13947     * ViewGroup, this method must not return null.
13948     *
13949     * @return The LayoutParams associated with this view, or null if no
13950     *         parameters have been set yet
13951     */
13952    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13953    public ViewGroup.LayoutParams getLayoutParams() {
13954        return mLayoutParams;
13955    }
13956
13957    /**
13958     * Set the layout parameters associated with this view. These supply
13959     * parameters to the <i>parent</i> of this view specifying how it should be
13960     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13961     * correspond to the different subclasses of ViewGroup that are responsible
13962     * for arranging their children.
13963     *
13964     * @param params The layout parameters for this view, cannot be null
13965     */
13966    public void setLayoutParams(ViewGroup.LayoutParams params) {
13967        if (params == null) {
13968            throw new NullPointerException("Layout parameters cannot be null");
13969        }
13970        mLayoutParams = params;
13971        resolveLayoutParams();
13972        if (mParent instanceof ViewGroup) {
13973            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13974        }
13975        requestLayout();
13976    }
13977
13978    /**
13979     * Resolve the layout parameters depending on the resolved layout direction
13980     *
13981     * @hide
13982     */
13983    public void resolveLayoutParams() {
13984        if (mLayoutParams != null) {
13985            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13986        }
13987    }
13988
13989    /**
13990     * Set the scrolled position of your view. This will cause a call to
13991     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13992     * invalidated.
13993     * @param x the x position to scroll to
13994     * @param y the y position to scroll to
13995     */
13996    public void scrollTo(int x, int y) {
13997        if (mScrollX != x || mScrollY != y) {
13998            int oldX = mScrollX;
13999            int oldY = mScrollY;
14000            mScrollX = x;
14001            mScrollY = y;
14002            invalidateParentCaches();
14003            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
14004            if (!awakenScrollBars()) {
14005                postInvalidateOnAnimation();
14006            }
14007        }
14008    }
14009
14010    /**
14011     * Move the scrolled position of your view. This will cause a call to
14012     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14013     * invalidated.
14014     * @param x the amount of pixels to scroll by horizontally
14015     * @param y the amount of pixels to scroll by vertically
14016     */
14017    public void scrollBy(int x, int y) {
14018        scrollTo(mScrollX + x, mScrollY + y);
14019    }
14020
14021    /**
14022     * <p>Trigger the scrollbars to draw. When invoked this method starts an
14023     * animation to fade the scrollbars out after a default delay. If a subclass
14024     * provides animated scrolling, the start delay should equal the duration
14025     * of the scrolling animation.</p>
14026     *
14027     * <p>The animation starts only if at least one of the scrollbars is
14028     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
14029     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14030     * this method returns true, and false otherwise. If the animation is
14031     * started, this method calls {@link #invalidate()}; in that case the
14032     * caller should not call {@link #invalidate()}.</p>
14033     *
14034     * <p>This method should be invoked every time a subclass directly updates
14035     * the scroll parameters.</p>
14036     *
14037     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
14038     * and {@link #scrollTo(int, int)}.</p>
14039     *
14040     * @return true if the animation is played, false otherwise
14041     *
14042     * @see #awakenScrollBars(int)
14043     * @see #scrollBy(int, int)
14044     * @see #scrollTo(int, int)
14045     * @see #isHorizontalScrollBarEnabled()
14046     * @see #isVerticalScrollBarEnabled()
14047     * @see #setHorizontalScrollBarEnabled(boolean)
14048     * @see #setVerticalScrollBarEnabled(boolean)
14049     */
14050    protected boolean awakenScrollBars() {
14051        return mScrollCache != null &&
14052                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
14053    }
14054
14055    /**
14056     * Trigger the scrollbars to draw.
14057     * This method differs from awakenScrollBars() only in its default duration.
14058     * initialAwakenScrollBars() will show the scroll bars for longer than
14059     * usual to give the user more of a chance to notice them.
14060     *
14061     * @return true if the animation is played, false otherwise.
14062     */
14063    private boolean initialAwakenScrollBars() {
14064        return mScrollCache != null &&
14065                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
14066    }
14067
14068    /**
14069     * <p>
14070     * Trigger the scrollbars to draw. When invoked this method starts an
14071     * animation to fade the scrollbars out after a fixed delay. If a subclass
14072     * provides animated scrolling, the start delay should equal the duration of
14073     * the scrolling animation.
14074     * </p>
14075     *
14076     * <p>
14077     * The animation starts only if at least one of the scrollbars is enabled,
14078     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14079     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14080     * this method returns true, and false otherwise. If the animation is
14081     * started, this method calls {@link #invalidate()}; 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     * @return true if the animation is played, false otherwise
14094     *
14095     * @see #scrollBy(int, int)
14096     * @see #scrollTo(int, int)
14097     * @see #isHorizontalScrollBarEnabled()
14098     * @see #isVerticalScrollBarEnabled()
14099     * @see #setHorizontalScrollBarEnabled(boolean)
14100     * @see #setVerticalScrollBarEnabled(boolean)
14101     */
14102    protected boolean awakenScrollBars(int startDelay) {
14103        return awakenScrollBars(startDelay, true);
14104    }
14105
14106    /**
14107     * <p>
14108     * Trigger the scrollbars to draw. When invoked this method starts an
14109     * animation to fade the scrollbars out after a fixed delay. If a subclass
14110     * provides animated scrolling, the start delay should equal the duration of
14111     * the scrolling animation.
14112     * </p>
14113     *
14114     * <p>
14115     * The animation starts only if at least one of the scrollbars is enabled,
14116     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14117     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14118     * this method returns true, and false otherwise. If the animation is
14119     * started, this method calls {@link #invalidate()} if the invalidate parameter
14120     * is set to true; in that case the caller
14121     * should not call {@link #invalidate()}.
14122     * </p>
14123     *
14124     * <p>
14125     * This method should be invoked every time a subclass directly updates the
14126     * scroll parameters.
14127     * </p>
14128     *
14129     * @param startDelay the delay, in milliseconds, after which the animation
14130     *        should start; when the delay is 0, the animation starts
14131     *        immediately
14132     *
14133     * @param invalidate Whether this method should call invalidate
14134     *
14135     * @return true if the animation is played, false otherwise
14136     *
14137     * @see #scrollBy(int, int)
14138     * @see #scrollTo(int, int)
14139     * @see #isHorizontalScrollBarEnabled()
14140     * @see #isVerticalScrollBarEnabled()
14141     * @see #setHorizontalScrollBarEnabled(boolean)
14142     * @see #setVerticalScrollBarEnabled(boolean)
14143     */
14144    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
14145        final ScrollabilityCache scrollCache = mScrollCache;
14146
14147        if (scrollCache == null || !scrollCache.fadeScrollBars) {
14148            return false;
14149        }
14150
14151        if (scrollCache.scrollBar == null) {
14152            scrollCache.scrollBar = new ScrollBarDrawable();
14153            scrollCache.scrollBar.setState(getDrawableState());
14154            scrollCache.scrollBar.setCallback(this);
14155        }
14156
14157        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
14158
14159            if (invalidate) {
14160                // Invalidate to show the scrollbars
14161                postInvalidateOnAnimation();
14162            }
14163
14164            if (scrollCache.state == ScrollabilityCache.OFF) {
14165                // FIXME: this is copied from WindowManagerService.
14166                // We should get this value from the system when it
14167                // is possible to do so.
14168                final int KEY_REPEAT_FIRST_DELAY = 750;
14169                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
14170            }
14171
14172            // Tell mScrollCache when we should start fading. This may
14173            // extend the fade start time if one was already scheduled
14174            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
14175            scrollCache.fadeStartTime = fadeStartTime;
14176            scrollCache.state = ScrollabilityCache.ON;
14177
14178            // Schedule our fader to run, unscheduling any old ones first
14179            if (mAttachInfo != null) {
14180                mAttachInfo.mHandler.removeCallbacks(scrollCache);
14181                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
14182            }
14183
14184            return true;
14185        }
14186
14187        return false;
14188    }
14189
14190    /**
14191     * Do not invalidate views which are not visible and which are not running an animation. They
14192     * will not get drawn and they should not set dirty flags as if they will be drawn
14193     */
14194    private boolean skipInvalidate() {
14195        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
14196                (!(mParent instanceof ViewGroup) ||
14197                        !((ViewGroup) mParent).isViewTransitioning(this));
14198    }
14199
14200    /**
14201     * Mark the area defined by dirty as needing to be drawn. If the view is
14202     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14203     * point in the future.
14204     * <p>
14205     * This must be called from a UI thread. To call from a non-UI thread, call
14206     * {@link #postInvalidate()}.
14207     * <p>
14208     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
14209     * {@code dirty}.
14210     *
14211     * @param dirty the rectangle representing the bounds of the dirty region
14212     */
14213    public void invalidate(Rect dirty) {
14214        final int scrollX = mScrollX;
14215        final int scrollY = mScrollY;
14216        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
14217                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
14218    }
14219
14220    /**
14221     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
14222     * coordinates of the dirty rect are relative to the view. If the view is
14223     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14224     * point in the future.
14225     * <p>
14226     * This must be called from a UI thread. To call from a non-UI thread, call
14227     * {@link #postInvalidate()}.
14228     *
14229     * @param l the left position of the dirty region
14230     * @param t the top position of the dirty region
14231     * @param r the right position of the dirty region
14232     * @param b the bottom position of the dirty region
14233     */
14234    public void invalidate(int l, int t, int r, int b) {
14235        final int scrollX = mScrollX;
14236        final int scrollY = mScrollY;
14237        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
14238    }
14239
14240    /**
14241     * Invalidate the whole view. If the view is visible,
14242     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
14243     * the future.
14244     * <p>
14245     * This must be called from a UI thread. To call from a non-UI thread, call
14246     * {@link #postInvalidate()}.
14247     */
14248    public void invalidate() {
14249        invalidate(true);
14250    }
14251
14252    /**
14253     * This is where the invalidate() work actually happens. A full invalidate()
14254     * causes the drawing cache to be invalidated, but this function can be
14255     * called with invalidateCache set to false to skip that invalidation step
14256     * for cases that do not need it (for example, a component that remains at
14257     * the same dimensions with the same content).
14258     *
14259     * @param invalidateCache Whether the drawing cache for this view should be
14260     *            invalidated as well. This is usually true for a full
14261     *            invalidate, but may be set to false if the View's contents or
14262     *            dimensions have not changed.
14263     * @hide
14264     */
14265    public void invalidate(boolean invalidateCache) {
14266        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
14267    }
14268
14269    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
14270            boolean fullInvalidate) {
14271        if (mGhostView != null) {
14272            mGhostView.invalidate(true);
14273            return;
14274        }
14275
14276        if (skipInvalidate()) {
14277            return;
14278        }
14279
14280        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
14281                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
14282                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
14283                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
14284            if (fullInvalidate) {
14285                mLastIsOpaque = isOpaque();
14286                mPrivateFlags &= ~PFLAG_DRAWN;
14287            }
14288
14289            mPrivateFlags |= PFLAG_DIRTY;
14290
14291            if (invalidateCache) {
14292                mPrivateFlags |= PFLAG_INVALIDATED;
14293                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14294            }
14295
14296            // Propagate the damage rectangle to the parent view.
14297            final AttachInfo ai = mAttachInfo;
14298            final ViewParent p = mParent;
14299            if (p != null && ai != null && l < r && t < b) {
14300                final Rect damage = ai.mTmpInvalRect;
14301                damage.set(l, t, r, b);
14302                p.invalidateChild(this, damage);
14303            }
14304
14305            // Damage the entire projection receiver, if necessary.
14306            if (mBackground != null && mBackground.isProjected()) {
14307                final View receiver = getProjectionReceiver();
14308                if (receiver != null) {
14309                    receiver.damageInParent();
14310                }
14311            }
14312        }
14313    }
14314
14315    /**
14316     * @return this view's projection receiver, or {@code null} if none exists
14317     */
14318    private View getProjectionReceiver() {
14319        ViewParent p = getParent();
14320        while (p != null && p instanceof View) {
14321            final View v = (View) p;
14322            if (v.isProjectionReceiver()) {
14323                return v;
14324            }
14325            p = p.getParent();
14326        }
14327
14328        return null;
14329    }
14330
14331    /**
14332     * @return whether the view is a projection receiver
14333     */
14334    private boolean isProjectionReceiver() {
14335        return mBackground != null;
14336    }
14337
14338    /**
14339     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
14340     * set any flags or handle all of the cases handled by the default invalidation methods.
14341     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
14342     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
14343     * walk up the hierarchy, transforming the dirty rect as necessary.
14344     *
14345     * The method also handles normal invalidation logic if display list properties are not
14346     * being used in this view. The invalidateParent and forceRedraw flags are used by that
14347     * backup approach, to handle these cases used in the various property-setting methods.
14348     *
14349     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
14350     * are not being used in this view
14351     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
14352     * list properties are not being used in this view
14353     */
14354    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
14355        if (!isHardwareAccelerated()
14356                || !mRenderNode.isValid()
14357                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
14358            if (invalidateParent) {
14359                invalidateParentCaches();
14360            }
14361            if (forceRedraw) {
14362                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14363            }
14364            invalidate(false);
14365        } else {
14366            damageInParent();
14367        }
14368    }
14369
14370    /**
14371     * Tells the parent view to damage this view's bounds.
14372     *
14373     * @hide
14374     */
14375    protected void damageInParent() {
14376        final AttachInfo ai = mAttachInfo;
14377        final ViewParent p = mParent;
14378        if (p != null && ai != null) {
14379            final Rect r = ai.mTmpInvalRect;
14380            r.set(0, 0, mRight - mLeft, mBottom - mTop);
14381            if (mParent instanceof ViewGroup) {
14382                ((ViewGroup) mParent).damageChild(this, r);
14383            } else {
14384                mParent.invalidateChild(this, r);
14385            }
14386        }
14387    }
14388
14389    /**
14390     * Utility method to transform a given Rect by the current matrix of this view.
14391     */
14392    void transformRect(final Rect rect) {
14393        if (!getMatrix().isIdentity()) {
14394            RectF boundingRect = mAttachInfo.mTmpTransformRect;
14395            boundingRect.set(rect);
14396            getMatrix().mapRect(boundingRect);
14397            rect.set((int) Math.floor(boundingRect.left),
14398                    (int) Math.floor(boundingRect.top),
14399                    (int) Math.ceil(boundingRect.right),
14400                    (int) Math.ceil(boundingRect.bottom));
14401        }
14402    }
14403
14404    /**
14405     * Used to indicate that the parent of this view should clear its caches. This functionality
14406     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14407     * which is necessary when various parent-managed properties of the view change, such as
14408     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
14409     * clears the parent caches and does not causes an invalidate event.
14410     *
14411     * @hide
14412     */
14413    protected void invalidateParentCaches() {
14414        if (mParent instanceof View) {
14415            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
14416        }
14417    }
14418
14419    /**
14420     * Used to indicate that the parent of this view should be invalidated. This functionality
14421     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14422     * which is necessary when various parent-managed properties of the view change, such as
14423     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
14424     * an invalidation event to the parent.
14425     *
14426     * @hide
14427     */
14428    protected void invalidateParentIfNeeded() {
14429        if (isHardwareAccelerated() && mParent instanceof View) {
14430            ((View) mParent).invalidate(true);
14431        }
14432    }
14433
14434    /**
14435     * @hide
14436     */
14437    protected void invalidateParentIfNeededAndWasQuickRejected() {
14438        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
14439            // View was rejected last time it was drawn by its parent; this may have changed
14440            invalidateParentIfNeeded();
14441        }
14442    }
14443
14444    /**
14445     * Indicates whether this View is opaque. An opaque View guarantees that it will
14446     * draw all the pixels overlapping its bounds using a fully opaque color.
14447     *
14448     * Subclasses of View should override this method whenever possible to indicate
14449     * whether an instance is opaque. Opaque Views are treated in a special way by
14450     * the View hierarchy, possibly allowing it to perform optimizations during
14451     * invalidate/draw passes.
14452     *
14453     * @return True if this View is guaranteed to be fully opaque, false otherwise.
14454     */
14455    @ViewDebug.ExportedProperty(category = "drawing")
14456    public boolean isOpaque() {
14457        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
14458                getFinalAlpha() >= 1.0f;
14459    }
14460
14461    /**
14462     * @hide
14463     */
14464    protected void computeOpaqueFlags() {
14465        // Opaque if:
14466        //   - Has a background
14467        //   - Background is opaque
14468        //   - Doesn't have scrollbars or scrollbars overlay
14469
14470        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
14471            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
14472        } else {
14473            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
14474        }
14475
14476        final int flags = mViewFlags;
14477        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
14478                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
14479                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
14480            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
14481        } else {
14482            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
14483        }
14484    }
14485
14486    /**
14487     * @hide
14488     */
14489    protected boolean hasOpaqueScrollbars() {
14490        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
14491    }
14492
14493    /**
14494     * @return A handler associated with the thread running the View. This
14495     * handler can be used to pump events in the UI events queue.
14496     */
14497    public Handler getHandler() {
14498        final AttachInfo attachInfo = mAttachInfo;
14499        if (attachInfo != null) {
14500            return attachInfo.mHandler;
14501        }
14502        return null;
14503    }
14504
14505    /**
14506     * Returns the queue of runnable for this view.
14507     *
14508     * @return the queue of runnables for this view
14509     */
14510    private HandlerActionQueue getRunQueue() {
14511        if (mRunQueue == null) {
14512            mRunQueue = new HandlerActionQueue();
14513        }
14514        return mRunQueue;
14515    }
14516
14517    /**
14518     * Gets the view root associated with the View.
14519     * @return The view root, or null if none.
14520     * @hide
14521     */
14522    public ViewRootImpl getViewRootImpl() {
14523        if (mAttachInfo != null) {
14524            return mAttachInfo.mViewRootImpl;
14525        }
14526        return null;
14527    }
14528
14529    /**
14530     * @hide
14531     */
14532    public ThreadedRenderer getThreadedRenderer() {
14533        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
14534    }
14535
14536    /**
14537     * <p>Causes the Runnable to be added to the message queue.
14538     * The runnable will be run on the user interface thread.</p>
14539     *
14540     * @param action The Runnable that will be executed.
14541     *
14542     * @return Returns true if the Runnable was successfully placed in to the
14543     *         message queue.  Returns false on failure, usually because the
14544     *         looper processing the message queue is exiting.
14545     *
14546     * @see #postDelayed
14547     * @see #removeCallbacks
14548     */
14549    public boolean post(Runnable action) {
14550        final AttachInfo attachInfo = mAttachInfo;
14551        if (attachInfo != null) {
14552            return attachInfo.mHandler.post(action);
14553        }
14554
14555        // Postpone the runnable until we know on which thread it needs to run.
14556        // Assume that the runnable will be successfully placed after attach.
14557        getRunQueue().post(action);
14558        return true;
14559    }
14560
14561    /**
14562     * <p>Causes the Runnable to be added to the message queue, to be run
14563     * after the specified amount of time elapses.
14564     * The runnable will be run on the user interface thread.</p>
14565     *
14566     * @param action The Runnable that will be executed.
14567     * @param delayMillis The delay (in milliseconds) until the Runnable
14568     *        will be executed.
14569     *
14570     * @return true if the Runnable was successfully placed in to the
14571     *         message queue.  Returns false on failure, usually because the
14572     *         looper processing the message queue is exiting.  Note that a
14573     *         result of true does not mean the Runnable will be processed --
14574     *         if the looper is quit before the delivery time of the message
14575     *         occurs then the message will be dropped.
14576     *
14577     * @see #post
14578     * @see #removeCallbacks
14579     */
14580    public boolean postDelayed(Runnable action, long delayMillis) {
14581        final AttachInfo attachInfo = mAttachInfo;
14582        if (attachInfo != null) {
14583            return attachInfo.mHandler.postDelayed(action, delayMillis);
14584        }
14585
14586        // Postpone the runnable until we know on which thread it needs to run.
14587        // Assume that the runnable will be successfully placed after attach.
14588        getRunQueue().postDelayed(action, delayMillis);
14589        return true;
14590    }
14591
14592    /**
14593     * <p>Causes the Runnable to execute on the next animation time step.
14594     * The runnable will be run on the user interface thread.</p>
14595     *
14596     * @param action The Runnable that will be executed.
14597     *
14598     * @see #postOnAnimationDelayed
14599     * @see #removeCallbacks
14600     */
14601    public void postOnAnimation(Runnable action) {
14602        final AttachInfo attachInfo = mAttachInfo;
14603        if (attachInfo != null) {
14604            attachInfo.mViewRootImpl.mChoreographer.postCallback(
14605                    Choreographer.CALLBACK_ANIMATION, action, null);
14606        } else {
14607            // Postpone the runnable until we know
14608            // on which thread it needs to run.
14609            getRunQueue().post(action);
14610        }
14611    }
14612
14613    /**
14614     * <p>Causes the Runnable to execute on the next animation time step,
14615     * after the specified amount of time elapses.
14616     * The runnable will be run on the user interface thread.</p>
14617     *
14618     * @param action The Runnable that will be executed.
14619     * @param delayMillis The delay (in milliseconds) until the Runnable
14620     *        will be executed.
14621     *
14622     * @see #postOnAnimation
14623     * @see #removeCallbacks
14624     */
14625    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14626        final AttachInfo attachInfo = mAttachInfo;
14627        if (attachInfo != null) {
14628            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14629                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14630        } else {
14631            // Postpone the runnable until we know
14632            // on which thread it needs to run.
14633            getRunQueue().postDelayed(action, delayMillis);
14634        }
14635    }
14636
14637    /**
14638     * <p>Removes the specified Runnable from the message queue.</p>
14639     *
14640     * @param action The Runnable to remove from the message handling queue
14641     *
14642     * @return true if this view could ask the Handler to remove the Runnable,
14643     *         false otherwise. When the returned value is true, the Runnable
14644     *         may or may not have been actually removed from the message queue
14645     *         (for instance, if the Runnable was not in the queue already.)
14646     *
14647     * @see #post
14648     * @see #postDelayed
14649     * @see #postOnAnimation
14650     * @see #postOnAnimationDelayed
14651     */
14652    public boolean removeCallbacks(Runnable action) {
14653        if (action != null) {
14654            final AttachInfo attachInfo = mAttachInfo;
14655            if (attachInfo != null) {
14656                attachInfo.mHandler.removeCallbacks(action);
14657                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14658                        Choreographer.CALLBACK_ANIMATION, action, null);
14659            }
14660            getRunQueue().removeCallbacks(action);
14661        }
14662        return true;
14663    }
14664
14665    /**
14666     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14667     * Use this to invalidate the View from a non-UI thread.</p>
14668     *
14669     * <p>This method can be invoked from outside of the UI thread
14670     * only when this View is attached to a window.</p>
14671     *
14672     * @see #invalidate()
14673     * @see #postInvalidateDelayed(long)
14674     */
14675    public void postInvalidate() {
14676        postInvalidateDelayed(0);
14677    }
14678
14679    /**
14680     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14681     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14682     *
14683     * <p>This method can be invoked from outside of the UI thread
14684     * only when this View is attached to a window.</p>
14685     *
14686     * @param left The left coordinate of the rectangle to invalidate.
14687     * @param top The top coordinate of the rectangle to invalidate.
14688     * @param right The right coordinate of the rectangle to invalidate.
14689     * @param bottom The bottom coordinate of the rectangle to invalidate.
14690     *
14691     * @see #invalidate(int, int, int, int)
14692     * @see #invalidate(Rect)
14693     * @see #postInvalidateDelayed(long, int, int, int, int)
14694     */
14695    public void postInvalidate(int left, int top, int right, int bottom) {
14696        postInvalidateDelayed(0, left, top, right, bottom);
14697    }
14698
14699    /**
14700     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14701     * loop. Waits for the specified amount of time.</p>
14702     *
14703     * <p>This method can be invoked from outside of the UI thread
14704     * only when this View is attached to a window.</p>
14705     *
14706     * @param delayMilliseconds the duration in milliseconds to delay the
14707     *         invalidation by
14708     *
14709     * @see #invalidate()
14710     * @see #postInvalidate()
14711     */
14712    public void postInvalidateDelayed(long delayMilliseconds) {
14713        // We try only with the AttachInfo because there's no point in invalidating
14714        // if we are not attached to our window
14715        final AttachInfo attachInfo = mAttachInfo;
14716        if (attachInfo != null) {
14717            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14718        }
14719    }
14720
14721    /**
14722     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14723     * through the event loop. Waits for the specified amount of time.</p>
14724     *
14725     * <p>This method can be invoked from outside of the UI thread
14726     * only when this View is attached to a window.</p>
14727     *
14728     * @param delayMilliseconds the duration in milliseconds to delay the
14729     *         invalidation by
14730     * @param left The left coordinate of the rectangle to invalidate.
14731     * @param top The top coordinate of the rectangle to invalidate.
14732     * @param right The right coordinate of the rectangle to invalidate.
14733     * @param bottom The bottom coordinate of the rectangle to invalidate.
14734     *
14735     * @see #invalidate(int, int, int, int)
14736     * @see #invalidate(Rect)
14737     * @see #postInvalidate(int, int, int, int)
14738     */
14739    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14740            int right, int bottom) {
14741
14742        // We try only with the AttachInfo because there's no point in invalidating
14743        // if we are not attached to our window
14744        final AttachInfo attachInfo = mAttachInfo;
14745        if (attachInfo != null) {
14746            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14747            info.target = this;
14748            info.left = left;
14749            info.top = top;
14750            info.right = right;
14751            info.bottom = bottom;
14752
14753            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14754        }
14755    }
14756
14757    /**
14758     * <p>Cause an invalidate to happen on the next animation time step, typically the
14759     * next display frame.</p>
14760     *
14761     * <p>This method can be invoked from outside of the UI thread
14762     * only when this View is attached to a window.</p>
14763     *
14764     * @see #invalidate()
14765     */
14766    public void postInvalidateOnAnimation() {
14767        // We try only with the AttachInfo because there's no point in invalidating
14768        // if we are not attached to our window
14769        final AttachInfo attachInfo = mAttachInfo;
14770        if (attachInfo != null) {
14771            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14772        }
14773    }
14774
14775    /**
14776     * <p>Cause an invalidate of the specified area to happen on the next animation
14777     * time step, typically the next display frame.</p>
14778     *
14779     * <p>This method can be invoked from outside of the UI thread
14780     * only when this View is attached to a window.</p>
14781     *
14782     * @param left The left coordinate of the rectangle to invalidate.
14783     * @param top The top coordinate of the rectangle to invalidate.
14784     * @param right The right coordinate of the rectangle to invalidate.
14785     * @param bottom The bottom coordinate of the rectangle to invalidate.
14786     *
14787     * @see #invalidate(int, int, int, int)
14788     * @see #invalidate(Rect)
14789     */
14790    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14791        // We try only with the AttachInfo because there's no point in invalidating
14792        // if we are not attached to our window
14793        final AttachInfo attachInfo = mAttachInfo;
14794        if (attachInfo != null) {
14795            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14796            info.target = this;
14797            info.left = left;
14798            info.top = top;
14799            info.right = right;
14800            info.bottom = bottom;
14801
14802            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14803        }
14804    }
14805
14806    /**
14807     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14808     * This event is sent at most once every
14809     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14810     */
14811    private void postSendViewScrolledAccessibilityEventCallback() {
14812        if (mSendViewScrolledAccessibilityEvent == null) {
14813            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14814        }
14815        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14816            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14817            postDelayed(mSendViewScrolledAccessibilityEvent,
14818                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14819        }
14820    }
14821
14822    /**
14823     * Called by a parent to request that a child update its values for mScrollX
14824     * and mScrollY if necessary. This will typically be done if the child is
14825     * animating a scroll using a {@link android.widget.Scroller Scroller}
14826     * object.
14827     */
14828    public void computeScroll() {
14829    }
14830
14831    /**
14832     * <p>Indicate whether the horizontal edges are faded when the view is
14833     * scrolled horizontally.</p>
14834     *
14835     * @return true if the horizontal edges should are faded on scroll, false
14836     *         otherwise
14837     *
14838     * @see #setHorizontalFadingEdgeEnabled(boolean)
14839     *
14840     * @attr ref android.R.styleable#View_requiresFadingEdge
14841     */
14842    public boolean isHorizontalFadingEdgeEnabled() {
14843        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14844    }
14845
14846    /**
14847     * <p>Define whether the horizontal edges should be faded when this view
14848     * is scrolled horizontally.</p>
14849     *
14850     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14851     *                                    be faded when the view is scrolled
14852     *                                    horizontally
14853     *
14854     * @see #isHorizontalFadingEdgeEnabled()
14855     *
14856     * @attr ref android.R.styleable#View_requiresFadingEdge
14857     */
14858    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14859        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14860            if (horizontalFadingEdgeEnabled) {
14861                initScrollCache();
14862            }
14863
14864            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14865        }
14866    }
14867
14868    /**
14869     * <p>Indicate whether the vertical edges are faded when the view is
14870     * scrolled horizontally.</p>
14871     *
14872     * @return true if the vertical edges should are faded on scroll, false
14873     *         otherwise
14874     *
14875     * @see #setVerticalFadingEdgeEnabled(boolean)
14876     *
14877     * @attr ref android.R.styleable#View_requiresFadingEdge
14878     */
14879    public boolean isVerticalFadingEdgeEnabled() {
14880        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14881    }
14882
14883    /**
14884     * <p>Define whether the vertical edges should be faded when this view
14885     * is scrolled vertically.</p>
14886     *
14887     * @param verticalFadingEdgeEnabled true if the vertical edges should
14888     *                                  be faded when the view is scrolled
14889     *                                  vertically
14890     *
14891     * @see #isVerticalFadingEdgeEnabled()
14892     *
14893     * @attr ref android.R.styleable#View_requiresFadingEdge
14894     */
14895    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14896        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14897            if (verticalFadingEdgeEnabled) {
14898                initScrollCache();
14899            }
14900
14901            mViewFlags ^= FADING_EDGE_VERTICAL;
14902        }
14903    }
14904
14905    /**
14906     * Returns the strength, or intensity, of the top faded edge. The strength is
14907     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14908     * returns 0.0 or 1.0 but no value in between.
14909     *
14910     * Subclasses should override this method to provide a smoother fade transition
14911     * when scrolling occurs.
14912     *
14913     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14914     */
14915    protected float getTopFadingEdgeStrength() {
14916        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14917    }
14918
14919    /**
14920     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14921     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14922     * returns 0.0 or 1.0 but no value in between.
14923     *
14924     * Subclasses should override this method to provide a smoother fade transition
14925     * when scrolling occurs.
14926     *
14927     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14928     */
14929    protected float getBottomFadingEdgeStrength() {
14930        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14931                computeVerticalScrollRange() ? 1.0f : 0.0f;
14932    }
14933
14934    /**
14935     * Returns the strength, or intensity, of the left faded edge. The strength is
14936     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14937     * returns 0.0 or 1.0 but no value in between.
14938     *
14939     * Subclasses should override this method to provide a smoother fade transition
14940     * when scrolling occurs.
14941     *
14942     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14943     */
14944    protected float getLeftFadingEdgeStrength() {
14945        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14946    }
14947
14948    /**
14949     * Returns the strength, or intensity, of the right faded edge. The strength is
14950     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14951     * returns 0.0 or 1.0 but no value in between.
14952     *
14953     * Subclasses should override this method to provide a smoother fade transition
14954     * when scrolling occurs.
14955     *
14956     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14957     */
14958    protected float getRightFadingEdgeStrength() {
14959        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14960                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14961    }
14962
14963    /**
14964     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14965     * scrollbar is not drawn by default.</p>
14966     *
14967     * @return true if the horizontal scrollbar should be painted, false
14968     *         otherwise
14969     *
14970     * @see #setHorizontalScrollBarEnabled(boolean)
14971     */
14972    public boolean isHorizontalScrollBarEnabled() {
14973        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14974    }
14975
14976    /**
14977     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14978     * scrollbar is not drawn by default.</p>
14979     *
14980     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14981     *                                   be painted
14982     *
14983     * @see #isHorizontalScrollBarEnabled()
14984     */
14985    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14986        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14987            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14988            computeOpaqueFlags();
14989            resolvePadding();
14990        }
14991    }
14992
14993    /**
14994     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14995     * scrollbar is not drawn by default.</p>
14996     *
14997     * @return true if the vertical scrollbar should be painted, false
14998     *         otherwise
14999     *
15000     * @see #setVerticalScrollBarEnabled(boolean)
15001     */
15002    public boolean isVerticalScrollBarEnabled() {
15003        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
15004    }
15005
15006    /**
15007     * <p>Define whether the vertical scrollbar should be drawn or not. The
15008     * scrollbar is not drawn by default.</p>
15009     *
15010     * @param verticalScrollBarEnabled true if the vertical scrollbar should
15011     *                                 be painted
15012     *
15013     * @see #isVerticalScrollBarEnabled()
15014     */
15015    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
15016        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
15017            mViewFlags ^= SCROLLBARS_VERTICAL;
15018            computeOpaqueFlags();
15019            resolvePadding();
15020        }
15021    }
15022
15023    /**
15024     * @hide
15025     */
15026    protected void recomputePadding() {
15027        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15028    }
15029
15030    /**
15031     * Define whether scrollbars will fade when the view is not scrolling.
15032     *
15033     * @param fadeScrollbars whether to enable fading
15034     *
15035     * @attr ref android.R.styleable#View_fadeScrollbars
15036     */
15037    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
15038        initScrollCache();
15039        final ScrollabilityCache scrollabilityCache = mScrollCache;
15040        scrollabilityCache.fadeScrollBars = fadeScrollbars;
15041        if (fadeScrollbars) {
15042            scrollabilityCache.state = ScrollabilityCache.OFF;
15043        } else {
15044            scrollabilityCache.state = ScrollabilityCache.ON;
15045        }
15046    }
15047
15048    /**
15049     *
15050     * Returns true if scrollbars will fade when this view is not scrolling
15051     *
15052     * @return true if scrollbar fading is enabled
15053     *
15054     * @attr ref android.R.styleable#View_fadeScrollbars
15055     */
15056    public boolean isScrollbarFadingEnabled() {
15057        return mScrollCache != null && mScrollCache.fadeScrollBars;
15058    }
15059
15060    /**
15061     *
15062     * Returns the delay before scrollbars fade.
15063     *
15064     * @return the delay before scrollbars fade
15065     *
15066     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15067     */
15068    public int getScrollBarDefaultDelayBeforeFade() {
15069        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
15070                mScrollCache.scrollBarDefaultDelayBeforeFade;
15071    }
15072
15073    /**
15074     * Define the delay before scrollbars fade.
15075     *
15076     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
15077     *
15078     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15079     */
15080    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
15081        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
15082    }
15083
15084    /**
15085     *
15086     * Returns the scrollbar fade duration.
15087     *
15088     * @return the scrollbar fade duration, in milliseconds
15089     *
15090     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15091     */
15092    public int getScrollBarFadeDuration() {
15093        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
15094                mScrollCache.scrollBarFadeDuration;
15095    }
15096
15097    /**
15098     * Define the scrollbar fade duration.
15099     *
15100     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
15101     *
15102     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15103     */
15104    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
15105        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
15106    }
15107
15108    /**
15109     *
15110     * Returns the scrollbar size.
15111     *
15112     * @return the scrollbar size
15113     *
15114     * @attr ref android.R.styleable#View_scrollbarSize
15115     */
15116    public int getScrollBarSize() {
15117        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
15118                mScrollCache.scrollBarSize;
15119    }
15120
15121    /**
15122     * Define the scrollbar size.
15123     *
15124     * @param scrollBarSize - the scrollbar size
15125     *
15126     * @attr ref android.R.styleable#View_scrollbarSize
15127     */
15128    public void setScrollBarSize(int scrollBarSize) {
15129        getScrollCache().scrollBarSize = scrollBarSize;
15130    }
15131
15132    /**
15133     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
15134     * inset. When inset, they add to the padding of the view. And the scrollbars
15135     * can be drawn inside the padding area or on the edge of the view. For example,
15136     * if a view has a background drawable and you want to draw the scrollbars
15137     * inside the padding specified by the drawable, you can use
15138     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
15139     * appear at the edge of the view, ignoring the padding, then you can use
15140     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
15141     * @param style the style of the scrollbars. Should be one of
15142     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
15143     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
15144     * @see #SCROLLBARS_INSIDE_OVERLAY
15145     * @see #SCROLLBARS_INSIDE_INSET
15146     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15147     * @see #SCROLLBARS_OUTSIDE_INSET
15148     *
15149     * @attr ref android.R.styleable#View_scrollbarStyle
15150     */
15151    public void setScrollBarStyle(@ScrollBarStyle int style) {
15152        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
15153            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
15154            computeOpaqueFlags();
15155            resolvePadding();
15156        }
15157    }
15158
15159    /**
15160     * <p>Returns the current scrollbar style.</p>
15161     * @return the current scrollbar style
15162     * @see #SCROLLBARS_INSIDE_OVERLAY
15163     * @see #SCROLLBARS_INSIDE_INSET
15164     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15165     * @see #SCROLLBARS_OUTSIDE_INSET
15166     *
15167     * @attr ref android.R.styleable#View_scrollbarStyle
15168     */
15169    @ViewDebug.ExportedProperty(mapping = {
15170            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
15171            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
15172            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
15173            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
15174    })
15175    @ScrollBarStyle
15176    public int getScrollBarStyle() {
15177        return mViewFlags & SCROLLBARS_STYLE_MASK;
15178    }
15179
15180    /**
15181     * <p>Compute the horizontal range that the horizontal scrollbar
15182     * represents.</p>
15183     *
15184     * <p>The range is expressed in arbitrary units that must be the same as the
15185     * units used by {@link #computeHorizontalScrollExtent()} and
15186     * {@link #computeHorizontalScrollOffset()}.</p>
15187     *
15188     * <p>The default range is the drawing width of this view.</p>
15189     *
15190     * @return the total horizontal range represented by the horizontal
15191     *         scrollbar
15192     *
15193     * @see #computeHorizontalScrollExtent()
15194     * @see #computeHorizontalScrollOffset()
15195     * @see android.widget.ScrollBarDrawable
15196     */
15197    protected int computeHorizontalScrollRange() {
15198        return getWidth();
15199    }
15200
15201    /**
15202     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
15203     * within the horizontal range. This value is used to compute the position
15204     * of the thumb within the scrollbar's track.</p>
15205     *
15206     * <p>The range is expressed in arbitrary units that must be the same as the
15207     * units used by {@link #computeHorizontalScrollRange()} and
15208     * {@link #computeHorizontalScrollExtent()}.</p>
15209     *
15210     * <p>The default offset is the scroll offset of this view.</p>
15211     *
15212     * @return the horizontal offset of the scrollbar's thumb
15213     *
15214     * @see #computeHorizontalScrollRange()
15215     * @see #computeHorizontalScrollExtent()
15216     * @see android.widget.ScrollBarDrawable
15217     */
15218    protected int computeHorizontalScrollOffset() {
15219        return mScrollX;
15220    }
15221
15222    /**
15223     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
15224     * within the horizontal range. This value is used to compute the length
15225     * of the thumb within the scrollbar's track.</p>
15226     *
15227     * <p>The range is expressed in arbitrary units that must be the same as the
15228     * units used by {@link #computeHorizontalScrollRange()} and
15229     * {@link #computeHorizontalScrollOffset()}.</p>
15230     *
15231     * <p>The default extent is the drawing width of this view.</p>
15232     *
15233     * @return the horizontal extent of the scrollbar's thumb
15234     *
15235     * @see #computeHorizontalScrollRange()
15236     * @see #computeHorizontalScrollOffset()
15237     * @see android.widget.ScrollBarDrawable
15238     */
15239    protected int computeHorizontalScrollExtent() {
15240        return getWidth();
15241    }
15242
15243    /**
15244     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
15245     *
15246     * <p>The range is expressed in arbitrary units that must be the same as the
15247     * units used by {@link #computeVerticalScrollExtent()} and
15248     * {@link #computeVerticalScrollOffset()}.</p>
15249     *
15250     * @return the total vertical range represented by the vertical scrollbar
15251     *
15252     * <p>The default range is the drawing height of this view.</p>
15253     *
15254     * @see #computeVerticalScrollExtent()
15255     * @see #computeVerticalScrollOffset()
15256     * @see android.widget.ScrollBarDrawable
15257     */
15258    protected int computeVerticalScrollRange() {
15259        return getHeight();
15260    }
15261
15262    /**
15263     * <p>Compute the vertical offset of the vertical scrollbar's thumb
15264     * within the horizontal range. This value is used to compute the position
15265     * of the thumb within the scrollbar's track.</p>
15266     *
15267     * <p>The range is expressed in arbitrary units that must be the same as the
15268     * units used by {@link #computeVerticalScrollRange()} and
15269     * {@link #computeVerticalScrollExtent()}.</p>
15270     *
15271     * <p>The default offset is the scroll offset of this view.</p>
15272     *
15273     * @return the vertical offset of the scrollbar's thumb
15274     *
15275     * @see #computeVerticalScrollRange()
15276     * @see #computeVerticalScrollExtent()
15277     * @see android.widget.ScrollBarDrawable
15278     */
15279    protected int computeVerticalScrollOffset() {
15280        return mScrollY;
15281    }
15282
15283    /**
15284     * <p>Compute the vertical extent of the vertical scrollbar's thumb
15285     * within the vertical range. This value is used to compute the length
15286     * of the thumb within the scrollbar's track.</p>
15287     *
15288     * <p>The range is expressed in arbitrary units that must be the same as the
15289     * units used by {@link #computeVerticalScrollRange()} and
15290     * {@link #computeVerticalScrollOffset()}.</p>
15291     *
15292     * <p>The default extent is the drawing height of this view.</p>
15293     *
15294     * @return the vertical extent of the scrollbar's thumb
15295     *
15296     * @see #computeVerticalScrollRange()
15297     * @see #computeVerticalScrollOffset()
15298     * @see android.widget.ScrollBarDrawable
15299     */
15300    protected int computeVerticalScrollExtent() {
15301        return getHeight();
15302    }
15303
15304    /**
15305     * Check if this view can be scrolled horizontally in a certain direction.
15306     *
15307     * @param direction Negative to check scrolling left, positive to check scrolling right.
15308     * @return true if this view can be scrolled in the specified direction, false otherwise.
15309     */
15310    public boolean canScrollHorizontally(int direction) {
15311        final int offset = computeHorizontalScrollOffset();
15312        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
15313        if (range == 0) return false;
15314        if (direction < 0) {
15315            return offset > 0;
15316        } else {
15317            return offset < range - 1;
15318        }
15319    }
15320
15321    /**
15322     * Check if this view can be scrolled vertically in a certain direction.
15323     *
15324     * @param direction Negative to check scrolling up, positive to check scrolling down.
15325     * @return true if this view can be scrolled in the specified direction, false otherwise.
15326     */
15327    public boolean canScrollVertically(int direction) {
15328        final int offset = computeVerticalScrollOffset();
15329        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
15330        if (range == 0) return false;
15331        if (direction < 0) {
15332            return offset > 0;
15333        } else {
15334            return offset < range - 1;
15335        }
15336    }
15337
15338    void getScrollIndicatorBounds(@NonNull Rect out) {
15339        out.left = mScrollX;
15340        out.right = mScrollX + mRight - mLeft;
15341        out.top = mScrollY;
15342        out.bottom = mScrollY + mBottom - mTop;
15343    }
15344
15345    private void onDrawScrollIndicators(Canvas c) {
15346        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
15347            // No scroll indicators enabled.
15348            return;
15349        }
15350
15351        final Drawable dr = mScrollIndicatorDrawable;
15352        if (dr == null) {
15353            // Scroll indicators aren't supported here.
15354            return;
15355        }
15356
15357        final int h = dr.getIntrinsicHeight();
15358        final int w = dr.getIntrinsicWidth();
15359        final Rect rect = mAttachInfo.mTmpInvalRect;
15360        getScrollIndicatorBounds(rect);
15361
15362        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
15363            final boolean canScrollUp = canScrollVertically(-1);
15364            if (canScrollUp) {
15365                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
15366                dr.draw(c);
15367            }
15368        }
15369
15370        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
15371            final boolean canScrollDown = canScrollVertically(1);
15372            if (canScrollDown) {
15373                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
15374                dr.draw(c);
15375            }
15376        }
15377
15378        final int leftRtl;
15379        final int rightRtl;
15380        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15381            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
15382            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
15383        } else {
15384            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
15385            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
15386        }
15387
15388        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
15389        if ((mPrivateFlags3 & leftMask) != 0) {
15390            final boolean canScrollLeft = canScrollHorizontally(-1);
15391            if (canScrollLeft) {
15392                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
15393                dr.draw(c);
15394            }
15395        }
15396
15397        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
15398        if ((mPrivateFlags3 & rightMask) != 0) {
15399            final boolean canScrollRight = canScrollHorizontally(1);
15400            if (canScrollRight) {
15401                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
15402                dr.draw(c);
15403            }
15404        }
15405    }
15406
15407    private void getHorizontalScrollBarBounds(Rect bounds) {
15408        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15409        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15410                && !isVerticalScrollBarHidden();
15411        final int size = getHorizontalScrollbarHeight();
15412        final int verticalScrollBarGap = drawVerticalScrollBar ?
15413                getVerticalScrollbarWidth() : 0;
15414        final int width = mRight - mLeft;
15415        final int height = mBottom - mTop;
15416        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
15417        bounds.left = mScrollX + (mPaddingLeft & inside);
15418        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
15419        bounds.bottom = bounds.top + size;
15420    }
15421
15422    private void getVerticalScrollBarBounds(Rect bounds) {
15423        if (mRoundScrollbarRenderer == null) {
15424            getStraightVerticalScrollBarBounds(bounds);
15425        } else {
15426            getRoundVerticalScrollBarBounds(bounds);
15427        }
15428    }
15429
15430    private void getRoundVerticalScrollBarBounds(Rect bounds) {
15431        final int width = mRight - mLeft;
15432        final int height = mBottom - mTop;
15433        // Do not take padding into account as we always want the scrollbars
15434        // to hug the screen for round wearable devices.
15435        bounds.left = mScrollX;
15436        bounds.top = mScrollY;
15437        bounds.right = bounds.left + width;
15438        bounds.bottom = mScrollY + height;
15439    }
15440
15441    private void getStraightVerticalScrollBarBounds(Rect bounds) {
15442        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15443        final int size = getVerticalScrollbarWidth();
15444        int verticalScrollbarPosition = mVerticalScrollbarPosition;
15445        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
15446            verticalScrollbarPosition = isLayoutRtl() ?
15447                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
15448        }
15449        final int width = mRight - mLeft;
15450        final int height = mBottom - mTop;
15451        switch (verticalScrollbarPosition) {
15452            default:
15453            case SCROLLBAR_POSITION_RIGHT:
15454                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
15455                break;
15456            case SCROLLBAR_POSITION_LEFT:
15457                bounds.left = mScrollX + (mUserPaddingLeft & inside);
15458                break;
15459        }
15460        bounds.top = mScrollY + (mPaddingTop & inside);
15461        bounds.right = bounds.left + size;
15462        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
15463    }
15464
15465    /**
15466     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
15467     * scrollbars are painted only if they have been awakened first.</p>
15468     *
15469     * @param canvas the canvas on which to draw the scrollbars
15470     *
15471     * @see #awakenScrollBars(int)
15472     */
15473    protected final void onDrawScrollBars(Canvas canvas) {
15474        // scrollbars are drawn only when the animation is running
15475        final ScrollabilityCache cache = mScrollCache;
15476
15477        if (cache != null) {
15478
15479            int state = cache.state;
15480
15481            if (state == ScrollabilityCache.OFF) {
15482                return;
15483            }
15484
15485            boolean invalidate = false;
15486
15487            if (state == ScrollabilityCache.FADING) {
15488                // We're fading -- get our fade interpolation
15489                if (cache.interpolatorValues == null) {
15490                    cache.interpolatorValues = new float[1];
15491                }
15492
15493                float[] values = cache.interpolatorValues;
15494
15495                // Stops the animation if we're done
15496                if (cache.scrollBarInterpolator.timeToValues(values) ==
15497                        Interpolator.Result.FREEZE_END) {
15498                    cache.state = ScrollabilityCache.OFF;
15499                } else {
15500                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
15501                }
15502
15503                // This will make the scroll bars inval themselves after
15504                // drawing. We only want this when we're fading so that
15505                // we prevent excessive redraws
15506                invalidate = true;
15507            } else {
15508                // We're just on -- but we may have been fading before so
15509                // reset alpha
15510                cache.scrollBar.mutate().setAlpha(255);
15511            }
15512
15513            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
15514            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15515                    && !isVerticalScrollBarHidden();
15516
15517            // Fork out the scroll bar drawing for round wearable devices.
15518            if (mRoundScrollbarRenderer != null) {
15519                if (drawVerticalScrollBar) {
15520                    final Rect bounds = cache.mScrollBarBounds;
15521                    getVerticalScrollBarBounds(bounds);
15522                    mRoundScrollbarRenderer.drawRoundScrollbars(
15523                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
15524                    if (invalidate) {
15525                        invalidate();
15526                    }
15527                }
15528                // Do not draw horizontal scroll bars for round wearable devices.
15529            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
15530                final ScrollBarDrawable scrollBar = cache.scrollBar;
15531
15532                if (drawHorizontalScrollBar) {
15533                    scrollBar.setParameters(computeHorizontalScrollRange(),
15534                            computeHorizontalScrollOffset(),
15535                            computeHorizontalScrollExtent(), false);
15536                    final Rect bounds = cache.mScrollBarBounds;
15537                    getHorizontalScrollBarBounds(bounds);
15538                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15539                            bounds.right, bounds.bottom);
15540                    if (invalidate) {
15541                        invalidate(bounds);
15542                    }
15543                }
15544
15545                if (drawVerticalScrollBar) {
15546                    scrollBar.setParameters(computeVerticalScrollRange(),
15547                            computeVerticalScrollOffset(),
15548                            computeVerticalScrollExtent(), true);
15549                    final Rect bounds = cache.mScrollBarBounds;
15550                    getVerticalScrollBarBounds(bounds);
15551                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15552                            bounds.right, bounds.bottom);
15553                    if (invalidate) {
15554                        invalidate(bounds);
15555                    }
15556                }
15557            }
15558        }
15559    }
15560
15561    /**
15562     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
15563     * FastScroller is visible.
15564     * @return whether to temporarily hide the vertical scrollbar
15565     * @hide
15566     */
15567    protected boolean isVerticalScrollBarHidden() {
15568        return false;
15569    }
15570
15571    /**
15572     * <p>Draw the horizontal scrollbar if
15573     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
15574     *
15575     * @param canvas the canvas on which to draw the scrollbar
15576     * @param scrollBar the scrollbar's drawable
15577     *
15578     * @see #isHorizontalScrollBarEnabled()
15579     * @see #computeHorizontalScrollRange()
15580     * @see #computeHorizontalScrollExtent()
15581     * @see #computeHorizontalScrollOffset()
15582     * @see android.widget.ScrollBarDrawable
15583     * @hide
15584     */
15585    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
15586            int l, int t, int r, int b) {
15587        scrollBar.setBounds(l, t, r, b);
15588        scrollBar.draw(canvas);
15589    }
15590
15591    /**
15592     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
15593     * returns true.</p>
15594     *
15595     * @param canvas the canvas on which to draw the scrollbar
15596     * @param scrollBar the scrollbar's drawable
15597     *
15598     * @see #isVerticalScrollBarEnabled()
15599     * @see #computeVerticalScrollRange()
15600     * @see #computeVerticalScrollExtent()
15601     * @see #computeVerticalScrollOffset()
15602     * @see android.widget.ScrollBarDrawable
15603     * @hide
15604     */
15605    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
15606            int l, int t, int r, int b) {
15607        scrollBar.setBounds(l, t, r, b);
15608        scrollBar.draw(canvas);
15609    }
15610
15611    /**
15612     * Implement this to do your drawing.
15613     *
15614     * @param canvas the canvas on which the background will be drawn
15615     */
15616    protected void onDraw(Canvas canvas) {
15617    }
15618
15619    /*
15620     * Caller is responsible for calling requestLayout if necessary.
15621     * (This allows addViewInLayout to not request a new layout.)
15622     */
15623    void assignParent(ViewParent parent) {
15624        if (mParent == null) {
15625            mParent = parent;
15626        } else if (parent == null) {
15627            mParent = null;
15628        } else {
15629            throw new RuntimeException("view " + this + " being added, but"
15630                    + " it already has a parent");
15631        }
15632    }
15633
15634    /**
15635     * This is called when the view is attached to a window.  At this point it
15636     * has a Surface and will start drawing.  Note that this function is
15637     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15638     * however it may be called any time before the first onDraw -- including
15639     * before or after {@link #onMeasure(int, int)}.
15640     *
15641     * @see #onDetachedFromWindow()
15642     */
15643    @CallSuper
15644    protected void onAttachedToWindow() {
15645        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15646            mParent.requestTransparentRegion(this);
15647        }
15648
15649        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15650
15651        jumpDrawablesToCurrentState();
15652
15653        resetSubtreeAccessibilityStateChanged();
15654
15655        // rebuild, since Outline not maintained while View is detached
15656        rebuildOutline();
15657
15658        if (isFocused()) {
15659            InputMethodManager imm = InputMethodManager.peekInstance();
15660            if (imm != null) {
15661                imm.focusIn(this);
15662            }
15663        }
15664    }
15665
15666    /**
15667     * Resolve all RTL related properties.
15668     *
15669     * @return true if resolution of RTL properties has been done
15670     *
15671     * @hide
15672     */
15673    public boolean resolveRtlPropertiesIfNeeded() {
15674        if (!needRtlPropertiesResolution()) return false;
15675
15676        // Order is important here: LayoutDirection MUST be resolved first
15677        if (!isLayoutDirectionResolved()) {
15678            resolveLayoutDirection();
15679            resolveLayoutParams();
15680        }
15681        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15682        if (!isTextDirectionResolved()) {
15683            resolveTextDirection();
15684        }
15685        if (!isTextAlignmentResolved()) {
15686            resolveTextAlignment();
15687        }
15688        // Should resolve Drawables before Padding because we need the layout direction of the
15689        // Drawable to correctly resolve Padding.
15690        if (!areDrawablesResolved()) {
15691            resolveDrawables();
15692        }
15693        if (!isPaddingResolved()) {
15694            resolvePadding();
15695        }
15696        onRtlPropertiesChanged(getLayoutDirection());
15697        return true;
15698    }
15699
15700    /**
15701     * Reset resolution of all RTL related properties.
15702     *
15703     * @hide
15704     */
15705    public void resetRtlProperties() {
15706        resetResolvedLayoutDirection();
15707        resetResolvedTextDirection();
15708        resetResolvedTextAlignment();
15709        resetResolvedPadding();
15710        resetResolvedDrawables();
15711    }
15712
15713    /**
15714     * @see #onScreenStateChanged(int)
15715     */
15716    void dispatchScreenStateChanged(int screenState) {
15717        onScreenStateChanged(screenState);
15718    }
15719
15720    /**
15721     * This method is called whenever the state of the screen this view is
15722     * attached to changes. A state change will usually occurs when the screen
15723     * turns on or off (whether it happens automatically or the user does it
15724     * manually.)
15725     *
15726     * @param screenState The new state of the screen. Can be either
15727     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15728     */
15729    public void onScreenStateChanged(int screenState) {
15730    }
15731
15732    /**
15733     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
15734     */
15735    private boolean hasRtlSupport() {
15736        return mContext.getApplicationInfo().hasRtlSupport();
15737    }
15738
15739    /**
15740     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15741     * RTL not supported)
15742     */
15743    private boolean isRtlCompatibilityMode() {
15744        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15745        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15746    }
15747
15748    /**
15749     * @return true if RTL properties need resolution.
15750     *
15751     */
15752    private boolean needRtlPropertiesResolution() {
15753        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15754    }
15755
15756    /**
15757     * Called when any RTL property (layout direction or text direction or text alignment) has
15758     * been changed.
15759     *
15760     * Subclasses need to override this method to take care of cached information that depends on the
15761     * resolved layout direction, or to inform child views that inherit their layout direction.
15762     *
15763     * The default implementation does nothing.
15764     *
15765     * @param layoutDirection the direction of the layout
15766     *
15767     * @see #LAYOUT_DIRECTION_LTR
15768     * @see #LAYOUT_DIRECTION_RTL
15769     */
15770    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15771    }
15772
15773    /**
15774     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15775     * that the parent directionality can and will be resolved before its children.
15776     *
15777     * @return true if resolution has been done, false otherwise.
15778     *
15779     * @hide
15780     */
15781    public boolean resolveLayoutDirection() {
15782        // Clear any previous layout direction resolution
15783        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15784
15785        if (hasRtlSupport()) {
15786            // Set resolved depending on layout direction
15787            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15788                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15789                case LAYOUT_DIRECTION_INHERIT:
15790                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15791                    // later to get the correct resolved value
15792                    if (!canResolveLayoutDirection()) return false;
15793
15794                    // Parent has not yet resolved, LTR is still the default
15795                    try {
15796                        if (!mParent.isLayoutDirectionResolved()) return false;
15797
15798                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15799                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15800                        }
15801                    } catch (AbstractMethodError e) {
15802                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15803                                " does not fully implement ViewParent", e);
15804                    }
15805                    break;
15806                case LAYOUT_DIRECTION_RTL:
15807                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15808                    break;
15809                case LAYOUT_DIRECTION_LOCALE:
15810                    if((LAYOUT_DIRECTION_RTL ==
15811                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15812                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15813                    }
15814                    break;
15815                default:
15816                    // Nothing to do, LTR by default
15817            }
15818        }
15819
15820        // Set to resolved
15821        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15822        return true;
15823    }
15824
15825    /**
15826     * Check if layout direction resolution can be done.
15827     *
15828     * @return true if layout direction resolution can be done otherwise return false.
15829     */
15830    public boolean canResolveLayoutDirection() {
15831        switch (getRawLayoutDirection()) {
15832            case LAYOUT_DIRECTION_INHERIT:
15833                if (mParent != null) {
15834                    try {
15835                        return mParent.canResolveLayoutDirection();
15836                    } catch (AbstractMethodError e) {
15837                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15838                                " does not fully implement ViewParent", e);
15839                    }
15840                }
15841                return false;
15842
15843            default:
15844                return true;
15845        }
15846    }
15847
15848    /**
15849     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15850     * {@link #onMeasure(int, int)}.
15851     *
15852     * @hide
15853     */
15854    public void resetResolvedLayoutDirection() {
15855        // Reset the current resolved bits
15856        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15857    }
15858
15859    /**
15860     * @return true if the layout direction is inherited.
15861     *
15862     * @hide
15863     */
15864    public boolean isLayoutDirectionInherited() {
15865        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15866    }
15867
15868    /**
15869     * @return true if layout direction has been resolved.
15870     */
15871    public boolean isLayoutDirectionResolved() {
15872        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15873    }
15874
15875    /**
15876     * Return if padding has been resolved
15877     *
15878     * @hide
15879     */
15880    boolean isPaddingResolved() {
15881        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15882    }
15883
15884    /**
15885     * Resolves padding depending on layout direction, if applicable, and
15886     * recomputes internal padding values to adjust for scroll bars.
15887     *
15888     * @hide
15889     */
15890    public void resolvePadding() {
15891        final int resolvedLayoutDirection = getLayoutDirection();
15892
15893        if (!isRtlCompatibilityMode()) {
15894            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15895            // If start / end padding are defined, they will be resolved (hence overriding) to
15896            // left / right or right / left depending on the resolved layout direction.
15897            // If start / end padding are not defined, use the left / right ones.
15898            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15899                Rect padding = sThreadLocal.get();
15900                if (padding == null) {
15901                    padding = new Rect();
15902                    sThreadLocal.set(padding);
15903                }
15904                mBackground.getPadding(padding);
15905                if (!mLeftPaddingDefined) {
15906                    mUserPaddingLeftInitial = padding.left;
15907                }
15908                if (!mRightPaddingDefined) {
15909                    mUserPaddingRightInitial = padding.right;
15910                }
15911            }
15912            switch (resolvedLayoutDirection) {
15913                case LAYOUT_DIRECTION_RTL:
15914                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15915                        mUserPaddingRight = mUserPaddingStart;
15916                    } else {
15917                        mUserPaddingRight = mUserPaddingRightInitial;
15918                    }
15919                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15920                        mUserPaddingLeft = mUserPaddingEnd;
15921                    } else {
15922                        mUserPaddingLeft = mUserPaddingLeftInitial;
15923                    }
15924                    break;
15925                case LAYOUT_DIRECTION_LTR:
15926                default:
15927                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15928                        mUserPaddingLeft = mUserPaddingStart;
15929                    } else {
15930                        mUserPaddingLeft = mUserPaddingLeftInitial;
15931                    }
15932                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15933                        mUserPaddingRight = mUserPaddingEnd;
15934                    } else {
15935                        mUserPaddingRight = mUserPaddingRightInitial;
15936                    }
15937            }
15938
15939            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15940        }
15941
15942        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15943        onRtlPropertiesChanged(resolvedLayoutDirection);
15944
15945        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15946    }
15947
15948    /**
15949     * Reset the resolved layout direction.
15950     *
15951     * @hide
15952     */
15953    public void resetResolvedPadding() {
15954        resetResolvedPaddingInternal();
15955    }
15956
15957    /**
15958     * Used when we only want to reset *this* view's padding and not trigger overrides
15959     * in ViewGroup that reset children too.
15960     */
15961    void resetResolvedPaddingInternal() {
15962        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15963    }
15964
15965    /**
15966     * This is called when the view is detached from a window.  At this point it
15967     * no longer has a surface for drawing.
15968     *
15969     * @see #onAttachedToWindow()
15970     */
15971    @CallSuper
15972    protected void onDetachedFromWindow() {
15973    }
15974
15975    /**
15976     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15977     * after onDetachedFromWindow().
15978     *
15979     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15980     * The super method should be called at the end of the overridden method to ensure
15981     * subclasses are destroyed first
15982     *
15983     * @hide
15984     */
15985    @CallSuper
15986    protected void onDetachedFromWindowInternal() {
15987        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15988        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15989        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15990
15991        removeUnsetPressCallback();
15992        removeLongPressCallback();
15993        removePerformClickCallback();
15994        removeSendViewScrolledAccessibilityEventCallback();
15995        stopNestedScroll();
15996
15997        // Anything that started animating right before detach should already
15998        // be in its final state when re-attached.
15999        jumpDrawablesToCurrentState();
16000
16001        destroyDrawingCache();
16002
16003        cleanupDraw();
16004        mCurrentAnimation = null;
16005
16006        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
16007            hideTooltip();
16008        }
16009    }
16010
16011    private void cleanupDraw() {
16012        resetDisplayList();
16013        if (mAttachInfo != null) {
16014            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
16015        }
16016    }
16017
16018    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
16019    }
16020
16021    /**
16022     * @return The number of times this view has been attached to a window
16023     */
16024    protected int getWindowAttachCount() {
16025        return mWindowAttachCount;
16026    }
16027
16028    /**
16029     * Retrieve a unique token identifying the window this view is attached to.
16030     * @return Return the window's token for use in
16031     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
16032     */
16033    public IBinder getWindowToken() {
16034        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
16035    }
16036
16037    /**
16038     * Retrieve the {@link WindowId} for the window this view is
16039     * currently attached to.
16040     */
16041    public WindowId getWindowId() {
16042        if (mAttachInfo == null) {
16043            return null;
16044        }
16045        if (mAttachInfo.mWindowId == null) {
16046            try {
16047                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
16048                        mAttachInfo.mWindowToken);
16049                mAttachInfo.mWindowId = new WindowId(
16050                        mAttachInfo.mIWindowId);
16051            } catch (RemoteException e) {
16052            }
16053        }
16054        return mAttachInfo.mWindowId;
16055    }
16056
16057    /**
16058     * Retrieve a unique token identifying the top-level "real" window of
16059     * the window that this view is attached to.  That is, this is like
16060     * {@link #getWindowToken}, except if the window this view in is a panel
16061     * window (attached to another containing window), then the token of
16062     * the containing window is returned instead.
16063     *
16064     * @return Returns the associated window token, either
16065     * {@link #getWindowToken()} or the containing window's token.
16066     */
16067    public IBinder getApplicationWindowToken() {
16068        AttachInfo ai = mAttachInfo;
16069        if (ai != null) {
16070            IBinder appWindowToken = ai.mPanelParentWindowToken;
16071            if (appWindowToken == null) {
16072                appWindowToken = ai.mWindowToken;
16073            }
16074            return appWindowToken;
16075        }
16076        return null;
16077    }
16078
16079    /**
16080     * Gets the logical display to which the view's window has been attached.
16081     *
16082     * @return The logical display, or null if the view is not currently attached to a window.
16083     */
16084    public Display getDisplay() {
16085        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
16086    }
16087
16088    /**
16089     * Retrieve private session object this view hierarchy is using to
16090     * communicate with the window manager.
16091     * @return the session object to communicate with the window manager
16092     */
16093    /*package*/ IWindowSession getWindowSession() {
16094        return mAttachInfo != null ? mAttachInfo.mSession : null;
16095    }
16096
16097    /**
16098     * Return the visibility value of the least visible component passed.
16099     */
16100    int combineVisibility(int vis1, int vis2) {
16101        // This works because VISIBLE < INVISIBLE < GONE.
16102        return Math.max(vis1, vis2);
16103    }
16104
16105    /**
16106     * @param info the {@link android.view.View.AttachInfo} to associated with
16107     *        this view
16108     */
16109    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
16110        mAttachInfo = info;
16111        if (mOverlay != null) {
16112            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
16113        }
16114        mWindowAttachCount++;
16115        // We will need to evaluate the drawable state at least once.
16116        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16117        if (mFloatingTreeObserver != null) {
16118            info.mTreeObserver.merge(mFloatingTreeObserver);
16119            mFloatingTreeObserver = null;
16120        }
16121
16122        registerPendingFrameMetricsObservers();
16123
16124        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
16125            mAttachInfo.mScrollContainers.add(this);
16126            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
16127        }
16128        // Transfer all pending runnables.
16129        if (mRunQueue != null) {
16130            mRunQueue.executeActions(info.mHandler);
16131            mRunQueue = null;
16132        }
16133        performCollectViewAttributes(mAttachInfo, visibility);
16134        onAttachedToWindow();
16135
16136        ListenerInfo li = mListenerInfo;
16137        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16138                li != null ? li.mOnAttachStateChangeListeners : null;
16139        if (listeners != null && listeners.size() > 0) {
16140            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16141            // perform the dispatching. The iterator is a safe guard against listeners that
16142            // could mutate the list by calling the various add/remove methods. This prevents
16143            // the array from being modified while we iterate it.
16144            for (OnAttachStateChangeListener listener : listeners) {
16145                listener.onViewAttachedToWindow(this);
16146            }
16147        }
16148
16149        int vis = info.mWindowVisibility;
16150        if (vis != GONE) {
16151            onWindowVisibilityChanged(vis);
16152            if (isShown()) {
16153                // Calling onVisibilityAggregated directly here since the subtree will also
16154                // receive dispatchAttachedToWindow and this same call
16155                onVisibilityAggregated(vis == VISIBLE);
16156            }
16157        }
16158
16159        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
16160        // As all views in the subtree will already receive dispatchAttachedToWindow
16161        // traversing the subtree again here is not desired.
16162        onVisibilityChanged(this, visibility);
16163
16164        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
16165            // If nobody has evaluated the drawable state yet, then do it now.
16166            refreshDrawableState();
16167        }
16168        needGlobalAttributesUpdate(false);
16169    }
16170
16171    void dispatchDetachedFromWindow() {
16172        AttachInfo info = mAttachInfo;
16173        if (info != null) {
16174            int vis = info.mWindowVisibility;
16175            if (vis != GONE) {
16176                onWindowVisibilityChanged(GONE);
16177                if (isShown()) {
16178                    // Invoking onVisibilityAggregated directly here since the subtree
16179                    // will also receive detached from window
16180                    onVisibilityAggregated(false);
16181                }
16182            }
16183        }
16184
16185        onDetachedFromWindow();
16186        onDetachedFromWindowInternal();
16187
16188        InputMethodManager imm = InputMethodManager.peekInstance();
16189        if (imm != null) {
16190            imm.onViewDetachedFromWindow(this);
16191        }
16192
16193        ListenerInfo li = mListenerInfo;
16194        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16195                li != null ? li.mOnAttachStateChangeListeners : null;
16196        if (listeners != null && listeners.size() > 0) {
16197            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16198            // perform the dispatching. The iterator is a safe guard against listeners that
16199            // could mutate the list by calling the various add/remove methods. This prevents
16200            // the array from being modified while we iterate it.
16201            for (OnAttachStateChangeListener listener : listeners) {
16202                listener.onViewDetachedFromWindow(this);
16203            }
16204        }
16205
16206        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
16207            mAttachInfo.mScrollContainers.remove(this);
16208            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
16209        }
16210
16211        mAttachInfo = null;
16212        if (mOverlay != null) {
16213            mOverlay.getOverlayView().dispatchDetachedFromWindow();
16214        }
16215    }
16216
16217    /**
16218     * Cancel any deferred high-level input events that were previously posted to the event queue.
16219     *
16220     * <p>Many views post high-level events such as click handlers to the event queue
16221     * to run deferred in order to preserve a desired user experience - clearing visible
16222     * pressed states before executing, etc. This method will abort any events of this nature
16223     * that are currently in flight.</p>
16224     *
16225     * <p>Custom views that generate their own high-level deferred input events should override
16226     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
16227     *
16228     * <p>This will also cancel pending input events for any child views.</p>
16229     *
16230     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
16231     * This will not impact newer events posted after this call that may occur as a result of
16232     * lower-level input events still waiting in the queue. If you are trying to prevent
16233     * double-submitted  events for the duration of some sort of asynchronous transaction
16234     * you should also take other steps to protect against unexpected double inputs e.g. calling
16235     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
16236     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
16237     */
16238    public final void cancelPendingInputEvents() {
16239        dispatchCancelPendingInputEvents();
16240    }
16241
16242    /**
16243     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
16244     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
16245     */
16246    void dispatchCancelPendingInputEvents() {
16247        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
16248        onCancelPendingInputEvents();
16249        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
16250            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
16251                    " did not call through to super.onCancelPendingInputEvents()");
16252        }
16253    }
16254
16255    /**
16256     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
16257     * a parent view.
16258     *
16259     * <p>This method is responsible for removing any pending high-level input events that were
16260     * posted to the event queue to run later. Custom view classes that post their own deferred
16261     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
16262     * {@link android.os.Handler} should override this method, call
16263     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
16264     * </p>
16265     */
16266    public void onCancelPendingInputEvents() {
16267        removePerformClickCallback();
16268        cancelLongPress();
16269        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
16270    }
16271
16272    /**
16273     * Store this view hierarchy's frozen state into the given container.
16274     *
16275     * @param container The SparseArray in which to save the view's state.
16276     *
16277     * @see #restoreHierarchyState(android.util.SparseArray)
16278     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16279     * @see #onSaveInstanceState()
16280     */
16281    public void saveHierarchyState(SparseArray<Parcelable> container) {
16282        dispatchSaveInstanceState(container);
16283    }
16284
16285    /**
16286     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
16287     * this view and its children. May be overridden to modify how freezing happens to a
16288     * view's children; for example, some views may want to not store state for their children.
16289     *
16290     * @param container The SparseArray in which to save the view's state.
16291     *
16292     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16293     * @see #saveHierarchyState(android.util.SparseArray)
16294     * @see #onSaveInstanceState()
16295     */
16296    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
16297        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
16298            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16299            Parcelable state = onSaveInstanceState();
16300            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16301                throw new IllegalStateException(
16302                        "Derived class did not call super.onSaveInstanceState()");
16303            }
16304            if (state != null) {
16305                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
16306                // + ": " + state);
16307                container.put(mID, state);
16308            }
16309        }
16310    }
16311
16312    /**
16313     * Hook allowing a view to generate a representation of its internal state
16314     * that can later be used to create a new instance with that same state.
16315     * This state should only contain information that is not persistent or can
16316     * not be reconstructed later. For example, you will never store your
16317     * current position on screen because that will be computed again when a
16318     * new instance of the view is placed in its view hierarchy.
16319     * <p>
16320     * Some examples of things you may store here: the current cursor position
16321     * in a text view (but usually not the text itself since that is stored in a
16322     * content provider or other persistent storage), the currently selected
16323     * item in a list view.
16324     *
16325     * @return Returns a Parcelable object containing the view's current dynamic
16326     *         state, or null if there is nothing interesting to save. The
16327     *         default implementation returns null.
16328     * @see #onRestoreInstanceState(android.os.Parcelable)
16329     * @see #saveHierarchyState(android.util.SparseArray)
16330     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16331     * @see #setSaveEnabled(boolean)
16332     */
16333    @CallSuper
16334    protected Parcelable onSaveInstanceState() {
16335        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16336        if (mStartActivityRequestWho != null) {
16337            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
16338            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
16339            return state;
16340        }
16341        return BaseSavedState.EMPTY_STATE;
16342    }
16343
16344    /**
16345     * Restore this view hierarchy's frozen state from the given container.
16346     *
16347     * @param container The SparseArray which holds previously frozen states.
16348     *
16349     * @see #saveHierarchyState(android.util.SparseArray)
16350     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16351     * @see #onRestoreInstanceState(android.os.Parcelable)
16352     */
16353    public void restoreHierarchyState(SparseArray<Parcelable> container) {
16354        dispatchRestoreInstanceState(container);
16355    }
16356
16357    /**
16358     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
16359     * state for this view and its children. May be overridden to modify how restoring
16360     * happens to a view's children; for example, some views may want to not store state
16361     * for their children.
16362     *
16363     * @param container The SparseArray which holds previously saved state.
16364     *
16365     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16366     * @see #restoreHierarchyState(android.util.SparseArray)
16367     * @see #onRestoreInstanceState(android.os.Parcelable)
16368     */
16369    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
16370        if (mID != NO_ID) {
16371            Parcelable state = container.get(mID);
16372            if (state != null) {
16373                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
16374                // + ": " + state);
16375                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16376                onRestoreInstanceState(state);
16377                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16378                    throw new IllegalStateException(
16379                            "Derived class did not call super.onRestoreInstanceState()");
16380                }
16381            }
16382        }
16383    }
16384
16385    /**
16386     * Hook allowing a view to re-apply a representation of its internal state that had previously
16387     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
16388     * null state.
16389     *
16390     * @param state The frozen state that had previously been returned by
16391     *        {@link #onSaveInstanceState}.
16392     *
16393     * @see #onSaveInstanceState()
16394     * @see #restoreHierarchyState(android.util.SparseArray)
16395     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16396     */
16397    @CallSuper
16398    protected void onRestoreInstanceState(Parcelable state) {
16399        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16400        if (state != null && !(state instanceof AbsSavedState)) {
16401            throw new IllegalArgumentException("Wrong state class, expecting View State but "
16402                    + "received " + state.getClass().toString() + " instead. This usually happens "
16403                    + "when two views of different type have the same id in the same hierarchy. "
16404                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
16405                    + "other views do not use the same id.");
16406        }
16407        if (state != null && state instanceof BaseSavedState) {
16408            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
16409        }
16410    }
16411
16412    /**
16413     * <p>Return the time at which the drawing of the view hierarchy started.</p>
16414     *
16415     * @return the drawing start time in milliseconds
16416     */
16417    public long getDrawingTime() {
16418        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
16419    }
16420
16421    /**
16422     * <p>Enables or disables the duplication of the parent's state into this view. When
16423     * duplication is enabled, this view gets its drawable state from its parent rather
16424     * than from its own internal properties.</p>
16425     *
16426     * <p>Note: in the current implementation, setting this property to true after the
16427     * view was added to a ViewGroup might have no effect at all. This property should
16428     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
16429     *
16430     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
16431     * property is enabled, an exception will be thrown.</p>
16432     *
16433     * <p>Note: if the child view uses and updates additional states which are unknown to the
16434     * parent, these states should not be affected by this method.</p>
16435     *
16436     * @param enabled True to enable duplication of the parent's drawable state, false
16437     *                to disable it.
16438     *
16439     * @see #getDrawableState()
16440     * @see #isDuplicateParentStateEnabled()
16441     */
16442    public void setDuplicateParentStateEnabled(boolean enabled) {
16443        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
16444    }
16445
16446    /**
16447     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
16448     *
16449     * @return True if this view's drawable state is duplicated from the parent,
16450     *         false otherwise
16451     *
16452     * @see #getDrawableState()
16453     * @see #setDuplicateParentStateEnabled(boolean)
16454     */
16455    public boolean isDuplicateParentStateEnabled() {
16456        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
16457    }
16458
16459    /**
16460     * <p>Specifies the type of layer backing this view. The layer can be
16461     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16462     * {@link #LAYER_TYPE_HARDWARE}.</p>
16463     *
16464     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16465     * instance that controls how the layer is composed on screen. The following
16466     * properties of the paint are taken into account when composing the layer:</p>
16467     * <ul>
16468     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16469     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16470     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16471     * </ul>
16472     *
16473     * <p>If this view has an alpha value set to < 1.0 by calling
16474     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
16475     * by this view's alpha value.</p>
16476     *
16477     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
16478     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
16479     * for more information on when and how to use layers.</p>
16480     *
16481     * @param layerType The type of layer to use with this view, must be one of
16482     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16483     *        {@link #LAYER_TYPE_HARDWARE}
16484     * @param paint The paint used to compose the layer. This argument is optional
16485     *        and can be null. It is ignored when the layer type is
16486     *        {@link #LAYER_TYPE_NONE}
16487     *
16488     * @see #getLayerType()
16489     * @see #LAYER_TYPE_NONE
16490     * @see #LAYER_TYPE_SOFTWARE
16491     * @see #LAYER_TYPE_HARDWARE
16492     * @see #setAlpha(float)
16493     *
16494     * @attr ref android.R.styleable#View_layerType
16495     */
16496    public void setLayerType(int layerType, @Nullable Paint paint) {
16497        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
16498            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
16499                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
16500        }
16501
16502        boolean typeChanged = mRenderNode.setLayerType(layerType);
16503
16504        if (!typeChanged) {
16505            setLayerPaint(paint);
16506            return;
16507        }
16508
16509        if (layerType != LAYER_TYPE_SOFTWARE) {
16510            // Destroy any previous software drawing cache if present
16511            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
16512            // drawing cache created in View#draw when drawing to a SW canvas.
16513            destroyDrawingCache();
16514        }
16515
16516        mLayerType = layerType;
16517        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
16518        mRenderNode.setLayerPaint(mLayerPaint);
16519
16520        // draw() behaves differently if we are on a layer, so we need to
16521        // invalidate() here
16522        invalidateParentCaches();
16523        invalidate(true);
16524    }
16525
16526    /**
16527     * Updates the {@link Paint} object used with the current layer (used only if the current
16528     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
16529     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
16530     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
16531     * ensure that the view gets redrawn immediately.
16532     *
16533     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16534     * instance that controls how the layer is composed on screen. The following
16535     * properties of the paint are taken into account when composing the layer:</p>
16536     * <ul>
16537     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16538     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16539     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16540     * </ul>
16541     *
16542     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
16543     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
16544     *
16545     * @param paint The paint used to compose the layer. This argument is optional
16546     *        and can be null. It is ignored when the layer type is
16547     *        {@link #LAYER_TYPE_NONE}
16548     *
16549     * @see #setLayerType(int, android.graphics.Paint)
16550     */
16551    public void setLayerPaint(@Nullable Paint paint) {
16552        int layerType = getLayerType();
16553        if (layerType != LAYER_TYPE_NONE) {
16554            mLayerPaint = paint;
16555            if (layerType == LAYER_TYPE_HARDWARE) {
16556                if (mRenderNode.setLayerPaint(paint)) {
16557                    invalidateViewProperty(false, false);
16558                }
16559            } else {
16560                invalidate();
16561            }
16562        }
16563    }
16564
16565    /**
16566     * Indicates what type of layer is currently associated with this view. By default
16567     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
16568     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
16569     * for more information on the different types of layers.
16570     *
16571     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16572     *         {@link #LAYER_TYPE_HARDWARE}
16573     *
16574     * @see #setLayerType(int, android.graphics.Paint)
16575     * @see #buildLayer()
16576     * @see #LAYER_TYPE_NONE
16577     * @see #LAYER_TYPE_SOFTWARE
16578     * @see #LAYER_TYPE_HARDWARE
16579     */
16580    public int getLayerType() {
16581        return mLayerType;
16582    }
16583
16584    /**
16585     * Forces this view's layer to be created and this view to be rendered
16586     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
16587     * invoking this method will have no effect.
16588     *
16589     * This method can for instance be used to render a view into its layer before
16590     * starting an animation. If this view is complex, rendering into the layer
16591     * before starting the animation will avoid skipping frames.
16592     *
16593     * @throws IllegalStateException If this view is not attached to a window
16594     *
16595     * @see #setLayerType(int, android.graphics.Paint)
16596     */
16597    public void buildLayer() {
16598        if (mLayerType == LAYER_TYPE_NONE) return;
16599
16600        final AttachInfo attachInfo = mAttachInfo;
16601        if (attachInfo == null) {
16602            throw new IllegalStateException("This view must be attached to a window first");
16603        }
16604
16605        if (getWidth() == 0 || getHeight() == 0) {
16606            return;
16607        }
16608
16609        switch (mLayerType) {
16610            case LAYER_TYPE_HARDWARE:
16611                updateDisplayListIfDirty();
16612                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
16613                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
16614                }
16615                break;
16616            case LAYER_TYPE_SOFTWARE:
16617                buildDrawingCache(true);
16618                break;
16619        }
16620    }
16621
16622    /**
16623     * Destroys all hardware rendering resources. This method is invoked
16624     * when the system needs to reclaim resources. Upon execution of this
16625     * method, you should free any OpenGL resources created by the view.
16626     *
16627     * Note: you <strong>must</strong> call
16628     * <code>super.destroyHardwareResources()</code> when overriding
16629     * this method.
16630     *
16631     * @hide
16632     */
16633    @CallSuper
16634    protected void destroyHardwareResources() {
16635        if (mOverlay != null) {
16636            mOverlay.getOverlayView().destroyHardwareResources();
16637        }
16638        if (mGhostView != null) {
16639            mGhostView.destroyHardwareResources();
16640        }
16641    }
16642
16643    /**
16644     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16645     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16646     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16647     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16648     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16649     * null.</p>
16650     *
16651     * <p>Enabling the drawing cache is similar to
16652     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16653     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16654     * drawing cache has no effect on rendering because the system uses a different mechanism
16655     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16656     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16657     * for information on how to enable software and hardware layers.</p>
16658     *
16659     * <p>This API can be used to manually generate
16660     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16661     * {@link #getDrawingCache()}.</p>
16662     *
16663     * @param enabled true to enable the drawing cache, false otherwise
16664     *
16665     * @see #isDrawingCacheEnabled()
16666     * @see #getDrawingCache()
16667     * @see #buildDrawingCache()
16668     * @see #setLayerType(int, android.graphics.Paint)
16669     */
16670    public void setDrawingCacheEnabled(boolean enabled) {
16671        mCachingFailed = false;
16672        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16673    }
16674
16675    /**
16676     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16677     *
16678     * @return true if the drawing cache is enabled
16679     *
16680     * @see #setDrawingCacheEnabled(boolean)
16681     * @see #getDrawingCache()
16682     */
16683    @ViewDebug.ExportedProperty(category = "drawing")
16684    public boolean isDrawingCacheEnabled() {
16685        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16686    }
16687
16688    /**
16689     * Debugging utility which recursively outputs the dirty state of a view and its
16690     * descendants.
16691     *
16692     * @hide
16693     */
16694    @SuppressWarnings({"UnusedDeclaration"})
16695    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16696        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16697                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16698                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16699                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16700        if (clear) {
16701            mPrivateFlags &= clearMask;
16702        }
16703        if (this instanceof ViewGroup) {
16704            ViewGroup parent = (ViewGroup) this;
16705            final int count = parent.getChildCount();
16706            for (int i = 0; i < count; i++) {
16707                final View child = parent.getChildAt(i);
16708                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16709            }
16710        }
16711    }
16712
16713    /**
16714     * This method is used by ViewGroup to cause its children to restore or recreate their
16715     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16716     * to recreate its own display list, which would happen if it went through the normal
16717     * draw/dispatchDraw mechanisms.
16718     *
16719     * @hide
16720     */
16721    protected void dispatchGetDisplayList() {}
16722
16723    /**
16724     * A view that is not attached or hardware accelerated cannot create a display list.
16725     * This method checks these conditions and returns the appropriate result.
16726     *
16727     * @return true if view has the ability to create a display list, false otherwise.
16728     *
16729     * @hide
16730     */
16731    public boolean canHaveDisplayList() {
16732        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
16733    }
16734
16735    /**
16736     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
16737     * @hide
16738     */
16739    @NonNull
16740    public RenderNode updateDisplayListIfDirty() {
16741        final RenderNode renderNode = mRenderNode;
16742        if (!canHaveDisplayList()) {
16743            // can't populate RenderNode, don't try
16744            return renderNode;
16745        }
16746
16747        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16748                || !renderNode.isValid()
16749                || (mRecreateDisplayList)) {
16750            // Don't need to recreate the display list, just need to tell our
16751            // children to restore/recreate theirs
16752            if (renderNode.isValid()
16753                    && !mRecreateDisplayList) {
16754                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16755                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16756                dispatchGetDisplayList();
16757
16758                return renderNode; // no work needed
16759            }
16760
16761            // If we got here, we're recreating it. Mark it as such to ensure that
16762            // we copy in child display lists into ours in drawChild()
16763            mRecreateDisplayList = true;
16764
16765            int width = mRight - mLeft;
16766            int height = mBottom - mTop;
16767            int layerType = getLayerType();
16768
16769            final DisplayListCanvas canvas = renderNode.start(width, height);
16770            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16771
16772            try {
16773                if (layerType == LAYER_TYPE_SOFTWARE) {
16774                    buildDrawingCache(true);
16775                    Bitmap cache = getDrawingCache(true);
16776                    if (cache != null) {
16777                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16778                    }
16779                } else {
16780                    computeScroll();
16781
16782                    canvas.translate(-mScrollX, -mScrollY);
16783                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16784                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16785
16786                    // Fast path for layouts with no backgrounds
16787                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16788                        dispatchDraw(canvas);
16789                        if (mOverlay != null && !mOverlay.isEmpty()) {
16790                            mOverlay.getOverlayView().draw(canvas);
16791                        }
16792                        if (debugDraw()) {
16793                            debugDrawFocus(canvas);
16794                        }
16795                    } else {
16796                        draw(canvas);
16797                    }
16798                }
16799            } finally {
16800                renderNode.end(canvas);
16801                setDisplayListProperties(renderNode);
16802            }
16803        } else {
16804            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16805            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16806        }
16807        return renderNode;
16808    }
16809
16810    private void resetDisplayList() {
16811        mRenderNode.discardDisplayList();
16812        if (mBackgroundRenderNode != null) {
16813            mBackgroundRenderNode.discardDisplayList();
16814        }
16815    }
16816
16817    /**
16818     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16819     *
16820     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16821     *
16822     * @see #getDrawingCache(boolean)
16823     */
16824    public Bitmap getDrawingCache() {
16825        return getDrawingCache(false);
16826    }
16827
16828    /**
16829     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16830     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16831     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16832     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16833     * request the drawing cache by calling this method and draw it on screen if the
16834     * returned bitmap is not null.</p>
16835     *
16836     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16837     * this method will create a bitmap of the same size as this view. Because this bitmap
16838     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16839     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16840     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16841     * size than the view. This implies that your application must be able to handle this
16842     * size.</p>
16843     *
16844     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16845     *        the current density of the screen when the application is in compatibility
16846     *        mode.
16847     *
16848     * @return A bitmap representing this view or null if cache is disabled.
16849     *
16850     * @see #setDrawingCacheEnabled(boolean)
16851     * @see #isDrawingCacheEnabled()
16852     * @see #buildDrawingCache(boolean)
16853     * @see #destroyDrawingCache()
16854     */
16855    public Bitmap getDrawingCache(boolean autoScale) {
16856        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16857            return null;
16858        }
16859        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16860            buildDrawingCache(autoScale);
16861        }
16862        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16863    }
16864
16865    /**
16866     * <p>Frees the resources used by the drawing cache. If you call
16867     * {@link #buildDrawingCache()} manually without calling
16868     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16869     * should cleanup the cache with this method afterwards.</p>
16870     *
16871     * @see #setDrawingCacheEnabled(boolean)
16872     * @see #buildDrawingCache()
16873     * @see #getDrawingCache()
16874     */
16875    public void destroyDrawingCache() {
16876        if (mDrawingCache != null) {
16877            mDrawingCache.recycle();
16878            mDrawingCache = null;
16879        }
16880        if (mUnscaledDrawingCache != null) {
16881            mUnscaledDrawingCache.recycle();
16882            mUnscaledDrawingCache = null;
16883        }
16884    }
16885
16886    /**
16887     * Setting a solid background color for the drawing cache's bitmaps will improve
16888     * performance and memory usage. Note, though that this should only be used if this
16889     * view will always be drawn on top of a solid color.
16890     *
16891     * @param color The background color to use for the drawing cache's bitmap
16892     *
16893     * @see #setDrawingCacheEnabled(boolean)
16894     * @see #buildDrawingCache()
16895     * @see #getDrawingCache()
16896     */
16897    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16898        if (color != mDrawingCacheBackgroundColor) {
16899            mDrawingCacheBackgroundColor = color;
16900            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16901        }
16902    }
16903
16904    /**
16905     * @see #setDrawingCacheBackgroundColor(int)
16906     *
16907     * @return The background color to used for the drawing cache's bitmap
16908     */
16909    @ColorInt
16910    public int getDrawingCacheBackgroundColor() {
16911        return mDrawingCacheBackgroundColor;
16912    }
16913
16914    /**
16915     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16916     *
16917     * @see #buildDrawingCache(boolean)
16918     */
16919    public void buildDrawingCache() {
16920        buildDrawingCache(false);
16921    }
16922
16923    /**
16924     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16925     *
16926     * <p>If you call {@link #buildDrawingCache()} manually without calling
16927     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16928     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16929     *
16930     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16931     * this method will create a bitmap of the same size as this view. Because this bitmap
16932     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16933     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16934     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16935     * size than the view. This implies that your application must be able to handle this
16936     * size.</p>
16937     *
16938     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16939     * you do not need the drawing cache bitmap, calling this method will increase memory
16940     * usage and cause the view to be rendered in software once, thus negatively impacting
16941     * performance.</p>
16942     *
16943     * @see #getDrawingCache()
16944     * @see #destroyDrawingCache()
16945     */
16946    public void buildDrawingCache(boolean autoScale) {
16947        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16948                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16949            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16950                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16951                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16952            }
16953            try {
16954                buildDrawingCacheImpl(autoScale);
16955            } finally {
16956                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16957            }
16958        }
16959    }
16960
16961    /**
16962     * private, internal implementation of buildDrawingCache, used to enable tracing
16963     */
16964    private void buildDrawingCacheImpl(boolean autoScale) {
16965        mCachingFailed = false;
16966
16967        int width = mRight - mLeft;
16968        int height = mBottom - mTop;
16969
16970        final AttachInfo attachInfo = mAttachInfo;
16971        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16972
16973        if (autoScale && scalingRequired) {
16974            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16975            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16976        }
16977
16978        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16979        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16980        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16981
16982        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16983        final long drawingCacheSize =
16984                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16985        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16986            if (width > 0 && height > 0) {
16987                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16988                        + " too large to fit into a software layer (or drawing cache), needs "
16989                        + projectedBitmapSize + " bytes, only "
16990                        + drawingCacheSize + " available");
16991            }
16992            destroyDrawingCache();
16993            mCachingFailed = true;
16994            return;
16995        }
16996
16997        boolean clear = true;
16998        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16999
17000        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
17001            Bitmap.Config quality;
17002            if (!opaque) {
17003                // Never pick ARGB_4444 because it looks awful
17004                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
17005                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
17006                    case DRAWING_CACHE_QUALITY_AUTO:
17007                    case DRAWING_CACHE_QUALITY_LOW:
17008                    case DRAWING_CACHE_QUALITY_HIGH:
17009                    default:
17010                        quality = Bitmap.Config.ARGB_8888;
17011                        break;
17012                }
17013            } else {
17014                // Optimization for translucent windows
17015                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
17016                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
17017            }
17018
17019            // Try to cleanup memory
17020            if (bitmap != null) bitmap.recycle();
17021
17022            try {
17023                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17024                        width, height, quality);
17025                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
17026                if (autoScale) {
17027                    mDrawingCache = bitmap;
17028                } else {
17029                    mUnscaledDrawingCache = bitmap;
17030                }
17031                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
17032            } catch (OutOfMemoryError e) {
17033                // If there is not enough memory to create the bitmap cache, just
17034                // ignore the issue as bitmap caches are not required to draw the
17035                // view hierarchy
17036                if (autoScale) {
17037                    mDrawingCache = null;
17038                } else {
17039                    mUnscaledDrawingCache = null;
17040                }
17041                mCachingFailed = true;
17042                return;
17043            }
17044
17045            clear = drawingCacheBackgroundColor != 0;
17046        }
17047
17048        Canvas canvas;
17049        if (attachInfo != null) {
17050            canvas = attachInfo.mCanvas;
17051            if (canvas == null) {
17052                canvas = new Canvas();
17053            }
17054            canvas.setBitmap(bitmap);
17055            // Temporarily clobber the cached Canvas in case one of our children
17056            // is also using a drawing cache. Without this, the children would
17057            // steal the canvas by attaching their own bitmap to it and bad, bad
17058            // thing would happen (invisible views, corrupted drawings, etc.)
17059            attachInfo.mCanvas = null;
17060        } else {
17061            // This case should hopefully never or seldom happen
17062            canvas = new Canvas(bitmap);
17063        }
17064
17065        if (clear) {
17066            bitmap.eraseColor(drawingCacheBackgroundColor);
17067        }
17068
17069        computeScroll();
17070        final int restoreCount = canvas.save();
17071
17072        if (autoScale && scalingRequired) {
17073            final float scale = attachInfo.mApplicationScale;
17074            canvas.scale(scale, scale);
17075        }
17076
17077        canvas.translate(-mScrollX, -mScrollY);
17078
17079        mPrivateFlags |= PFLAG_DRAWN;
17080        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
17081                mLayerType != LAYER_TYPE_NONE) {
17082            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
17083        }
17084
17085        // Fast path for layouts with no backgrounds
17086        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17087            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17088            dispatchDraw(canvas);
17089            if (mOverlay != null && !mOverlay.isEmpty()) {
17090                mOverlay.getOverlayView().draw(canvas);
17091            }
17092        } else {
17093            draw(canvas);
17094        }
17095
17096        canvas.restoreToCount(restoreCount);
17097        canvas.setBitmap(null);
17098
17099        if (attachInfo != null) {
17100            // Restore the cached Canvas for our siblings
17101            attachInfo.mCanvas = canvas;
17102        }
17103    }
17104
17105    /**
17106     * Create a snapshot of the view into a bitmap.  We should probably make
17107     * some form of this public, but should think about the API.
17108     *
17109     * @hide
17110     */
17111    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
17112        int width = mRight - mLeft;
17113        int height = mBottom - mTop;
17114
17115        final AttachInfo attachInfo = mAttachInfo;
17116        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
17117        width = (int) ((width * scale) + 0.5f);
17118        height = (int) ((height * scale) + 0.5f);
17119
17120        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17121                width > 0 ? width : 1, height > 0 ? height : 1, quality);
17122        if (bitmap == null) {
17123            throw new OutOfMemoryError();
17124        }
17125
17126        Resources resources = getResources();
17127        if (resources != null) {
17128            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
17129        }
17130
17131        Canvas canvas;
17132        if (attachInfo != null) {
17133            canvas = attachInfo.mCanvas;
17134            if (canvas == null) {
17135                canvas = new Canvas();
17136            }
17137            canvas.setBitmap(bitmap);
17138            // Temporarily clobber the cached Canvas in case one of our children
17139            // is also using a drawing cache. Without this, the children would
17140            // steal the canvas by attaching their own bitmap to it and bad, bad
17141            // things would happen (invisible views, corrupted drawings, etc.)
17142            attachInfo.mCanvas = null;
17143        } else {
17144            // This case should hopefully never or seldom happen
17145            canvas = new Canvas(bitmap);
17146        }
17147
17148        if ((backgroundColor & 0xff000000) != 0) {
17149            bitmap.eraseColor(backgroundColor);
17150        }
17151
17152        computeScroll();
17153        final int restoreCount = canvas.save();
17154        canvas.scale(scale, scale);
17155        canvas.translate(-mScrollX, -mScrollY);
17156
17157        // Temporarily remove the dirty mask
17158        int flags = mPrivateFlags;
17159        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17160
17161        // Fast path for layouts with no backgrounds
17162        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17163            dispatchDraw(canvas);
17164            if (mOverlay != null && !mOverlay.isEmpty()) {
17165                mOverlay.getOverlayView().draw(canvas);
17166            }
17167        } else {
17168            draw(canvas);
17169        }
17170
17171        mPrivateFlags = flags;
17172
17173        canvas.restoreToCount(restoreCount);
17174        canvas.setBitmap(null);
17175
17176        if (attachInfo != null) {
17177            // Restore the cached Canvas for our siblings
17178            attachInfo.mCanvas = canvas;
17179        }
17180
17181        return bitmap;
17182    }
17183
17184    /**
17185     * Indicates whether this View is currently in edit mode. A View is usually
17186     * in edit mode when displayed within a developer tool. For instance, if
17187     * this View is being drawn by a visual user interface builder, this method
17188     * should return true.
17189     *
17190     * Subclasses should check the return value of this method to provide
17191     * different behaviors if their normal behavior might interfere with the
17192     * host environment. For instance: the class spawns a thread in its
17193     * constructor, the drawing code relies on device-specific features, etc.
17194     *
17195     * This method is usually checked in the drawing code of custom widgets.
17196     *
17197     * @return True if this View is in edit mode, false otherwise.
17198     */
17199    public boolean isInEditMode() {
17200        return false;
17201    }
17202
17203    /**
17204     * If the View draws content inside its padding and enables fading edges,
17205     * it needs to support padding offsets. Padding offsets are added to the
17206     * fading edges to extend the length of the fade so that it covers pixels
17207     * drawn inside the padding.
17208     *
17209     * Subclasses of this class should override this method if they need
17210     * to draw content inside the padding.
17211     *
17212     * @return True if padding offset must be applied, false otherwise.
17213     *
17214     * @see #getLeftPaddingOffset()
17215     * @see #getRightPaddingOffset()
17216     * @see #getTopPaddingOffset()
17217     * @see #getBottomPaddingOffset()
17218     *
17219     * @since CURRENT
17220     */
17221    protected boolean isPaddingOffsetRequired() {
17222        return false;
17223    }
17224
17225    /**
17226     * Amount by which to extend the left fading region. Called only when
17227     * {@link #isPaddingOffsetRequired()} returns true.
17228     *
17229     * @return The left padding offset in pixels.
17230     *
17231     * @see #isPaddingOffsetRequired()
17232     *
17233     * @since CURRENT
17234     */
17235    protected int getLeftPaddingOffset() {
17236        return 0;
17237    }
17238
17239    /**
17240     * Amount by which to extend the right fading region. Called only when
17241     * {@link #isPaddingOffsetRequired()} returns true.
17242     *
17243     * @return The right padding offset in pixels.
17244     *
17245     * @see #isPaddingOffsetRequired()
17246     *
17247     * @since CURRENT
17248     */
17249    protected int getRightPaddingOffset() {
17250        return 0;
17251    }
17252
17253    /**
17254     * Amount by which to extend the top fading region. Called only when
17255     * {@link #isPaddingOffsetRequired()} returns true.
17256     *
17257     * @return The top padding offset in pixels.
17258     *
17259     * @see #isPaddingOffsetRequired()
17260     *
17261     * @since CURRENT
17262     */
17263    protected int getTopPaddingOffset() {
17264        return 0;
17265    }
17266
17267    /**
17268     * Amount by which to extend the bottom fading region. Called only when
17269     * {@link #isPaddingOffsetRequired()} returns true.
17270     *
17271     * @return The bottom padding offset in pixels.
17272     *
17273     * @see #isPaddingOffsetRequired()
17274     *
17275     * @since CURRENT
17276     */
17277    protected int getBottomPaddingOffset() {
17278        return 0;
17279    }
17280
17281    /**
17282     * @hide
17283     * @param offsetRequired
17284     */
17285    protected int getFadeTop(boolean offsetRequired) {
17286        int top = mPaddingTop;
17287        if (offsetRequired) top += getTopPaddingOffset();
17288        return top;
17289    }
17290
17291    /**
17292     * @hide
17293     * @param offsetRequired
17294     */
17295    protected int getFadeHeight(boolean offsetRequired) {
17296        int padding = mPaddingTop;
17297        if (offsetRequired) padding += getTopPaddingOffset();
17298        return mBottom - mTop - mPaddingBottom - padding;
17299    }
17300
17301    /**
17302     * <p>Indicates whether this view is attached to a hardware accelerated
17303     * window or not.</p>
17304     *
17305     * <p>Even if this method returns true, it does not mean that every call
17306     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
17307     * accelerated {@link android.graphics.Canvas}. For instance, if this view
17308     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
17309     * window is hardware accelerated,
17310     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
17311     * return false, and this method will return true.</p>
17312     *
17313     * @return True if the view is attached to a window and the window is
17314     *         hardware accelerated; false in any other case.
17315     */
17316    @ViewDebug.ExportedProperty(category = "drawing")
17317    public boolean isHardwareAccelerated() {
17318        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
17319    }
17320
17321    /**
17322     * Sets a rectangular area on this view to which the view will be clipped
17323     * when it is drawn. Setting the value to null will remove the clip bounds
17324     * and the view will draw normally, using its full bounds.
17325     *
17326     * @param clipBounds The rectangular area, in the local coordinates of
17327     * this view, to which future drawing operations will be clipped.
17328     */
17329    public void setClipBounds(Rect clipBounds) {
17330        if (clipBounds == mClipBounds
17331                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
17332            return;
17333        }
17334        if (clipBounds != null) {
17335            if (mClipBounds == null) {
17336                mClipBounds = new Rect(clipBounds);
17337            } else {
17338                mClipBounds.set(clipBounds);
17339            }
17340        } else {
17341            mClipBounds = null;
17342        }
17343        mRenderNode.setClipBounds(mClipBounds);
17344        invalidateViewProperty(false, false);
17345    }
17346
17347    /**
17348     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
17349     *
17350     * @return A copy of the current clip bounds if clip bounds are set,
17351     * otherwise null.
17352     */
17353    public Rect getClipBounds() {
17354        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
17355    }
17356
17357
17358    /**
17359     * Populates an output rectangle with the clip bounds of the view,
17360     * returning {@code true} if successful or {@code false} if the view's
17361     * clip bounds are {@code null}.
17362     *
17363     * @param outRect rectangle in which to place the clip bounds of the view
17364     * @return {@code true} if successful or {@code false} if the view's
17365     *         clip bounds are {@code null}
17366     */
17367    public boolean getClipBounds(Rect outRect) {
17368        if (mClipBounds != null) {
17369            outRect.set(mClipBounds);
17370            return true;
17371        }
17372        return false;
17373    }
17374
17375    /**
17376     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
17377     * case of an active Animation being run on the view.
17378     */
17379    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
17380            Animation a, boolean scalingRequired) {
17381        Transformation invalidationTransform;
17382        final int flags = parent.mGroupFlags;
17383        final boolean initialized = a.isInitialized();
17384        if (!initialized) {
17385            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
17386            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
17387            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
17388            onAnimationStart();
17389        }
17390
17391        final Transformation t = parent.getChildTransformation();
17392        boolean more = a.getTransformation(drawingTime, t, 1f);
17393        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
17394            if (parent.mInvalidationTransformation == null) {
17395                parent.mInvalidationTransformation = new Transformation();
17396            }
17397            invalidationTransform = parent.mInvalidationTransformation;
17398            a.getTransformation(drawingTime, invalidationTransform, 1f);
17399        } else {
17400            invalidationTransform = t;
17401        }
17402
17403        if (more) {
17404            if (!a.willChangeBounds()) {
17405                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
17406                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
17407                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
17408                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
17409                    // The child need to draw an animation, potentially offscreen, so
17410                    // make sure we do not cancel invalidate requests
17411                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17412                    parent.invalidate(mLeft, mTop, mRight, mBottom);
17413                }
17414            } else {
17415                if (parent.mInvalidateRegion == null) {
17416                    parent.mInvalidateRegion = new RectF();
17417                }
17418                final RectF region = parent.mInvalidateRegion;
17419                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
17420                        invalidationTransform);
17421
17422                // The child need to draw an animation, potentially offscreen, so
17423                // make sure we do not cancel invalidate requests
17424                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17425
17426                final int left = mLeft + (int) region.left;
17427                final int top = mTop + (int) region.top;
17428                parent.invalidate(left, top, left + (int) (region.width() + .5f),
17429                        top + (int) (region.height() + .5f));
17430            }
17431        }
17432        return more;
17433    }
17434
17435    /**
17436     * This method is called by getDisplayList() when a display list is recorded for a View.
17437     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
17438     */
17439    void setDisplayListProperties(RenderNode renderNode) {
17440        if (renderNode != null) {
17441            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
17442            renderNode.setClipToBounds(mParent instanceof ViewGroup
17443                    && ((ViewGroup) mParent).getClipChildren());
17444
17445            float alpha = 1;
17446            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
17447                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17448                ViewGroup parentVG = (ViewGroup) mParent;
17449                final Transformation t = parentVG.getChildTransformation();
17450                if (parentVG.getChildStaticTransformation(this, t)) {
17451                    final int transformType = t.getTransformationType();
17452                    if (transformType != Transformation.TYPE_IDENTITY) {
17453                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
17454                            alpha = t.getAlpha();
17455                        }
17456                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
17457                            renderNode.setStaticMatrix(t.getMatrix());
17458                        }
17459                    }
17460                }
17461            }
17462            if (mTransformationInfo != null) {
17463                alpha *= getFinalAlpha();
17464                if (alpha < 1) {
17465                    final int multipliedAlpha = (int) (255 * alpha);
17466                    if (onSetAlpha(multipliedAlpha)) {
17467                        alpha = 1;
17468                    }
17469                }
17470                renderNode.setAlpha(alpha);
17471            } else if (alpha < 1) {
17472                renderNode.setAlpha(alpha);
17473            }
17474        }
17475    }
17476
17477    /**
17478     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
17479     *
17480     * This is where the View specializes rendering behavior based on layer type,
17481     * and hardware acceleration.
17482     */
17483    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
17484        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
17485        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
17486         *
17487         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
17488         * HW accelerated, it can't handle drawing RenderNodes.
17489         */
17490        boolean drawingWithRenderNode = mAttachInfo != null
17491                && mAttachInfo.mHardwareAccelerated
17492                && hardwareAcceleratedCanvas;
17493
17494        boolean more = false;
17495        final boolean childHasIdentityMatrix = hasIdentityMatrix();
17496        final int parentFlags = parent.mGroupFlags;
17497
17498        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
17499            parent.getChildTransformation().clear();
17500            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17501        }
17502
17503        Transformation transformToApply = null;
17504        boolean concatMatrix = false;
17505        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
17506        final Animation a = getAnimation();
17507        if (a != null) {
17508            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
17509            concatMatrix = a.willChangeTransformationMatrix();
17510            if (concatMatrix) {
17511                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17512            }
17513            transformToApply = parent.getChildTransformation();
17514        } else {
17515            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
17516                // No longer animating: clear out old animation matrix
17517                mRenderNode.setAnimationMatrix(null);
17518                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17519            }
17520            if (!drawingWithRenderNode
17521                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17522                final Transformation t = parent.getChildTransformation();
17523                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
17524                if (hasTransform) {
17525                    final int transformType = t.getTransformationType();
17526                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
17527                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
17528                }
17529            }
17530        }
17531
17532        concatMatrix |= !childHasIdentityMatrix;
17533
17534        // Sets the flag as early as possible to allow draw() implementations
17535        // to call invalidate() successfully when doing animations
17536        mPrivateFlags |= PFLAG_DRAWN;
17537
17538        if (!concatMatrix &&
17539                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
17540                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
17541                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
17542                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
17543            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
17544            return more;
17545        }
17546        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
17547
17548        if (hardwareAcceleratedCanvas) {
17549            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
17550            // retain the flag's value temporarily in the mRecreateDisplayList flag
17551            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
17552            mPrivateFlags &= ~PFLAG_INVALIDATED;
17553        }
17554
17555        RenderNode renderNode = null;
17556        Bitmap cache = null;
17557        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
17558        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
17559             if (layerType != LAYER_TYPE_NONE) {
17560                 // If not drawing with RenderNode, treat HW layers as SW
17561                 layerType = LAYER_TYPE_SOFTWARE;
17562                 buildDrawingCache(true);
17563            }
17564            cache = getDrawingCache(true);
17565        }
17566
17567        if (drawingWithRenderNode) {
17568            // Delay getting the display list until animation-driven alpha values are
17569            // set up and possibly passed on to the view
17570            renderNode = updateDisplayListIfDirty();
17571            if (!renderNode.isValid()) {
17572                // Uncommon, but possible. If a view is removed from the hierarchy during the call
17573                // to getDisplayList(), the display list will be marked invalid and we should not
17574                // try to use it again.
17575                renderNode = null;
17576                drawingWithRenderNode = false;
17577            }
17578        }
17579
17580        int sx = 0;
17581        int sy = 0;
17582        if (!drawingWithRenderNode) {
17583            computeScroll();
17584            sx = mScrollX;
17585            sy = mScrollY;
17586        }
17587
17588        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
17589        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
17590
17591        int restoreTo = -1;
17592        if (!drawingWithRenderNode || transformToApply != null) {
17593            restoreTo = canvas.save();
17594        }
17595        if (offsetForScroll) {
17596            canvas.translate(mLeft - sx, mTop - sy);
17597        } else {
17598            if (!drawingWithRenderNode) {
17599                canvas.translate(mLeft, mTop);
17600            }
17601            if (scalingRequired) {
17602                if (drawingWithRenderNode) {
17603                    // TODO: Might not need this if we put everything inside the DL
17604                    restoreTo = canvas.save();
17605                }
17606                // mAttachInfo cannot be null, otherwise scalingRequired == false
17607                final float scale = 1.0f / mAttachInfo.mApplicationScale;
17608                canvas.scale(scale, scale);
17609            }
17610        }
17611
17612        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
17613        if (transformToApply != null
17614                || alpha < 1
17615                || !hasIdentityMatrix()
17616                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17617            if (transformToApply != null || !childHasIdentityMatrix) {
17618                int transX = 0;
17619                int transY = 0;
17620
17621                if (offsetForScroll) {
17622                    transX = -sx;
17623                    transY = -sy;
17624                }
17625
17626                if (transformToApply != null) {
17627                    if (concatMatrix) {
17628                        if (drawingWithRenderNode) {
17629                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17630                        } else {
17631                            // Undo the scroll translation, apply the transformation matrix,
17632                            // then redo the scroll translate to get the correct result.
17633                            canvas.translate(-transX, -transY);
17634                            canvas.concat(transformToApply.getMatrix());
17635                            canvas.translate(transX, transY);
17636                        }
17637                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17638                    }
17639
17640                    float transformAlpha = transformToApply.getAlpha();
17641                    if (transformAlpha < 1) {
17642                        alpha *= transformAlpha;
17643                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17644                    }
17645                }
17646
17647                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17648                    canvas.translate(-transX, -transY);
17649                    canvas.concat(getMatrix());
17650                    canvas.translate(transX, transY);
17651                }
17652            }
17653
17654            // Deal with alpha if it is or used to be <1
17655            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17656                if (alpha < 1) {
17657                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17658                } else {
17659                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17660                }
17661                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17662                if (!drawingWithDrawingCache) {
17663                    final int multipliedAlpha = (int) (255 * alpha);
17664                    if (!onSetAlpha(multipliedAlpha)) {
17665                        if (drawingWithRenderNode) {
17666                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17667                        } else if (layerType == LAYER_TYPE_NONE) {
17668                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17669                                    multipliedAlpha);
17670                        }
17671                    } else {
17672                        // Alpha is handled by the child directly, clobber the layer's alpha
17673                        mPrivateFlags |= PFLAG_ALPHA_SET;
17674                    }
17675                }
17676            }
17677        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17678            onSetAlpha(255);
17679            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17680        }
17681
17682        if (!drawingWithRenderNode) {
17683            // apply clips directly, since RenderNode won't do it for this draw
17684            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17685                if (offsetForScroll) {
17686                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17687                } else {
17688                    if (!scalingRequired || cache == null) {
17689                        canvas.clipRect(0, 0, getWidth(), getHeight());
17690                    } else {
17691                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17692                    }
17693                }
17694            }
17695
17696            if (mClipBounds != null) {
17697                // clip bounds ignore scroll
17698                canvas.clipRect(mClipBounds);
17699            }
17700        }
17701
17702        if (!drawingWithDrawingCache) {
17703            if (drawingWithRenderNode) {
17704                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17705                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17706            } else {
17707                // Fast path for layouts with no backgrounds
17708                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17709                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17710                    dispatchDraw(canvas);
17711                } else {
17712                    draw(canvas);
17713                }
17714            }
17715        } else if (cache != null) {
17716            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17717            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17718                // no layer paint, use temporary paint to draw bitmap
17719                Paint cachePaint = parent.mCachePaint;
17720                if (cachePaint == null) {
17721                    cachePaint = new Paint();
17722                    cachePaint.setDither(false);
17723                    parent.mCachePaint = cachePaint;
17724                }
17725                cachePaint.setAlpha((int) (alpha * 255));
17726                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17727            } else {
17728                // use layer paint to draw the bitmap, merging the two alphas, but also restore
17729                int layerPaintAlpha = mLayerPaint.getAlpha();
17730                if (alpha < 1) {
17731                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
17732                }
17733                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17734                if (alpha < 1) {
17735                    mLayerPaint.setAlpha(layerPaintAlpha);
17736                }
17737            }
17738        }
17739
17740        if (restoreTo >= 0) {
17741            canvas.restoreToCount(restoreTo);
17742        }
17743
17744        if (a != null && !more) {
17745            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17746                onSetAlpha(255);
17747            }
17748            parent.finishAnimatingView(this, a);
17749        }
17750
17751        if (more && hardwareAcceleratedCanvas) {
17752            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17753                // alpha animations should cause the child to recreate its display list
17754                invalidate(true);
17755            }
17756        }
17757
17758        mRecreateDisplayList = false;
17759
17760        return more;
17761    }
17762
17763    static Paint getDebugPaint() {
17764        if (sDebugPaint == null) {
17765            sDebugPaint = new Paint();
17766            sDebugPaint.setAntiAlias(false);
17767        }
17768        return sDebugPaint;
17769    }
17770
17771    final int dipsToPixels(int dips) {
17772        float scale = getContext().getResources().getDisplayMetrics().density;
17773        return (int) (dips * scale + 0.5f);
17774    }
17775
17776    final private void debugDrawFocus(Canvas canvas) {
17777        if (isFocused()) {
17778            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
17779            final int l = mScrollX;
17780            final int r = l + mRight - mLeft;
17781            final int t = mScrollY;
17782            final int b = t + mBottom - mTop;
17783
17784            final Paint paint = getDebugPaint();
17785            paint.setColor(DEBUG_CORNERS_COLOR);
17786
17787            // Draw squares in corners.
17788            paint.setStyle(Paint.Style.FILL);
17789            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
17790            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
17791            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
17792            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
17793
17794            // Draw big X across the view.
17795            paint.setStyle(Paint.Style.STROKE);
17796            canvas.drawLine(l, t, r, b, paint);
17797            canvas.drawLine(l, b, r, t, paint);
17798        }
17799    }
17800
17801    /**
17802     * Manually render this view (and all of its children) to the given Canvas.
17803     * The view must have already done a full layout before this function is
17804     * called.  When implementing a view, implement
17805     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17806     * If you do need to override this method, call the superclass version.
17807     *
17808     * @param canvas The Canvas to which the View is rendered.
17809     */
17810    @CallSuper
17811    public void draw(Canvas canvas) {
17812        final int privateFlags = mPrivateFlags;
17813        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17814                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17815        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17816
17817        /*
17818         * Draw traversal performs several drawing steps which must be executed
17819         * in the appropriate order:
17820         *
17821         *      1. Draw the background
17822         *      2. If necessary, save the canvas' layers to prepare for fading
17823         *      3. Draw view's content
17824         *      4. Draw children
17825         *      5. If necessary, draw the fading edges and restore layers
17826         *      6. Draw decorations (scrollbars for instance)
17827         */
17828
17829        // Step 1, draw the background, if needed
17830        int saveCount;
17831
17832        if (!dirtyOpaque) {
17833            drawBackground(canvas);
17834        }
17835
17836        // skip step 2 & 5 if possible (common case)
17837        final int viewFlags = mViewFlags;
17838        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17839        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17840        if (!verticalEdges && !horizontalEdges) {
17841            // Step 3, draw the content
17842            if (!dirtyOpaque) onDraw(canvas);
17843
17844            // Step 4, draw the children
17845            dispatchDraw(canvas);
17846
17847            // Overlay is part of the content and draws beneath Foreground
17848            if (mOverlay != null && !mOverlay.isEmpty()) {
17849                mOverlay.getOverlayView().dispatchDraw(canvas);
17850            }
17851
17852            // Step 6, draw decorations (foreground, scrollbars)
17853            onDrawForeground(canvas);
17854
17855            if (debugDraw()) {
17856                debugDrawFocus(canvas);
17857            }
17858
17859            // we're done...
17860            return;
17861        }
17862
17863        /*
17864         * Here we do the full fledged routine...
17865         * (this is an uncommon case where speed matters less,
17866         * this is why we repeat some of the tests that have been
17867         * done above)
17868         */
17869
17870        boolean drawTop = false;
17871        boolean drawBottom = false;
17872        boolean drawLeft = false;
17873        boolean drawRight = false;
17874
17875        float topFadeStrength = 0.0f;
17876        float bottomFadeStrength = 0.0f;
17877        float leftFadeStrength = 0.0f;
17878        float rightFadeStrength = 0.0f;
17879
17880        // Step 2, save the canvas' layers
17881        int paddingLeft = mPaddingLeft;
17882
17883        final boolean offsetRequired = isPaddingOffsetRequired();
17884        if (offsetRequired) {
17885            paddingLeft += getLeftPaddingOffset();
17886        }
17887
17888        int left = mScrollX + paddingLeft;
17889        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17890        int top = mScrollY + getFadeTop(offsetRequired);
17891        int bottom = top + getFadeHeight(offsetRequired);
17892
17893        if (offsetRequired) {
17894            right += getRightPaddingOffset();
17895            bottom += getBottomPaddingOffset();
17896        }
17897
17898        final ScrollabilityCache scrollabilityCache = mScrollCache;
17899        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17900        int length = (int) fadeHeight;
17901
17902        // clip the fade length if top and bottom fades overlap
17903        // overlapping fades produce odd-looking artifacts
17904        if (verticalEdges && (top + length > bottom - length)) {
17905            length = (bottom - top) / 2;
17906        }
17907
17908        // also clip horizontal fades if necessary
17909        if (horizontalEdges && (left + length > right - length)) {
17910            length = (right - left) / 2;
17911        }
17912
17913        if (verticalEdges) {
17914            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17915            drawTop = topFadeStrength * fadeHeight > 1.0f;
17916            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17917            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17918        }
17919
17920        if (horizontalEdges) {
17921            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17922            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17923            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17924            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17925        }
17926
17927        saveCount = canvas.getSaveCount();
17928
17929        int solidColor = getSolidColor();
17930        if (solidColor == 0) {
17931            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17932
17933            if (drawTop) {
17934                canvas.saveLayer(left, top, right, top + length, null, flags);
17935            }
17936
17937            if (drawBottom) {
17938                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17939            }
17940
17941            if (drawLeft) {
17942                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17943            }
17944
17945            if (drawRight) {
17946                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17947            }
17948        } else {
17949            scrollabilityCache.setFadeColor(solidColor);
17950        }
17951
17952        // Step 3, draw the content
17953        if (!dirtyOpaque) onDraw(canvas);
17954
17955        // Step 4, draw the children
17956        dispatchDraw(canvas);
17957
17958        // Step 5, draw the fade effect and restore layers
17959        final Paint p = scrollabilityCache.paint;
17960        final Matrix matrix = scrollabilityCache.matrix;
17961        final Shader fade = scrollabilityCache.shader;
17962
17963        if (drawTop) {
17964            matrix.setScale(1, fadeHeight * topFadeStrength);
17965            matrix.postTranslate(left, top);
17966            fade.setLocalMatrix(matrix);
17967            p.setShader(fade);
17968            canvas.drawRect(left, top, right, top + length, p);
17969        }
17970
17971        if (drawBottom) {
17972            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17973            matrix.postRotate(180);
17974            matrix.postTranslate(left, bottom);
17975            fade.setLocalMatrix(matrix);
17976            p.setShader(fade);
17977            canvas.drawRect(left, bottom - length, right, bottom, p);
17978        }
17979
17980        if (drawLeft) {
17981            matrix.setScale(1, fadeHeight * leftFadeStrength);
17982            matrix.postRotate(-90);
17983            matrix.postTranslate(left, top);
17984            fade.setLocalMatrix(matrix);
17985            p.setShader(fade);
17986            canvas.drawRect(left, top, left + length, bottom, p);
17987        }
17988
17989        if (drawRight) {
17990            matrix.setScale(1, fadeHeight * rightFadeStrength);
17991            matrix.postRotate(90);
17992            matrix.postTranslate(right, top);
17993            fade.setLocalMatrix(matrix);
17994            p.setShader(fade);
17995            canvas.drawRect(right - length, top, right, bottom, p);
17996        }
17997
17998        canvas.restoreToCount(saveCount);
17999
18000        // Overlay is part of the content and draws beneath Foreground
18001        if (mOverlay != null && !mOverlay.isEmpty()) {
18002            mOverlay.getOverlayView().dispatchDraw(canvas);
18003        }
18004
18005        // Step 6, draw decorations (foreground, scrollbars)
18006        onDrawForeground(canvas);
18007
18008        if (debugDraw()) {
18009            debugDrawFocus(canvas);
18010        }
18011    }
18012
18013    /**
18014     * Draws the background onto the specified canvas.
18015     *
18016     * @param canvas Canvas on which to draw the background
18017     */
18018    private void drawBackground(Canvas canvas) {
18019        final Drawable background = mBackground;
18020        if (background == null) {
18021            return;
18022        }
18023
18024        setBackgroundBounds();
18025
18026        // Attempt to use a display list if requested.
18027        if (canvas.isHardwareAccelerated() && mAttachInfo != null
18028                && mAttachInfo.mThreadedRenderer != null) {
18029            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
18030
18031            final RenderNode renderNode = mBackgroundRenderNode;
18032            if (renderNode != null && renderNode.isValid()) {
18033                setBackgroundRenderNodeProperties(renderNode);
18034                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
18035                return;
18036            }
18037        }
18038
18039        final int scrollX = mScrollX;
18040        final int scrollY = mScrollY;
18041        if ((scrollX | scrollY) == 0) {
18042            background.draw(canvas);
18043        } else {
18044            canvas.translate(scrollX, scrollY);
18045            background.draw(canvas);
18046            canvas.translate(-scrollX, -scrollY);
18047        }
18048    }
18049
18050    /**
18051     * Sets the correct background bounds and rebuilds the outline, if needed.
18052     * <p/>
18053     * This is called by LayoutLib.
18054     */
18055    void setBackgroundBounds() {
18056        if (mBackgroundSizeChanged && mBackground != null) {
18057            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
18058            mBackgroundSizeChanged = false;
18059            rebuildOutline();
18060        }
18061    }
18062
18063    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
18064        renderNode.setTranslationX(mScrollX);
18065        renderNode.setTranslationY(mScrollY);
18066    }
18067
18068    /**
18069     * Creates a new display list or updates the existing display list for the
18070     * specified Drawable.
18071     *
18072     * @param drawable Drawable for which to create a display list
18073     * @param renderNode Existing RenderNode, or {@code null}
18074     * @return A valid display list for the specified drawable
18075     */
18076    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
18077        if (renderNode == null) {
18078            renderNode = RenderNode.create(drawable.getClass().getName(), this);
18079        }
18080
18081        final Rect bounds = drawable.getBounds();
18082        final int width = bounds.width();
18083        final int height = bounds.height();
18084        final DisplayListCanvas canvas = renderNode.start(width, height);
18085
18086        // Reverse left/top translation done by drawable canvas, which will
18087        // instead be applied by rendernode's LTRB bounds below. This way, the
18088        // drawable's bounds match with its rendernode bounds and its content
18089        // will lie within those bounds in the rendernode tree.
18090        canvas.translate(-bounds.left, -bounds.top);
18091
18092        try {
18093            drawable.draw(canvas);
18094        } finally {
18095            renderNode.end(canvas);
18096        }
18097
18098        // Set up drawable properties that are view-independent.
18099        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
18100        renderNode.setProjectBackwards(drawable.isProjected());
18101        renderNode.setProjectionReceiver(true);
18102        renderNode.setClipToBounds(false);
18103        return renderNode;
18104    }
18105
18106    /**
18107     * Returns the overlay for this view, creating it if it does not yet exist.
18108     * Adding drawables to the overlay will cause them to be displayed whenever
18109     * the view itself is redrawn. Objects in the overlay should be actively
18110     * managed: remove them when they should not be displayed anymore. The
18111     * overlay will always have the same size as its host view.
18112     *
18113     * <p>Note: Overlays do not currently work correctly with {@link
18114     * SurfaceView} or {@link TextureView}; contents in overlays for these
18115     * types of views may not display correctly.</p>
18116     *
18117     * @return The ViewOverlay object for this view.
18118     * @see ViewOverlay
18119     */
18120    public ViewOverlay getOverlay() {
18121        if (mOverlay == null) {
18122            mOverlay = new ViewOverlay(mContext, this);
18123        }
18124        return mOverlay;
18125    }
18126
18127    /**
18128     * Override this if your view is known to always be drawn on top of a solid color background,
18129     * and needs to draw fading edges. Returning a non-zero color enables the view system to
18130     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
18131     * should be set to 0xFF.
18132     *
18133     * @see #setVerticalFadingEdgeEnabled(boolean)
18134     * @see #setHorizontalFadingEdgeEnabled(boolean)
18135     *
18136     * @return The known solid color background for this view, or 0 if the color may vary
18137     */
18138    @ViewDebug.ExportedProperty(category = "drawing")
18139    @ColorInt
18140    public int getSolidColor() {
18141        return 0;
18142    }
18143
18144    /**
18145     * Build a human readable string representation of the specified view flags.
18146     *
18147     * @param flags the view flags to convert to a string
18148     * @return a String representing the supplied flags
18149     */
18150    private static String printFlags(int flags) {
18151        String output = "";
18152        int numFlags = 0;
18153        if ((flags & FOCUSABLE) == FOCUSABLE) {
18154            output += "TAKES_FOCUS";
18155            numFlags++;
18156        }
18157
18158        switch (flags & VISIBILITY_MASK) {
18159        case INVISIBLE:
18160            if (numFlags > 0) {
18161                output += " ";
18162            }
18163            output += "INVISIBLE";
18164            // USELESS HERE numFlags++;
18165            break;
18166        case GONE:
18167            if (numFlags > 0) {
18168                output += " ";
18169            }
18170            output += "GONE";
18171            // USELESS HERE numFlags++;
18172            break;
18173        default:
18174            break;
18175        }
18176        return output;
18177    }
18178
18179    /**
18180     * Build a human readable string representation of the specified private
18181     * view flags.
18182     *
18183     * @param privateFlags the private view flags to convert to a string
18184     * @return a String representing the supplied flags
18185     */
18186    private static String printPrivateFlags(int privateFlags) {
18187        String output = "";
18188        int numFlags = 0;
18189
18190        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
18191            output += "WANTS_FOCUS";
18192            numFlags++;
18193        }
18194
18195        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
18196            if (numFlags > 0) {
18197                output += " ";
18198            }
18199            output += "FOCUSED";
18200            numFlags++;
18201        }
18202
18203        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
18204            if (numFlags > 0) {
18205                output += " ";
18206            }
18207            output += "SELECTED";
18208            numFlags++;
18209        }
18210
18211        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
18212            if (numFlags > 0) {
18213                output += " ";
18214            }
18215            output += "IS_ROOT_NAMESPACE";
18216            numFlags++;
18217        }
18218
18219        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
18220            if (numFlags > 0) {
18221                output += " ";
18222            }
18223            output += "HAS_BOUNDS";
18224            numFlags++;
18225        }
18226
18227        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
18228            if (numFlags > 0) {
18229                output += " ";
18230            }
18231            output += "DRAWN";
18232            // USELESS HERE numFlags++;
18233        }
18234        return output;
18235    }
18236
18237    /**
18238     * <p>Indicates whether or not this view's layout will be requested during
18239     * the next hierarchy layout pass.</p>
18240     *
18241     * @return true if the layout will be forced during next layout pass
18242     */
18243    public boolean isLayoutRequested() {
18244        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18245    }
18246
18247    /**
18248     * Return true if o is a ViewGroup that is laying out using optical bounds.
18249     * @hide
18250     */
18251    public static boolean isLayoutModeOptical(Object o) {
18252        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
18253    }
18254
18255    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
18256        Insets parentInsets = mParent instanceof View ?
18257                ((View) mParent).getOpticalInsets() : Insets.NONE;
18258        Insets childInsets = getOpticalInsets();
18259        return setFrame(
18260                left   + parentInsets.left - childInsets.left,
18261                top    + parentInsets.top  - childInsets.top,
18262                right  + parentInsets.left + childInsets.right,
18263                bottom + parentInsets.top  + childInsets.bottom);
18264    }
18265
18266    /**
18267     * Assign a size and position to a view and all of its
18268     * descendants
18269     *
18270     * <p>This is the second phase of the layout mechanism.
18271     * (The first is measuring). In this phase, each parent calls
18272     * layout on all of its children to position them.
18273     * This is typically done using the child measurements
18274     * that were stored in the measure pass().</p>
18275     *
18276     * <p>Derived classes should not override this method.
18277     * Derived classes with children should override
18278     * onLayout. In that method, they should
18279     * call layout on each of their children.</p>
18280     *
18281     * @param l Left position, relative to parent
18282     * @param t Top position, relative to parent
18283     * @param r Right position, relative to parent
18284     * @param b Bottom position, relative to parent
18285     */
18286    @SuppressWarnings({"unchecked"})
18287    public void layout(int l, int t, int r, int b) {
18288        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
18289            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
18290            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18291        }
18292
18293        int oldL = mLeft;
18294        int oldT = mTop;
18295        int oldB = mBottom;
18296        int oldR = mRight;
18297
18298        boolean changed = isLayoutModeOptical(mParent) ?
18299                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
18300
18301        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
18302            onLayout(changed, l, t, r, b);
18303
18304            if (shouldDrawRoundScrollbar()) {
18305                if(mRoundScrollbarRenderer == null) {
18306                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
18307                }
18308            } else {
18309                mRoundScrollbarRenderer = null;
18310            }
18311
18312            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
18313
18314            ListenerInfo li = mListenerInfo;
18315            if (li != null && li.mOnLayoutChangeListeners != null) {
18316                ArrayList<OnLayoutChangeListener> listenersCopy =
18317                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
18318                int numListeners = listenersCopy.size();
18319                for (int i = 0; i < numListeners; ++i) {
18320                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
18321                }
18322            }
18323        }
18324
18325        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
18326        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
18327    }
18328
18329    /**
18330     * Called from layout when this view should
18331     * assign a size and position to each of its children.
18332     *
18333     * Derived classes with children should override
18334     * this method and call layout on each of
18335     * their children.
18336     * @param changed This is a new size or position for this view
18337     * @param left Left position, relative to parent
18338     * @param top Top position, relative to parent
18339     * @param right Right position, relative to parent
18340     * @param bottom Bottom position, relative to parent
18341     */
18342    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
18343    }
18344
18345    /**
18346     * Assign a size and position to this view.
18347     *
18348     * This is called from layout.
18349     *
18350     * @param left Left position, relative to parent
18351     * @param top Top position, relative to parent
18352     * @param right Right position, relative to parent
18353     * @param bottom Bottom position, relative to parent
18354     * @return true if the new size and position are different than the
18355     *         previous ones
18356     * {@hide}
18357     */
18358    protected boolean setFrame(int left, int top, int right, int bottom) {
18359        boolean changed = false;
18360
18361        if (DBG) {
18362            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
18363                    + right + "," + bottom + ")");
18364        }
18365
18366        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
18367            changed = true;
18368
18369            // Remember our drawn bit
18370            int drawn = mPrivateFlags & PFLAG_DRAWN;
18371
18372            int oldWidth = mRight - mLeft;
18373            int oldHeight = mBottom - mTop;
18374            int newWidth = right - left;
18375            int newHeight = bottom - top;
18376            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
18377
18378            // Invalidate our old position
18379            invalidate(sizeChanged);
18380
18381            mLeft = left;
18382            mTop = top;
18383            mRight = right;
18384            mBottom = bottom;
18385            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
18386
18387            mPrivateFlags |= PFLAG_HAS_BOUNDS;
18388
18389
18390            if (sizeChanged) {
18391                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
18392            }
18393
18394            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
18395                // If we are visible, force the DRAWN bit to on so that
18396                // this invalidate will go through (at least to our parent).
18397                // This is because someone may have invalidated this view
18398                // before this call to setFrame came in, thereby clearing
18399                // the DRAWN bit.
18400                mPrivateFlags |= PFLAG_DRAWN;
18401                invalidate(sizeChanged);
18402                // parent display list may need to be recreated based on a change in the bounds
18403                // of any child
18404                invalidateParentCaches();
18405            }
18406
18407            // Reset drawn bit to original value (invalidate turns it off)
18408            mPrivateFlags |= drawn;
18409
18410            mBackgroundSizeChanged = true;
18411            if (mForegroundInfo != null) {
18412                mForegroundInfo.mBoundsChanged = true;
18413            }
18414
18415            notifySubtreeAccessibilityStateChangedIfNeeded();
18416        }
18417        return changed;
18418    }
18419
18420    /**
18421     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
18422     * @hide
18423     */
18424    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
18425        setFrame(left, top, right, bottom);
18426    }
18427
18428    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
18429        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
18430        if (mOverlay != null) {
18431            mOverlay.getOverlayView().setRight(newWidth);
18432            mOverlay.getOverlayView().setBottom(newHeight);
18433        }
18434        rebuildOutline();
18435    }
18436
18437    /**
18438     * Finalize inflating a view from XML.  This is called as the last phase
18439     * of inflation, after all child views have been added.
18440     *
18441     * <p>Even if the subclass overrides onFinishInflate, they should always be
18442     * sure to call the super method, so that we get called.
18443     */
18444    @CallSuper
18445    protected void onFinishInflate() {
18446    }
18447
18448    /**
18449     * Returns the resources associated with this view.
18450     *
18451     * @return Resources object.
18452     */
18453    public Resources getResources() {
18454        return mResources;
18455    }
18456
18457    /**
18458     * Invalidates the specified Drawable.
18459     *
18460     * @param drawable the drawable to invalidate
18461     */
18462    @Override
18463    public void invalidateDrawable(@NonNull Drawable drawable) {
18464        if (verifyDrawable(drawable)) {
18465            final Rect dirty = drawable.getDirtyBounds();
18466            final int scrollX = mScrollX;
18467            final int scrollY = mScrollY;
18468
18469            invalidate(dirty.left + scrollX, dirty.top + scrollY,
18470                    dirty.right + scrollX, dirty.bottom + scrollY);
18471            rebuildOutline();
18472        }
18473    }
18474
18475    /**
18476     * Schedules an action on a drawable to occur at a specified time.
18477     *
18478     * @param who the recipient of the action
18479     * @param what the action to run on the drawable
18480     * @param when the time at which the action must occur. Uses the
18481     *        {@link SystemClock#uptimeMillis} timebase.
18482     */
18483    @Override
18484    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
18485        if (verifyDrawable(who) && what != null) {
18486            final long delay = when - SystemClock.uptimeMillis();
18487            if (mAttachInfo != null) {
18488                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
18489                        Choreographer.CALLBACK_ANIMATION, what, who,
18490                        Choreographer.subtractFrameDelay(delay));
18491            } else {
18492                // Postpone the runnable until we know
18493                // on which thread it needs to run.
18494                getRunQueue().postDelayed(what, delay);
18495            }
18496        }
18497    }
18498
18499    /**
18500     * Cancels a scheduled action on a drawable.
18501     *
18502     * @param who the recipient of the action
18503     * @param what the action to cancel
18504     */
18505    @Override
18506    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
18507        if (verifyDrawable(who) && what != null) {
18508            if (mAttachInfo != null) {
18509                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18510                        Choreographer.CALLBACK_ANIMATION, what, who);
18511            }
18512            getRunQueue().removeCallbacks(what);
18513        }
18514    }
18515
18516    /**
18517     * Unschedule any events associated with the given Drawable.  This can be
18518     * used when selecting a new Drawable into a view, so that the previous
18519     * one is completely unscheduled.
18520     *
18521     * @param who The Drawable to unschedule.
18522     *
18523     * @see #drawableStateChanged
18524     */
18525    public void unscheduleDrawable(Drawable who) {
18526        if (mAttachInfo != null && who != null) {
18527            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18528                    Choreographer.CALLBACK_ANIMATION, null, who);
18529        }
18530    }
18531
18532    /**
18533     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
18534     * that the View directionality can and will be resolved before its Drawables.
18535     *
18536     * Will call {@link View#onResolveDrawables} when resolution is done.
18537     *
18538     * @hide
18539     */
18540    protected void resolveDrawables() {
18541        // Drawables resolution may need to happen before resolving the layout direction (which is
18542        // done only during the measure() call).
18543        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
18544        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
18545        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
18546        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
18547        // direction to be resolved as its resolved value will be the same as its raw value.
18548        if (!isLayoutDirectionResolved() &&
18549                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
18550            return;
18551        }
18552
18553        final int layoutDirection = isLayoutDirectionResolved() ?
18554                getLayoutDirection() : getRawLayoutDirection();
18555
18556        if (mBackground != null) {
18557            mBackground.setLayoutDirection(layoutDirection);
18558        }
18559        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18560            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
18561        }
18562        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
18563        onResolveDrawables(layoutDirection);
18564    }
18565
18566    boolean areDrawablesResolved() {
18567        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
18568    }
18569
18570    /**
18571     * Called when layout direction has been resolved.
18572     *
18573     * The default implementation does nothing.
18574     *
18575     * @param layoutDirection The resolved layout direction.
18576     *
18577     * @see #LAYOUT_DIRECTION_LTR
18578     * @see #LAYOUT_DIRECTION_RTL
18579     *
18580     * @hide
18581     */
18582    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
18583    }
18584
18585    /**
18586     * @hide
18587     */
18588    protected void resetResolvedDrawables() {
18589        resetResolvedDrawablesInternal();
18590    }
18591
18592    void resetResolvedDrawablesInternal() {
18593        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
18594    }
18595
18596    /**
18597     * If your view subclass is displaying its own Drawable objects, it should
18598     * override this function and return true for any Drawable it is
18599     * displaying.  This allows animations for those drawables to be
18600     * scheduled.
18601     *
18602     * <p>Be sure to call through to the super class when overriding this
18603     * function.
18604     *
18605     * @param who The Drawable to verify.  Return true if it is one you are
18606     *            displaying, else return the result of calling through to the
18607     *            super class.
18608     *
18609     * @return boolean If true than the Drawable is being displayed in the
18610     *         view; else false and it is not allowed to animate.
18611     *
18612     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
18613     * @see #drawableStateChanged()
18614     */
18615    @CallSuper
18616    protected boolean verifyDrawable(@NonNull Drawable who) {
18617        // Avoid verifying the scroll bar drawable so that we don't end up in
18618        // an invalidation loop. This effectively prevents the scroll bar
18619        // drawable from triggering invalidations and scheduling runnables.
18620        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
18621    }
18622
18623    /**
18624     * This function is called whenever the state of the view changes in such
18625     * a way that it impacts the state of drawables being shown.
18626     * <p>
18627     * If the View has a StateListAnimator, it will also be called to run necessary state
18628     * change animations.
18629     * <p>
18630     * Be sure to call through to the superclass when overriding this function.
18631     *
18632     * @see Drawable#setState(int[])
18633     */
18634    @CallSuper
18635    protected void drawableStateChanged() {
18636        final int[] state = getDrawableState();
18637        boolean changed = false;
18638
18639        final Drawable bg = mBackground;
18640        if (bg != null && bg.isStateful()) {
18641            changed |= bg.setState(state);
18642        }
18643
18644        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18645        if (fg != null && fg.isStateful()) {
18646            changed |= fg.setState(state);
18647        }
18648
18649        if (mScrollCache != null) {
18650            final Drawable scrollBar = mScrollCache.scrollBar;
18651            if (scrollBar != null && scrollBar.isStateful()) {
18652                changed |= scrollBar.setState(state)
18653                        && mScrollCache.state != ScrollabilityCache.OFF;
18654            }
18655        }
18656
18657        if (mStateListAnimator != null) {
18658            mStateListAnimator.setState(state);
18659        }
18660
18661        if (changed) {
18662            invalidate();
18663        }
18664    }
18665
18666    /**
18667     * This function is called whenever the view hotspot changes and needs to
18668     * be propagated to drawables or child views managed by the view.
18669     * <p>
18670     * Dispatching to child views is handled by
18671     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18672     * <p>
18673     * Be sure to call through to the superclass when overriding this function.
18674     *
18675     * @param x hotspot x coordinate
18676     * @param y hotspot y coordinate
18677     */
18678    @CallSuper
18679    public void drawableHotspotChanged(float x, float y) {
18680        if (mBackground != null) {
18681            mBackground.setHotspot(x, y);
18682        }
18683        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18684            mForegroundInfo.mDrawable.setHotspot(x, y);
18685        }
18686
18687        dispatchDrawableHotspotChanged(x, y);
18688    }
18689
18690    /**
18691     * Dispatches drawableHotspotChanged to all of this View's children.
18692     *
18693     * @param x hotspot x coordinate
18694     * @param y hotspot y coordinate
18695     * @see #drawableHotspotChanged(float, float)
18696     */
18697    public void dispatchDrawableHotspotChanged(float x, float y) {
18698    }
18699
18700    /**
18701     * Call this to force a view to update its drawable state. This will cause
18702     * drawableStateChanged to be called on this view. Views that are interested
18703     * in the new state should call getDrawableState.
18704     *
18705     * @see #drawableStateChanged
18706     * @see #getDrawableState
18707     */
18708    public void refreshDrawableState() {
18709        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18710        drawableStateChanged();
18711
18712        ViewParent parent = mParent;
18713        if (parent != null) {
18714            parent.childDrawableStateChanged(this);
18715        }
18716    }
18717
18718    /**
18719     * Return an array of resource IDs of the drawable states representing the
18720     * current state of the view.
18721     *
18722     * @return The current drawable state
18723     *
18724     * @see Drawable#setState(int[])
18725     * @see #drawableStateChanged()
18726     * @see #onCreateDrawableState(int)
18727     */
18728    public final int[] getDrawableState() {
18729        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
18730            return mDrawableState;
18731        } else {
18732            mDrawableState = onCreateDrawableState(0);
18733            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
18734            return mDrawableState;
18735        }
18736    }
18737
18738    /**
18739     * Generate the new {@link android.graphics.drawable.Drawable} state for
18740     * this view. This is called by the view
18741     * system when the cached Drawable state is determined to be invalid.  To
18742     * retrieve the current state, you should use {@link #getDrawableState}.
18743     *
18744     * @param extraSpace if non-zero, this is the number of extra entries you
18745     * would like in the returned array in which you can place your own
18746     * states.
18747     *
18748     * @return Returns an array holding the current {@link Drawable} state of
18749     * the view.
18750     *
18751     * @see #mergeDrawableStates(int[], int[])
18752     */
18753    protected int[] onCreateDrawableState(int extraSpace) {
18754        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
18755                mParent instanceof View) {
18756            return ((View) mParent).onCreateDrawableState(extraSpace);
18757        }
18758
18759        int[] drawableState;
18760
18761        int privateFlags = mPrivateFlags;
18762
18763        int viewStateIndex = 0;
18764        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
18765        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
18766        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
18767        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
18768        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
18769        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
18770        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
18771                ThreadedRenderer.isAvailable()) {
18772            // This is set if HW acceleration is requested, even if the current
18773            // process doesn't allow it.  This is just to allow app preview
18774            // windows to better match their app.
18775            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
18776        }
18777        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
18778
18779        final int privateFlags2 = mPrivateFlags2;
18780        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
18781            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
18782        }
18783        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
18784            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
18785        }
18786
18787        drawableState = StateSet.get(viewStateIndex);
18788
18789        //noinspection ConstantIfStatement
18790        if (false) {
18791            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18792            Log.i("View", toString()
18793                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18794                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18795                    + " fo=" + hasFocus()
18796                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18797                    + " wf=" + hasWindowFocus()
18798                    + ": " + Arrays.toString(drawableState));
18799        }
18800
18801        if (extraSpace == 0) {
18802            return drawableState;
18803        }
18804
18805        final int[] fullState;
18806        if (drawableState != null) {
18807            fullState = new int[drawableState.length + extraSpace];
18808            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18809        } else {
18810            fullState = new int[extraSpace];
18811        }
18812
18813        return fullState;
18814    }
18815
18816    /**
18817     * Merge your own state values in <var>additionalState</var> into the base
18818     * state values <var>baseState</var> that were returned by
18819     * {@link #onCreateDrawableState(int)}.
18820     *
18821     * @param baseState The base state values returned by
18822     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18823     * own additional state values.
18824     *
18825     * @param additionalState The additional state values you would like
18826     * added to <var>baseState</var>; this array is not modified.
18827     *
18828     * @return As a convenience, the <var>baseState</var> array you originally
18829     * passed into the function is returned.
18830     *
18831     * @see #onCreateDrawableState(int)
18832     */
18833    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18834        final int N = baseState.length;
18835        int i = N - 1;
18836        while (i >= 0 && baseState[i] == 0) {
18837            i--;
18838        }
18839        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18840        return baseState;
18841    }
18842
18843    /**
18844     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18845     * on all Drawable objects associated with this view.
18846     * <p>
18847     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18848     * attached to this view.
18849     */
18850    @CallSuper
18851    public void jumpDrawablesToCurrentState() {
18852        if (mBackground != null) {
18853            mBackground.jumpToCurrentState();
18854        }
18855        if (mStateListAnimator != null) {
18856            mStateListAnimator.jumpToCurrentState();
18857        }
18858        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18859            mForegroundInfo.mDrawable.jumpToCurrentState();
18860        }
18861    }
18862
18863    /**
18864     * Sets the background color for this view.
18865     * @param color the color of the background
18866     */
18867    @RemotableViewMethod
18868    public void setBackgroundColor(@ColorInt int color) {
18869        if (mBackground instanceof ColorDrawable) {
18870            ((ColorDrawable) mBackground.mutate()).setColor(color);
18871            computeOpaqueFlags();
18872            mBackgroundResource = 0;
18873        } else {
18874            setBackground(new ColorDrawable(color));
18875        }
18876    }
18877
18878    /**
18879     * Set the background to a given resource. The resource should refer to
18880     * a Drawable object or 0 to remove the background.
18881     * @param resid The identifier of the resource.
18882     *
18883     * @attr ref android.R.styleable#View_background
18884     */
18885    @RemotableViewMethod
18886    public void setBackgroundResource(@DrawableRes int resid) {
18887        if (resid != 0 && resid == mBackgroundResource) {
18888            return;
18889        }
18890
18891        Drawable d = null;
18892        if (resid != 0) {
18893            d = mContext.getDrawable(resid);
18894        }
18895        setBackground(d);
18896
18897        mBackgroundResource = resid;
18898    }
18899
18900    /**
18901     * Set the background to a given Drawable, or remove the background. If the
18902     * background has padding, this View's padding is set to the background's
18903     * padding. However, when a background is removed, this View's padding isn't
18904     * touched. If setting the padding is desired, please use
18905     * {@link #setPadding(int, int, int, int)}.
18906     *
18907     * @param background The Drawable to use as the background, or null to remove the
18908     *        background
18909     */
18910    public void setBackground(Drawable background) {
18911        //noinspection deprecation
18912        setBackgroundDrawable(background);
18913    }
18914
18915    /**
18916     * @deprecated use {@link #setBackground(Drawable)} instead
18917     */
18918    @Deprecated
18919    public void setBackgroundDrawable(Drawable background) {
18920        computeOpaqueFlags();
18921
18922        if (background == mBackground) {
18923            return;
18924        }
18925
18926        boolean requestLayout = false;
18927
18928        mBackgroundResource = 0;
18929
18930        /*
18931         * Regardless of whether we're setting a new background or not, we want
18932         * to clear the previous drawable. setVisible first while we still have the callback set.
18933         */
18934        if (mBackground != null) {
18935            if (isAttachedToWindow()) {
18936                mBackground.setVisible(false, false);
18937            }
18938            mBackground.setCallback(null);
18939            unscheduleDrawable(mBackground);
18940        }
18941
18942        if (background != null) {
18943            Rect padding = sThreadLocal.get();
18944            if (padding == null) {
18945                padding = new Rect();
18946                sThreadLocal.set(padding);
18947            }
18948            resetResolvedDrawablesInternal();
18949            background.setLayoutDirection(getLayoutDirection());
18950            if (background.getPadding(padding)) {
18951                resetResolvedPaddingInternal();
18952                switch (background.getLayoutDirection()) {
18953                    case LAYOUT_DIRECTION_RTL:
18954                        mUserPaddingLeftInitial = padding.right;
18955                        mUserPaddingRightInitial = padding.left;
18956                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18957                        break;
18958                    case LAYOUT_DIRECTION_LTR:
18959                    default:
18960                        mUserPaddingLeftInitial = padding.left;
18961                        mUserPaddingRightInitial = padding.right;
18962                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18963                }
18964                mLeftPaddingDefined = false;
18965                mRightPaddingDefined = false;
18966            }
18967
18968            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18969            // if it has a different minimum size, we should layout again
18970            if (mBackground == null
18971                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18972                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18973                requestLayout = true;
18974            }
18975
18976            // Set mBackground before we set this as the callback and start making other
18977            // background drawable state change calls. In particular, the setVisible call below
18978            // can result in drawables attempting to start animations or otherwise invalidate,
18979            // which requires the view set as the callback (us) to recognize the drawable as
18980            // belonging to it as per verifyDrawable.
18981            mBackground = background;
18982            if (background.isStateful()) {
18983                background.setState(getDrawableState());
18984            }
18985            if (isAttachedToWindow()) {
18986                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18987            }
18988
18989            applyBackgroundTint();
18990
18991            // Set callback last, since the view may still be initializing.
18992            background.setCallback(this);
18993
18994            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18995                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18996                requestLayout = true;
18997            }
18998        } else {
18999            /* Remove the background */
19000            mBackground = null;
19001            if ((mViewFlags & WILL_NOT_DRAW) != 0
19002                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
19003                mPrivateFlags |= PFLAG_SKIP_DRAW;
19004            }
19005
19006            /*
19007             * When the background is set, we try to apply its padding to this
19008             * View. When the background is removed, we don't touch this View's
19009             * padding. This is noted in the Javadocs. Hence, we don't need to
19010             * requestLayout(), the invalidate() below is sufficient.
19011             */
19012
19013            // The old background's minimum size could have affected this
19014            // View's layout, so let's requestLayout
19015            requestLayout = true;
19016        }
19017
19018        computeOpaqueFlags();
19019
19020        if (requestLayout) {
19021            requestLayout();
19022        }
19023
19024        mBackgroundSizeChanged = true;
19025        invalidate(true);
19026        invalidateOutline();
19027    }
19028
19029    /**
19030     * Gets the background drawable
19031     *
19032     * @return The drawable used as the background for this view, if any.
19033     *
19034     * @see #setBackground(Drawable)
19035     *
19036     * @attr ref android.R.styleable#View_background
19037     */
19038    public Drawable getBackground() {
19039        return mBackground;
19040    }
19041
19042    /**
19043     * Applies a tint to the background drawable. Does not modify the current tint
19044     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19045     * <p>
19046     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
19047     * mutate the drawable and apply the specified tint and tint mode using
19048     * {@link Drawable#setTintList(ColorStateList)}.
19049     *
19050     * @param tint the tint to apply, may be {@code null} to clear tint
19051     *
19052     * @attr ref android.R.styleable#View_backgroundTint
19053     * @see #getBackgroundTintList()
19054     * @see Drawable#setTintList(ColorStateList)
19055     */
19056    public void setBackgroundTintList(@Nullable ColorStateList tint) {
19057        if (mBackgroundTint == null) {
19058            mBackgroundTint = new TintInfo();
19059        }
19060        mBackgroundTint.mTintList = tint;
19061        mBackgroundTint.mHasTintList = true;
19062
19063        applyBackgroundTint();
19064    }
19065
19066    /**
19067     * Return the tint applied to the background drawable, if specified.
19068     *
19069     * @return the tint applied to the background drawable
19070     * @attr ref android.R.styleable#View_backgroundTint
19071     * @see #setBackgroundTintList(ColorStateList)
19072     */
19073    @Nullable
19074    public ColorStateList getBackgroundTintList() {
19075        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
19076    }
19077
19078    /**
19079     * Specifies the blending mode used to apply the tint specified by
19080     * {@link #setBackgroundTintList(ColorStateList)}} to the background
19081     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19082     *
19083     * @param tintMode the blending mode used to apply the tint, may be
19084     *                 {@code null} to clear tint
19085     * @attr ref android.R.styleable#View_backgroundTintMode
19086     * @see #getBackgroundTintMode()
19087     * @see Drawable#setTintMode(PorterDuff.Mode)
19088     */
19089    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19090        if (mBackgroundTint == null) {
19091            mBackgroundTint = new TintInfo();
19092        }
19093        mBackgroundTint.mTintMode = tintMode;
19094        mBackgroundTint.mHasTintMode = true;
19095
19096        applyBackgroundTint();
19097    }
19098
19099    /**
19100     * Return the blending mode used to apply the tint to the background
19101     * drawable, if specified.
19102     *
19103     * @return the blending mode used to apply the tint to the background
19104     *         drawable
19105     * @attr ref android.R.styleable#View_backgroundTintMode
19106     * @see #setBackgroundTintMode(PorterDuff.Mode)
19107     */
19108    @Nullable
19109    public PorterDuff.Mode getBackgroundTintMode() {
19110        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
19111    }
19112
19113    private void applyBackgroundTint() {
19114        if (mBackground != null && mBackgroundTint != null) {
19115            final TintInfo tintInfo = mBackgroundTint;
19116            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19117                mBackground = mBackground.mutate();
19118
19119                if (tintInfo.mHasTintList) {
19120                    mBackground.setTintList(tintInfo.mTintList);
19121                }
19122
19123                if (tintInfo.mHasTintMode) {
19124                    mBackground.setTintMode(tintInfo.mTintMode);
19125                }
19126
19127                // The drawable (or one of its children) may not have been
19128                // stateful before applying the tint, so let's try again.
19129                if (mBackground.isStateful()) {
19130                    mBackground.setState(getDrawableState());
19131                }
19132            }
19133        }
19134    }
19135
19136    /**
19137     * Returns the drawable used as the foreground of this View. The
19138     * foreground drawable, if non-null, is always drawn on top of the view's content.
19139     *
19140     * @return a Drawable or null if no foreground was set
19141     *
19142     * @see #onDrawForeground(Canvas)
19143     */
19144    public Drawable getForeground() {
19145        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19146    }
19147
19148    /**
19149     * Supply a Drawable that is to be rendered on top of all of the content in the view.
19150     *
19151     * @param foreground the Drawable to be drawn on top of the children
19152     *
19153     * @attr ref android.R.styleable#View_foreground
19154     */
19155    public void setForeground(Drawable foreground) {
19156        if (mForegroundInfo == null) {
19157            if (foreground == null) {
19158                // Nothing to do.
19159                return;
19160            }
19161            mForegroundInfo = new ForegroundInfo();
19162        }
19163
19164        if (foreground == mForegroundInfo.mDrawable) {
19165            // Nothing to do
19166            return;
19167        }
19168
19169        if (mForegroundInfo.mDrawable != null) {
19170            if (isAttachedToWindow()) {
19171                mForegroundInfo.mDrawable.setVisible(false, false);
19172            }
19173            mForegroundInfo.mDrawable.setCallback(null);
19174            unscheduleDrawable(mForegroundInfo.mDrawable);
19175        }
19176
19177        mForegroundInfo.mDrawable = foreground;
19178        mForegroundInfo.mBoundsChanged = true;
19179        if (foreground != null) {
19180            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19181                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19182            }
19183            foreground.setLayoutDirection(getLayoutDirection());
19184            if (foreground.isStateful()) {
19185                foreground.setState(getDrawableState());
19186            }
19187            applyForegroundTint();
19188            if (isAttachedToWindow()) {
19189                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19190            }
19191            // Set callback last, since the view may still be initializing.
19192            foreground.setCallback(this);
19193        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
19194            mPrivateFlags |= PFLAG_SKIP_DRAW;
19195        }
19196        requestLayout();
19197        invalidate();
19198    }
19199
19200    /**
19201     * Magic bit used to support features of framework-internal window decor implementation details.
19202     * This used to live exclusively in FrameLayout.
19203     *
19204     * @return true if the foreground should draw inside the padding region or false
19205     *         if it should draw inset by the view's padding
19206     * @hide internal use only; only used by FrameLayout and internal screen layouts.
19207     */
19208    public boolean isForegroundInsidePadding() {
19209        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
19210    }
19211
19212    /**
19213     * Describes how the foreground is positioned.
19214     *
19215     * @return foreground gravity.
19216     *
19217     * @see #setForegroundGravity(int)
19218     *
19219     * @attr ref android.R.styleable#View_foregroundGravity
19220     */
19221    public int getForegroundGravity() {
19222        return mForegroundInfo != null ? mForegroundInfo.mGravity
19223                : Gravity.START | Gravity.TOP;
19224    }
19225
19226    /**
19227     * Describes how the foreground is positioned. Defaults to START and TOP.
19228     *
19229     * @param gravity see {@link android.view.Gravity}
19230     *
19231     * @see #getForegroundGravity()
19232     *
19233     * @attr ref android.R.styleable#View_foregroundGravity
19234     */
19235    public void setForegroundGravity(int gravity) {
19236        if (mForegroundInfo == null) {
19237            mForegroundInfo = new ForegroundInfo();
19238        }
19239
19240        if (mForegroundInfo.mGravity != gravity) {
19241            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
19242                gravity |= Gravity.START;
19243            }
19244
19245            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
19246                gravity |= Gravity.TOP;
19247            }
19248
19249            mForegroundInfo.mGravity = gravity;
19250            requestLayout();
19251        }
19252    }
19253
19254    /**
19255     * Applies a tint to the foreground drawable. Does not modify the current tint
19256     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19257     * <p>
19258     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
19259     * mutate the drawable and apply the specified tint and tint mode using
19260     * {@link Drawable#setTintList(ColorStateList)}.
19261     *
19262     * @param tint the tint to apply, may be {@code null} to clear tint
19263     *
19264     * @attr ref android.R.styleable#View_foregroundTint
19265     * @see #getForegroundTintList()
19266     * @see Drawable#setTintList(ColorStateList)
19267     */
19268    public void setForegroundTintList(@Nullable ColorStateList tint) {
19269        if (mForegroundInfo == null) {
19270            mForegroundInfo = new ForegroundInfo();
19271        }
19272        if (mForegroundInfo.mTintInfo == null) {
19273            mForegroundInfo.mTintInfo = new TintInfo();
19274        }
19275        mForegroundInfo.mTintInfo.mTintList = tint;
19276        mForegroundInfo.mTintInfo.mHasTintList = true;
19277
19278        applyForegroundTint();
19279    }
19280
19281    /**
19282     * Return the tint applied to the foreground drawable, if specified.
19283     *
19284     * @return the tint applied to the foreground drawable
19285     * @attr ref android.R.styleable#View_foregroundTint
19286     * @see #setForegroundTintList(ColorStateList)
19287     */
19288    @Nullable
19289    public ColorStateList getForegroundTintList() {
19290        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19291                ? mForegroundInfo.mTintInfo.mTintList : null;
19292    }
19293
19294    /**
19295     * Specifies the blending mode used to apply the tint specified by
19296     * {@link #setForegroundTintList(ColorStateList)}} to the background
19297     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19298     *
19299     * @param tintMode the blending mode used to apply the tint, may be
19300     *                 {@code null} to clear tint
19301     * @attr ref android.R.styleable#View_foregroundTintMode
19302     * @see #getForegroundTintMode()
19303     * @see Drawable#setTintMode(PorterDuff.Mode)
19304     */
19305    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19306        if (mForegroundInfo == null) {
19307            mForegroundInfo = new ForegroundInfo();
19308        }
19309        if (mForegroundInfo.mTintInfo == null) {
19310            mForegroundInfo.mTintInfo = new TintInfo();
19311        }
19312        mForegroundInfo.mTintInfo.mTintMode = tintMode;
19313        mForegroundInfo.mTintInfo.mHasTintMode = true;
19314
19315        applyForegroundTint();
19316    }
19317
19318    /**
19319     * Return the blending mode used to apply the tint to the foreground
19320     * drawable, if specified.
19321     *
19322     * @return the blending mode used to apply the tint to the foreground
19323     *         drawable
19324     * @attr ref android.R.styleable#View_foregroundTintMode
19325     * @see #setForegroundTintMode(PorterDuff.Mode)
19326     */
19327    @Nullable
19328    public PorterDuff.Mode getForegroundTintMode() {
19329        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19330                ? mForegroundInfo.mTintInfo.mTintMode : null;
19331    }
19332
19333    private void applyForegroundTint() {
19334        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
19335                && mForegroundInfo.mTintInfo != null) {
19336            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
19337            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19338                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
19339
19340                if (tintInfo.mHasTintList) {
19341                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
19342                }
19343
19344                if (tintInfo.mHasTintMode) {
19345                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
19346                }
19347
19348                // The drawable (or one of its children) may not have been
19349                // stateful before applying the tint, so let's try again.
19350                if (mForegroundInfo.mDrawable.isStateful()) {
19351                    mForegroundInfo.mDrawable.setState(getDrawableState());
19352                }
19353            }
19354        }
19355    }
19356
19357    /**
19358     * Draw any foreground content for this view.
19359     *
19360     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
19361     * drawable or other view-specific decorations. The foreground is drawn on top of the
19362     * primary view content.</p>
19363     *
19364     * @param canvas canvas to draw into
19365     */
19366    public void onDrawForeground(Canvas canvas) {
19367        onDrawScrollIndicators(canvas);
19368        onDrawScrollBars(canvas);
19369
19370        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19371        if (foreground != null) {
19372            if (mForegroundInfo.mBoundsChanged) {
19373                mForegroundInfo.mBoundsChanged = false;
19374                final Rect selfBounds = mForegroundInfo.mSelfBounds;
19375                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
19376
19377                if (mForegroundInfo.mInsidePadding) {
19378                    selfBounds.set(0, 0, getWidth(), getHeight());
19379                } else {
19380                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
19381                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
19382                }
19383
19384                final int ld = getLayoutDirection();
19385                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
19386                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
19387                foreground.setBounds(overlayBounds);
19388            }
19389
19390            foreground.draw(canvas);
19391        }
19392    }
19393
19394    /**
19395     * Sets the padding. The view may add on the space required to display
19396     * the scrollbars, depending on the style and visibility of the scrollbars.
19397     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
19398     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
19399     * from the values set in this call.
19400     *
19401     * @attr ref android.R.styleable#View_padding
19402     * @attr ref android.R.styleable#View_paddingBottom
19403     * @attr ref android.R.styleable#View_paddingLeft
19404     * @attr ref android.R.styleable#View_paddingRight
19405     * @attr ref android.R.styleable#View_paddingTop
19406     * @param left the left padding in pixels
19407     * @param top the top padding in pixels
19408     * @param right the right padding in pixels
19409     * @param bottom the bottom padding in pixels
19410     */
19411    public void setPadding(int left, int top, int right, int bottom) {
19412        resetResolvedPaddingInternal();
19413
19414        mUserPaddingStart = UNDEFINED_PADDING;
19415        mUserPaddingEnd = UNDEFINED_PADDING;
19416
19417        mUserPaddingLeftInitial = left;
19418        mUserPaddingRightInitial = right;
19419
19420        mLeftPaddingDefined = true;
19421        mRightPaddingDefined = true;
19422
19423        internalSetPadding(left, top, right, bottom);
19424    }
19425
19426    /**
19427     * @hide
19428     */
19429    protected void internalSetPadding(int left, int top, int right, int bottom) {
19430        mUserPaddingLeft = left;
19431        mUserPaddingRight = right;
19432        mUserPaddingBottom = bottom;
19433
19434        final int viewFlags = mViewFlags;
19435        boolean changed = false;
19436
19437        // Common case is there are no scroll bars.
19438        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
19439            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
19440                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
19441                        ? 0 : getVerticalScrollbarWidth();
19442                switch (mVerticalScrollbarPosition) {
19443                    case SCROLLBAR_POSITION_DEFAULT:
19444                        if (isLayoutRtl()) {
19445                            left += offset;
19446                        } else {
19447                            right += offset;
19448                        }
19449                        break;
19450                    case SCROLLBAR_POSITION_RIGHT:
19451                        right += offset;
19452                        break;
19453                    case SCROLLBAR_POSITION_LEFT:
19454                        left += offset;
19455                        break;
19456                }
19457            }
19458            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
19459                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
19460                        ? 0 : getHorizontalScrollbarHeight();
19461            }
19462        }
19463
19464        if (mPaddingLeft != left) {
19465            changed = true;
19466            mPaddingLeft = left;
19467        }
19468        if (mPaddingTop != top) {
19469            changed = true;
19470            mPaddingTop = top;
19471        }
19472        if (mPaddingRight != right) {
19473            changed = true;
19474            mPaddingRight = right;
19475        }
19476        if (mPaddingBottom != bottom) {
19477            changed = true;
19478            mPaddingBottom = bottom;
19479        }
19480
19481        if (changed) {
19482            requestLayout();
19483            invalidateOutline();
19484        }
19485    }
19486
19487    /**
19488     * Sets the relative padding. The view may add on the space required to display
19489     * the scrollbars, depending on the style and visibility of the scrollbars.
19490     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
19491     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
19492     * from the values set in this call.
19493     *
19494     * @attr ref android.R.styleable#View_padding
19495     * @attr ref android.R.styleable#View_paddingBottom
19496     * @attr ref android.R.styleable#View_paddingStart
19497     * @attr ref android.R.styleable#View_paddingEnd
19498     * @attr ref android.R.styleable#View_paddingTop
19499     * @param start the start padding in pixels
19500     * @param top the top padding in pixels
19501     * @param end the end padding in pixels
19502     * @param bottom the bottom padding in pixels
19503     */
19504    public void setPaddingRelative(int start, int top, int end, int bottom) {
19505        resetResolvedPaddingInternal();
19506
19507        mUserPaddingStart = start;
19508        mUserPaddingEnd = end;
19509        mLeftPaddingDefined = true;
19510        mRightPaddingDefined = true;
19511
19512        switch(getLayoutDirection()) {
19513            case LAYOUT_DIRECTION_RTL:
19514                mUserPaddingLeftInitial = end;
19515                mUserPaddingRightInitial = start;
19516                internalSetPadding(end, top, start, bottom);
19517                break;
19518            case LAYOUT_DIRECTION_LTR:
19519            default:
19520                mUserPaddingLeftInitial = start;
19521                mUserPaddingRightInitial = end;
19522                internalSetPadding(start, top, end, bottom);
19523        }
19524    }
19525
19526    /**
19527     * Returns the top padding of this view.
19528     *
19529     * @return the top padding in pixels
19530     */
19531    public int getPaddingTop() {
19532        return mPaddingTop;
19533    }
19534
19535    /**
19536     * Returns the bottom padding of this view. If there are inset and enabled
19537     * scrollbars, this value may include the space required to display the
19538     * scrollbars as well.
19539     *
19540     * @return the bottom padding in pixels
19541     */
19542    public int getPaddingBottom() {
19543        return mPaddingBottom;
19544    }
19545
19546    /**
19547     * Returns the left padding of this view. If there are inset and enabled
19548     * scrollbars, this value may include the space required to display the
19549     * scrollbars as well.
19550     *
19551     * @return the left padding in pixels
19552     */
19553    public int getPaddingLeft() {
19554        if (!isPaddingResolved()) {
19555            resolvePadding();
19556        }
19557        return mPaddingLeft;
19558    }
19559
19560    /**
19561     * Returns the start padding of this view depending on its resolved layout direction.
19562     * If there are inset and enabled scrollbars, this value may include the space
19563     * required to display the scrollbars as well.
19564     *
19565     * @return the start padding in pixels
19566     */
19567    public int getPaddingStart() {
19568        if (!isPaddingResolved()) {
19569            resolvePadding();
19570        }
19571        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19572                mPaddingRight : mPaddingLeft;
19573    }
19574
19575    /**
19576     * Returns the right padding of this view. If there are inset and enabled
19577     * scrollbars, this value may include the space required to display the
19578     * scrollbars as well.
19579     *
19580     * @return the right padding in pixels
19581     */
19582    public int getPaddingRight() {
19583        if (!isPaddingResolved()) {
19584            resolvePadding();
19585        }
19586        return mPaddingRight;
19587    }
19588
19589    /**
19590     * Returns the end padding of this view depending on its resolved layout direction.
19591     * If there are inset and enabled scrollbars, this value may include the space
19592     * required to display the scrollbars as well.
19593     *
19594     * @return the end padding in pixels
19595     */
19596    public int getPaddingEnd() {
19597        if (!isPaddingResolved()) {
19598            resolvePadding();
19599        }
19600        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19601                mPaddingLeft : mPaddingRight;
19602    }
19603
19604    /**
19605     * Return if the padding has been set through relative values
19606     * {@link #setPaddingRelative(int, int, int, int)} or through
19607     * @attr ref android.R.styleable#View_paddingStart or
19608     * @attr ref android.R.styleable#View_paddingEnd
19609     *
19610     * @return true if the padding is relative or false if it is not.
19611     */
19612    public boolean isPaddingRelative() {
19613        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
19614    }
19615
19616    Insets computeOpticalInsets() {
19617        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
19618    }
19619
19620    /**
19621     * @hide
19622     */
19623    public void resetPaddingToInitialValues() {
19624        if (isRtlCompatibilityMode()) {
19625            mPaddingLeft = mUserPaddingLeftInitial;
19626            mPaddingRight = mUserPaddingRightInitial;
19627            return;
19628        }
19629        if (isLayoutRtl()) {
19630            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
19631            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
19632        } else {
19633            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
19634            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
19635        }
19636    }
19637
19638    /**
19639     * @hide
19640     */
19641    public Insets getOpticalInsets() {
19642        if (mLayoutInsets == null) {
19643            mLayoutInsets = computeOpticalInsets();
19644        }
19645        return mLayoutInsets;
19646    }
19647
19648    /**
19649     * Set this view's optical insets.
19650     *
19651     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
19652     * property. Views that compute their own optical insets should call it as part of measurement.
19653     * This method does not request layout. If you are setting optical insets outside of
19654     * measure/layout itself you will want to call requestLayout() yourself.
19655     * </p>
19656     * @hide
19657     */
19658    public void setOpticalInsets(Insets insets) {
19659        mLayoutInsets = insets;
19660    }
19661
19662    /**
19663     * Changes the selection state of this view. A view can be selected or not.
19664     * Note that selection is not the same as focus. Views are typically
19665     * selected in the context of an AdapterView like ListView or GridView;
19666     * the selected view is the view that is highlighted.
19667     *
19668     * @param selected true if the view must be selected, false otherwise
19669     */
19670    public void setSelected(boolean selected) {
19671        //noinspection DoubleNegation
19672        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19673            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19674            if (!selected) resetPressedState();
19675            invalidate(true);
19676            refreshDrawableState();
19677            dispatchSetSelected(selected);
19678            if (selected) {
19679                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19680            } else {
19681                notifyViewAccessibilityStateChangedIfNeeded(
19682                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19683            }
19684        }
19685    }
19686
19687    /**
19688     * Dispatch setSelected to all of this View's children.
19689     *
19690     * @see #setSelected(boolean)
19691     *
19692     * @param selected The new selected state
19693     */
19694    protected void dispatchSetSelected(boolean selected) {
19695    }
19696
19697    /**
19698     * Indicates the selection state of this view.
19699     *
19700     * @return true if the view is selected, false otherwise
19701     */
19702    @ViewDebug.ExportedProperty
19703    public boolean isSelected() {
19704        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19705    }
19706
19707    /**
19708     * Changes the activated state of this view. A view can be activated or not.
19709     * Note that activation is not the same as selection.  Selection is
19710     * a transient property, representing the view (hierarchy) the user is
19711     * currently interacting with.  Activation is a longer-term state that the
19712     * user can move views in and out of.  For example, in a list view with
19713     * single or multiple selection enabled, the views in the current selection
19714     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19715     * here.)  The activated state is propagated down to children of the view it
19716     * is set on.
19717     *
19718     * @param activated true if the view must be activated, false otherwise
19719     */
19720    public void setActivated(boolean activated) {
19721        //noinspection DoubleNegation
19722        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19723            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19724            invalidate(true);
19725            refreshDrawableState();
19726            dispatchSetActivated(activated);
19727        }
19728    }
19729
19730    /**
19731     * Dispatch setActivated to all of this View's children.
19732     *
19733     * @see #setActivated(boolean)
19734     *
19735     * @param activated The new activated state
19736     */
19737    protected void dispatchSetActivated(boolean activated) {
19738    }
19739
19740    /**
19741     * Indicates the activation state of this view.
19742     *
19743     * @return true if the view is activated, false otherwise
19744     */
19745    @ViewDebug.ExportedProperty
19746    public boolean isActivated() {
19747        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
19748    }
19749
19750    /**
19751     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
19752     * observer can be used to get notifications when global events, like
19753     * layout, happen.
19754     *
19755     * The returned ViewTreeObserver observer is not guaranteed to remain
19756     * valid for the lifetime of this View. If the caller of this method keeps
19757     * a long-lived reference to ViewTreeObserver, it should always check for
19758     * the return value of {@link ViewTreeObserver#isAlive()}.
19759     *
19760     * @return The ViewTreeObserver for this view's hierarchy.
19761     */
19762    public ViewTreeObserver getViewTreeObserver() {
19763        if (mAttachInfo != null) {
19764            return mAttachInfo.mTreeObserver;
19765        }
19766        if (mFloatingTreeObserver == null) {
19767            mFloatingTreeObserver = new ViewTreeObserver(mContext);
19768        }
19769        return mFloatingTreeObserver;
19770    }
19771
19772    /**
19773     * <p>Finds the topmost view in the current view hierarchy.</p>
19774     *
19775     * @return the topmost view containing this view
19776     */
19777    public View getRootView() {
19778        if (mAttachInfo != null) {
19779            final View v = mAttachInfo.mRootView;
19780            if (v != null) {
19781                return v;
19782            }
19783        }
19784
19785        View parent = this;
19786
19787        while (parent.mParent != null && parent.mParent instanceof View) {
19788            parent = (View) parent.mParent;
19789        }
19790
19791        return parent;
19792    }
19793
19794    /**
19795     * Transforms a motion event from view-local coordinates to on-screen
19796     * coordinates.
19797     *
19798     * @param ev the view-local motion event
19799     * @return false if the transformation could not be applied
19800     * @hide
19801     */
19802    public boolean toGlobalMotionEvent(MotionEvent ev) {
19803        final AttachInfo info = mAttachInfo;
19804        if (info == null) {
19805            return false;
19806        }
19807
19808        final Matrix m = info.mTmpMatrix;
19809        m.set(Matrix.IDENTITY_MATRIX);
19810        transformMatrixToGlobal(m);
19811        ev.transform(m);
19812        return true;
19813    }
19814
19815    /**
19816     * Transforms a motion event from on-screen coordinates to view-local
19817     * coordinates.
19818     *
19819     * @param ev the on-screen motion event
19820     * @return false if the transformation could not be applied
19821     * @hide
19822     */
19823    public boolean toLocalMotionEvent(MotionEvent ev) {
19824        final AttachInfo info = mAttachInfo;
19825        if (info == null) {
19826            return false;
19827        }
19828
19829        final Matrix m = info.mTmpMatrix;
19830        m.set(Matrix.IDENTITY_MATRIX);
19831        transformMatrixToLocal(m);
19832        ev.transform(m);
19833        return true;
19834    }
19835
19836    /**
19837     * Modifies the input matrix such that it maps view-local coordinates to
19838     * on-screen coordinates.
19839     *
19840     * @param m input matrix to modify
19841     * @hide
19842     */
19843    public void transformMatrixToGlobal(Matrix m) {
19844        final ViewParent parent = mParent;
19845        if (parent instanceof View) {
19846            final View vp = (View) parent;
19847            vp.transformMatrixToGlobal(m);
19848            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19849        } else if (parent instanceof ViewRootImpl) {
19850            final ViewRootImpl vr = (ViewRootImpl) parent;
19851            vr.transformMatrixToGlobal(m);
19852            m.preTranslate(0, -vr.mCurScrollY);
19853        }
19854
19855        m.preTranslate(mLeft, mTop);
19856
19857        if (!hasIdentityMatrix()) {
19858            m.preConcat(getMatrix());
19859        }
19860    }
19861
19862    /**
19863     * Modifies the input matrix such that it maps on-screen coordinates to
19864     * view-local coordinates.
19865     *
19866     * @param m input matrix to modify
19867     * @hide
19868     */
19869    public void transformMatrixToLocal(Matrix m) {
19870        final ViewParent parent = mParent;
19871        if (parent instanceof View) {
19872            final View vp = (View) parent;
19873            vp.transformMatrixToLocal(m);
19874            m.postTranslate(vp.mScrollX, vp.mScrollY);
19875        } else if (parent instanceof ViewRootImpl) {
19876            final ViewRootImpl vr = (ViewRootImpl) parent;
19877            vr.transformMatrixToLocal(m);
19878            m.postTranslate(0, vr.mCurScrollY);
19879        }
19880
19881        m.postTranslate(-mLeft, -mTop);
19882
19883        if (!hasIdentityMatrix()) {
19884            m.postConcat(getInverseMatrix());
19885        }
19886    }
19887
19888    /**
19889     * @hide
19890     */
19891    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19892            @ViewDebug.IntToString(from = 0, to = "x"),
19893            @ViewDebug.IntToString(from = 1, to = "y")
19894    })
19895    public int[] getLocationOnScreen() {
19896        int[] location = new int[2];
19897        getLocationOnScreen(location);
19898        return location;
19899    }
19900
19901    /**
19902     * <p>Computes the coordinates of this view on the screen. The argument
19903     * must be an array of two integers. After the method returns, the array
19904     * contains the x and y location in that order.</p>
19905     *
19906     * @param outLocation an array of two integers in which to hold the coordinates
19907     */
19908    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19909        getLocationInWindow(outLocation);
19910
19911        final AttachInfo info = mAttachInfo;
19912        if (info != null) {
19913            outLocation[0] += info.mWindowLeft;
19914            outLocation[1] += info.mWindowTop;
19915        }
19916    }
19917
19918    /**
19919     * <p>Computes the coordinates of this view in its window. The argument
19920     * must be an array of two integers. After the method returns, the array
19921     * contains the x and y location in that order.</p>
19922     *
19923     * @param outLocation an array of two integers in which to hold the coordinates
19924     */
19925    public void getLocationInWindow(@Size(2) int[] outLocation) {
19926        if (outLocation == null || outLocation.length < 2) {
19927            throw new IllegalArgumentException("outLocation must be an array of two integers");
19928        }
19929
19930        outLocation[0] = 0;
19931        outLocation[1] = 0;
19932
19933        transformFromViewToWindowSpace(outLocation);
19934    }
19935
19936    /** @hide */
19937    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19938        if (inOutLocation == null || inOutLocation.length < 2) {
19939            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19940        }
19941
19942        if (mAttachInfo == null) {
19943            // When the view is not attached to a window, this method does not make sense
19944            inOutLocation[0] = inOutLocation[1] = 0;
19945            return;
19946        }
19947
19948        float position[] = mAttachInfo.mTmpTransformLocation;
19949        position[0] = inOutLocation[0];
19950        position[1] = inOutLocation[1];
19951
19952        if (!hasIdentityMatrix()) {
19953            getMatrix().mapPoints(position);
19954        }
19955
19956        position[0] += mLeft;
19957        position[1] += mTop;
19958
19959        ViewParent viewParent = mParent;
19960        while (viewParent instanceof View) {
19961            final View view = (View) viewParent;
19962
19963            position[0] -= view.mScrollX;
19964            position[1] -= view.mScrollY;
19965
19966            if (!view.hasIdentityMatrix()) {
19967                view.getMatrix().mapPoints(position);
19968            }
19969
19970            position[0] += view.mLeft;
19971            position[1] += view.mTop;
19972
19973            viewParent = view.mParent;
19974         }
19975
19976        if (viewParent instanceof ViewRootImpl) {
19977            // *cough*
19978            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19979            position[1] -= vr.mCurScrollY;
19980        }
19981
19982        inOutLocation[0] = Math.round(position[0]);
19983        inOutLocation[1] = Math.round(position[1]);
19984    }
19985
19986    /**
19987     * {@hide}
19988     * @param id the id of the view to be found
19989     * @return the view of the specified id, null if cannot be found
19990     */
19991    protected View findViewTraversal(@IdRes int id) {
19992        if (id == mID) {
19993            return this;
19994        }
19995        return null;
19996    }
19997
19998    /**
19999     * {@hide}
20000     * @param tag the tag of the view to be found
20001     * @return the view of specified tag, null if cannot be found
20002     */
20003    protected View findViewWithTagTraversal(Object tag) {
20004        if (tag != null && tag.equals(mTag)) {
20005            return this;
20006        }
20007        return null;
20008    }
20009
20010    /**
20011     * {@hide}
20012     * @param predicate The predicate to evaluate.
20013     * @param childToSkip If not null, ignores this child during the recursive traversal.
20014     * @return The first view that matches the predicate or null.
20015     */
20016    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
20017        if (predicate.apply(this)) {
20018            return this;
20019        }
20020        return null;
20021    }
20022
20023    /**
20024     * Look for a child view with the given id.  If this view has the given
20025     * id, return this view.
20026     *
20027     * @param id The id to search for.
20028     * @return The view that has the given id in the hierarchy or null
20029     */
20030    @Nullable
20031    public final View findViewById(@IdRes int id) {
20032        if (id < 0) {
20033            return null;
20034        }
20035        return findViewTraversal(id);
20036    }
20037
20038    /**
20039     * Finds a view by its unuque and stable accessibility id.
20040     *
20041     * @param accessibilityId The searched accessibility id.
20042     * @return The found view.
20043     */
20044    final View findViewByAccessibilityId(int accessibilityId) {
20045        if (accessibilityId < 0) {
20046            return null;
20047        }
20048        View view = findViewByAccessibilityIdTraversal(accessibilityId);
20049        if (view != null) {
20050            return view.includeForAccessibility() ? view : null;
20051        }
20052        return null;
20053    }
20054
20055    /**
20056     * Performs the traversal to find a view by its unuque and stable accessibility id.
20057     *
20058     * <strong>Note:</strong>This method does not stop at the root namespace
20059     * boundary since the user can touch the screen at an arbitrary location
20060     * potentially crossing the root namespace bounday which will send an
20061     * accessibility event to accessibility services and they should be able
20062     * to obtain the event source. Also accessibility ids are guaranteed to be
20063     * unique in the window.
20064     *
20065     * @param accessibilityId The accessibility id.
20066     * @return The found view.
20067     *
20068     * @hide
20069     */
20070    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
20071        if (getAccessibilityViewId() == accessibilityId) {
20072            return this;
20073        }
20074        return null;
20075    }
20076
20077    /**
20078     * Look for a child view with the given tag.  If this view has the given
20079     * tag, return this view.
20080     *
20081     * @param tag The tag to search for, using "tag.equals(getTag())".
20082     * @return The View that has the given tag in the hierarchy or null
20083     */
20084    public final View findViewWithTag(Object tag) {
20085        if (tag == null) {
20086            return null;
20087        }
20088        return findViewWithTagTraversal(tag);
20089    }
20090
20091    /**
20092     * {@hide}
20093     * Look for a child view that matches the specified predicate.
20094     * If this view matches the predicate, return this view.
20095     *
20096     * @param predicate The predicate to evaluate.
20097     * @return The first view that matches the predicate or null.
20098     */
20099    public final View findViewByPredicate(Predicate<View> predicate) {
20100        return findViewByPredicateTraversal(predicate, null);
20101    }
20102
20103    /**
20104     * {@hide}
20105     * Look for a child view that matches the specified predicate,
20106     * starting with the specified view and its descendents and then
20107     * recusively searching the ancestors and siblings of that view
20108     * until this view is reached.
20109     *
20110     * This method is useful in cases where the predicate does not match
20111     * a single unique view (perhaps multiple views use the same id)
20112     * and we are trying to find the view that is "closest" in scope to the
20113     * starting view.
20114     *
20115     * @param start The view to start from.
20116     * @param predicate The predicate to evaluate.
20117     * @return The first view that matches the predicate or null.
20118     */
20119    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
20120        View childToSkip = null;
20121        for (;;) {
20122            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
20123            if (view != null || start == this) {
20124                return view;
20125            }
20126
20127            ViewParent parent = start.getParent();
20128            if (parent == null || !(parent instanceof View)) {
20129                return null;
20130            }
20131
20132            childToSkip = start;
20133            start = (View) parent;
20134        }
20135    }
20136
20137    /**
20138     * Sets the identifier for this view. The identifier does not have to be
20139     * unique in this view's hierarchy. The identifier should be a positive
20140     * number.
20141     *
20142     * @see #NO_ID
20143     * @see #getId()
20144     * @see #findViewById(int)
20145     *
20146     * @param id a number used to identify the view
20147     *
20148     * @attr ref android.R.styleable#View_id
20149     */
20150    public void setId(@IdRes int id) {
20151        mID = id;
20152        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
20153            mID = generateViewId();
20154        }
20155    }
20156
20157    /**
20158     * {@hide}
20159     *
20160     * @param isRoot true if the view belongs to the root namespace, false
20161     *        otherwise
20162     */
20163    public void setIsRootNamespace(boolean isRoot) {
20164        if (isRoot) {
20165            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
20166        } else {
20167            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
20168        }
20169    }
20170
20171    /**
20172     * {@hide}
20173     *
20174     * @return true if the view belongs to the root namespace, false otherwise
20175     */
20176    public boolean isRootNamespace() {
20177        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
20178    }
20179
20180    /**
20181     * Returns this view's identifier.
20182     *
20183     * @return a positive integer used to identify the view or {@link #NO_ID}
20184     *         if the view has no ID
20185     *
20186     * @see #setId(int)
20187     * @see #findViewById(int)
20188     * @attr ref android.R.styleable#View_id
20189     */
20190    @IdRes
20191    @ViewDebug.CapturedViewProperty
20192    public int getId() {
20193        return mID;
20194    }
20195
20196    /**
20197     * Returns this view's tag.
20198     *
20199     * @return the Object stored in this view as a tag, or {@code null} if not
20200     *         set
20201     *
20202     * @see #setTag(Object)
20203     * @see #getTag(int)
20204     */
20205    @ViewDebug.ExportedProperty
20206    public Object getTag() {
20207        return mTag;
20208    }
20209
20210    /**
20211     * Sets the tag associated with this view. A tag can be used to mark
20212     * a view in its hierarchy and does not have to be unique within the
20213     * hierarchy. Tags can also be used to store data within a view without
20214     * resorting to another data structure.
20215     *
20216     * @param tag an Object to tag the view with
20217     *
20218     * @see #getTag()
20219     * @see #setTag(int, Object)
20220     */
20221    public void setTag(final Object tag) {
20222        mTag = tag;
20223    }
20224
20225    /**
20226     * Returns the tag associated with this view and the specified key.
20227     *
20228     * @param key The key identifying the tag
20229     *
20230     * @return the Object stored in this view as a tag, or {@code null} if not
20231     *         set
20232     *
20233     * @see #setTag(int, Object)
20234     * @see #getTag()
20235     */
20236    public Object getTag(int key) {
20237        if (mKeyedTags != null) return mKeyedTags.get(key);
20238        return null;
20239    }
20240
20241    /**
20242     * Sets a tag associated with this view and a key. A tag can be used
20243     * to mark a view in its hierarchy and does not have to be unique within
20244     * the hierarchy. Tags can also be used to store data within a view
20245     * without resorting to another data structure.
20246     *
20247     * The specified key should be an id declared in the resources of the
20248     * application to ensure it is unique (see the <a
20249     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
20250     * Keys identified as belonging to
20251     * the Android framework or not associated with any package will cause
20252     * an {@link IllegalArgumentException} to be thrown.
20253     *
20254     * @param key The key identifying the tag
20255     * @param tag An Object to tag the view with
20256     *
20257     * @throws IllegalArgumentException If they specified key is not valid
20258     *
20259     * @see #setTag(Object)
20260     * @see #getTag(int)
20261     */
20262    public void setTag(int key, final Object tag) {
20263        // If the package id is 0x00 or 0x01, it's either an undefined package
20264        // or a framework id
20265        if ((key >>> 24) < 2) {
20266            throw new IllegalArgumentException("The key must be an application-specific "
20267                    + "resource id.");
20268        }
20269
20270        setKeyedTag(key, tag);
20271    }
20272
20273    /**
20274     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
20275     * framework id.
20276     *
20277     * @hide
20278     */
20279    public void setTagInternal(int key, Object tag) {
20280        if ((key >>> 24) != 0x1) {
20281            throw new IllegalArgumentException("The key must be a framework-specific "
20282                    + "resource id.");
20283        }
20284
20285        setKeyedTag(key, tag);
20286    }
20287
20288    private void setKeyedTag(int key, Object tag) {
20289        if (mKeyedTags == null) {
20290            mKeyedTags = new SparseArray<Object>(2);
20291        }
20292
20293        mKeyedTags.put(key, tag);
20294    }
20295
20296    /**
20297     * Prints information about this view in the log output, with the tag
20298     * {@link #VIEW_LOG_TAG}.
20299     *
20300     * @hide
20301     */
20302    public void debug() {
20303        debug(0);
20304    }
20305
20306    /**
20307     * Prints information about this view in the log output, with the tag
20308     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
20309     * indentation defined by the <code>depth</code>.
20310     *
20311     * @param depth the indentation level
20312     *
20313     * @hide
20314     */
20315    protected void debug(int depth) {
20316        String output = debugIndent(depth - 1);
20317
20318        output += "+ " + this;
20319        int id = getId();
20320        if (id != -1) {
20321            output += " (id=" + id + ")";
20322        }
20323        Object tag = getTag();
20324        if (tag != null) {
20325            output += " (tag=" + tag + ")";
20326        }
20327        Log.d(VIEW_LOG_TAG, output);
20328
20329        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
20330            output = debugIndent(depth) + " FOCUSED";
20331            Log.d(VIEW_LOG_TAG, output);
20332        }
20333
20334        output = debugIndent(depth);
20335        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
20336                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
20337                + "} ";
20338        Log.d(VIEW_LOG_TAG, output);
20339
20340        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
20341                || mPaddingBottom != 0) {
20342            output = debugIndent(depth);
20343            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
20344                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
20345            Log.d(VIEW_LOG_TAG, output);
20346        }
20347
20348        output = debugIndent(depth);
20349        output += "mMeasureWidth=" + mMeasuredWidth +
20350                " mMeasureHeight=" + mMeasuredHeight;
20351        Log.d(VIEW_LOG_TAG, output);
20352
20353        output = debugIndent(depth);
20354        if (mLayoutParams == null) {
20355            output += "BAD! no layout params";
20356        } else {
20357            output = mLayoutParams.debug(output);
20358        }
20359        Log.d(VIEW_LOG_TAG, output);
20360
20361        output = debugIndent(depth);
20362        output += "flags={";
20363        output += View.printFlags(mViewFlags);
20364        output += "}";
20365        Log.d(VIEW_LOG_TAG, output);
20366
20367        output = debugIndent(depth);
20368        output += "privateFlags={";
20369        output += View.printPrivateFlags(mPrivateFlags);
20370        output += "}";
20371        Log.d(VIEW_LOG_TAG, output);
20372    }
20373
20374    /**
20375     * Creates a string of whitespaces used for indentation.
20376     *
20377     * @param depth the indentation level
20378     * @return a String containing (depth * 2 + 3) * 2 white spaces
20379     *
20380     * @hide
20381     */
20382    protected static String debugIndent(int depth) {
20383        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
20384        for (int i = 0; i < (depth * 2) + 3; i++) {
20385            spaces.append(' ').append(' ');
20386        }
20387        return spaces.toString();
20388    }
20389
20390    /**
20391     * <p>Return the offset of the widget's text baseline from the widget's top
20392     * boundary. If this widget does not support baseline alignment, this
20393     * method returns -1. </p>
20394     *
20395     * @return the offset of the baseline within the widget's bounds or -1
20396     *         if baseline alignment is not supported
20397     */
20398    @ViewDebug.ExportedProperty(category = "layout")
20399    public int getBaseline() {
20400        return -1;
20401    }
20402
20403    /**
20404     * Returns whether the view hierarchy is currently undergoing a layout pass. This
20405     * information is useful to avoid situations such as calling {@link #requestLayout()} during
20406     * a layout pass.
20407     *
20408     * @return whether the view hierarchy is currently undergoing a layout pass
20409     */
20410    public boolean isInLayout() {
20411        ViewRootImpl viewRoot = getViewRootImpl();
20412        return (viewRoot != null && viewRoot.isInLayout());
20413    }
20414
20415    /**
20416     * Call this when something has changed which has invalidated the
20417     * layout of this view. This will schedule a layout pass of the view
20418     * tree. This should not be called while the view hierarchy is currently in a layout
20419     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
20420     * end of the current layout pass (and then layout will run again) or after the current
20421     * frame is drawn and the next layout occurs.
20422     *
20423     * <p>Subclasses which override this method should call the superclass method to
20424     * handle possible request-during-layout errors correctly.</p>
20425     */
20426    @CallSuper
20427    public void requestLayout() {
20428        if (mMeasureCache != null) mMeasureCache.clear();
20429
20430        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
20431            // Only trigger request-during-layout logic if this is the view requesting it,
20432            // not the views in its parent hierarchy
20433            ViewRootImpl viewRoot = getViewRootImpl();
20434            if (viewRoot != null && viewRoot.isInLayout()) {
20435                if (!viewRoot.requestLayoutDuringLayout(this)) {
20436                    return;
20437                }
20438            }
20439            mAttachInfo.mViewRequestingLayout = this;
20440        }
20441
20442        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20443        mPrivateFlags |= PFLAG_INVALIDATED;
20444
20445        if (mParent != null && !mParent.isLayoutRequested()) {
20446            mParent.requestLayout();
20447        }
20448        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
20449            mAttachInfo.mViewRequestingLayout = null;
20450        }
20451    }
20452
20453    /**
20454     * Forces this view to be laid out during the next layout pass.
20455     * This method does not call requestLayout() or forceLayout()
20456     * on the parent.
20457     */
20458    public void forceLayout() {
20459        if (mMeasureCache != null) mMeasureCache.clear();
20460
20461        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20462        mPrivateFlags |= PFLAG_INVALIDATED;
20463    }
20464
20465    /**
20466     * <p>
20467     * This is called to find out how big a view should be. The parent
20468     * supplies constraint information in the width and height parameters.
20469     * </p>
20470     *
20471     * <p>
20472     * The actual measurement work of a view is performed in
20473     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
20474     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
20475     * </p>
20476     *
20477     *
20478     * @param widthMeasureSpec Horizontal space requirements as imposed by the
20479     *        parent
20480     * @param heightMeasureSpec Vertical space requirements as imposed by the
20481     *        parent
20482     *
20483     * @see #onMeasure(int, int)
20484     */
20485    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
20486        boolean optical = isLayoutModeOptical(this);
20487        if (optical != isLayoutModeOptical(mParent)) {
20488            Insets insets = getOpticalInsets();
20489            int oWidth  = insets.left + insets.right;
20490            int oHeight = insets.top  + insets.bottom;
20491            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
20492            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
20493        }
20494
20495        // Suppress sign extension for the low bytes
20496        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
20497        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
20498
20499        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20500
20501        // Optimize layout by avoiding an extra EXACTLY pass when the view is
20502        // already measured as the correct size. In API 23 and below, this
20503        // extra pass is required to make LinearLayout re-distribute weight.
20504        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
20505                || heightMeasureSpec != mOldHeightMeasureSpec;
20506        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
20507                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
20508        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
20509                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
20510        final boolean needsLayout = specChanged
20511                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
20512
20513        if (forceLayout || needsLayout) {
20514            // first clears the measured dimension flag
20515            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
20516
20517            resolveRtlPropertiesIfNeeded();
20518
20519            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
20520            if (cacheIndex < 0 || sIgnoreMeasureCache) {
20521                // measure ourselves, this should set the measured dimension flag back
20522                onMeasure(widthMeasureSpec, heightMeasureSpec);
20523                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20524            } else {
20525                long value = mMeasureCache.valueAt(cacheIndex);
20526                // Casting a long to int drops the high 32 bits, no mask needed
20527                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
20528                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20529            }
20530
20531            // flag not set, setMeasuredDimension() was not invoked, we raise
20532            // an exception to warn the developer
20533            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
20534                throw new IllegalStateException("View with id " + getId() + ": "
20535                        + getClass().getName() + "#onMeasure() did not set the"
20536                        + " measured dimension by calling"
20537                        + " setMeasuredDimension()");
20538            }
20539
20540            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
20541        }
20542
20543        mOldWidthMeasureSpec = widthMeasureSpec;
20544        mOldHeightMeasureSpec = heightMeasureSpec;
20545
20546        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
20547                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
20548    }
20549
20550    /**
20551     * <p>
20552     * Measure the view and its content to determine the measured width and the
20553     * measured height. This method is invoked by {@link #measure(int, int)} and
20554     * should be overridden by subclasses to provide accurate and efficient
20555     * measurement of their contents.
20556     * </p>
20557     *
20558     * <p>
20559     * <strong>CONTRACT:</strong> When overriding this method, you
20560     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
20561     * measured width and height of this view. Failure to do so will trigger an
20562     * <code>IllegalStateException</code>, thrown by
20563     * {@link #measure(int, int)}. Calling the superclass'
20564     * {@link #onMeasure(int, int)} is a valid use.
20565     * </p>
20566     *
20567     * <p>
20568     * The base class implementation of measure defaults to the background size,
20569     * unless a larger size is allowed by the MeasureSpec. Subclasses should
20570     * override {@link #onMeasure(int, int)} to provide better measurements of
20571     * their content.
20572     * </p>
20573     *
20574     * <p>
20575     * If this method is overridden, it is the subclass's responsibility to make
20576     * sure the measured height and width are at least the view's minimum height
20577     * and width ({@link #getSuggestedMinimumHeight()} and
20578     * {@link #getSuggestedMinimumWidth()}).
20579     * </p>
20580     *
20581     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
20582     *                         The requirements are encoded with
20583     *                         {@link android.view.View.MeasureSpec}.
20584     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
20585     *                         The requirements are encoded with
20586     *                         {@link android.view.View.MeasureSpec}.
20587     *
20588     * @see #getMeasuredWidth()
20589     * @see #getMeasuredHeight()
20590     * @see #setMeasuredDimension(int, int)
20591     * @see #getSuggestedMinimumHeight()
20592     * @see #getSuggestedMinimumWidth()
20593     * @see android.view.View.MeasureSpec#getMode(int)
20594     * @see android.view.View.MeasureSpec#getSize(int)
20595     */
20596    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
20597        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
20598                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
20599    }
20600
20601    /**
20602     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
20603     * measured width and measured height. Failing to do so will trigger an
20604     * exception at measurement time.</p>
20605     *
20606     * @param measuredWidth The measured width of this view.  May be a complex
20607     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20608     * {@link #MEASURED_STATE_TOO_SMALL}.
20609     * @param measuredHeight The measured height of this view.  May be a complex
20610     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20611     * {@link #MEASURED_STATE_TOO_SMALL}.
20612     */
20613    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
20614        boolean optical = isLayoutModeOptical(this);
20615        if (optical != isLayoutModeOptical(mParent)) {
20616            Insets insets = getOpticalInsets();
20617            int opticalWidth  = insets.left + insets.right;
20618            int opticalHeight = insets.top  + insets.bottom;
20619
20620            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
20621            measuredHeight += optical ? opticalHeight : -opticalHeight;
20622        }
20623        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
20624    }
20625
20626    /**
20627     * Sets the measured dimension without extra processing for things like optical bounds.
20628     * Useful for reapplying consistent values that have already been cooked with adjustments
20629     * for optical bounds, etc. such as those from the measurement cache.
20630     *
20631     * @param measuredWidth The measured width of this view.  May be a complex
20632     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20633     * {@link #MEASURED_STATE_TOO_SMALL}.
20634     * @param measuredHeight The measured height of this view.  May be a complex
20635     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20636     * {@link #MEASURED_STATE_TOO_SMALL}.
20637     */
20638    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
20639        mMeasuredWidth = measuredWidth;
20640        mMeasuredHeight = measuredHeight;
20641
20642        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
20643    }
20644
20645    /**
20646     * Merge two states as returned by {@link #getMeasuredState()}.
20647     * @param curState The current state as returned from a view or the result
20648     * of combining multiple views.
20649     * @param newState The new view state to combine.
20650     * @return Returns a new integer reflecting the combination of the two
20651     * states.
20652     */
20653    public static int combineMeasuredStates(int curState, int newState) {
20654        return curState | newState;
20655    }
20656
20657    /**
20658     * Version of {@link #resolveSizeAndState(int, int, int)}
20659     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
20660     */
20661    public static int resolveSize(int size, int measureSpec) {
20662        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
20663    }
20664
20665    /**
20666     * Utility to reconcile a desired size and state, with constraints imposed
20667     * by a MeasureSpec. Will take the desired size, unless a different size
20668     * is imposed by the constraints. The returned value is a compound integer,
20669     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20670     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20671     * resulting size is smaller than the size the view wants to be.
20672     *
20673     * @param size How big the view wants to be.
20674     * @param measureSpec Constraints imposed by the parent.
20675     * @param childMeasuredState Size information bit mask for the view's
20676     *                           children.
20677     * @return Size information bit mask as defined by
20678     *         {@link #MEASURED_SIZE_MASK} and
20679     *         {@link #MEASURED_STATE_TOO_SMALL}.
20680     */
20681    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20682        final int specMode = MeasureSpec.getMode(measureSpec);
20683        final int specSize = MeasureSpec.getSize(measureSpec);
20684        final int result;
20685        switch (specMode) {
20686            case MeasureSpec.AT_MOST:
20687                if (specSize < size) {
20688                    result = specSize | MEASURED_STATE_TOO_SMALL;
20689                } else {
20690                    result = size;
20691                }
20692                break;
20693            case MeasureSpec.EXACTLY:
20694                result = specSize;
20695                break;
20696            case MeasureSpec.UNSPECIFIED:
20697            default:
20698                result = size;
20699        }
20700        return result | (childMeasuredState & MEASURED_STATE_MASK);
20701    }
20702
20703    /**
20704     * Utility to return a default size. Uses the supplied size if the
20705     * MeasureSpec imposed no constraints. Will get larger if allowed
20706     * by the MeasureSpec.
20707     *
20708     * @param size Default size for this view
20709     * @param measureSpec Constraints imposed by the parent
20710     * @return The size this view should be.
20711     */
20712    public static int getDefaultSize(int size, int measureSpec) {
20713        int result = size;
20714        int specMode = MeasureSpec.getMode(measureSpec);
20715        int specSize = MeasureSpec.getSize(measureSpec);
20716
20717        switch (specMode) {
20718        case MeasureSpec.UNSPECIFIED:
20719            result = size;
20720            break;
20721        case MeasureSpec.AT_MOST:
20722        case MeasureSpec.EXACTLY:
20723            result = specSize;
20724            break;
20725        }
20726        return result;
20727    }
20728
20729    /**
20730     * Returns the suggested minimum height that the view should use. This
20731     * returns the maximum of the view's minimum height
20732     * and the background's minimum height
20733     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
20734     * <p>
20735     * When being used in {@link #onMeasure(int, int)}, the caller should still
20736     * ensure the returned height is within the requirements of the parent.
20737     *
20738     * @return The suggested minimum height of the view.
20739     */
20740    protected int getSuggestedMinimumHeight() {
20741        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
20742
20743    }
20744
20745    /**
20746     * Returns the suggested minimum width that the view should use. This
20747     * returns the maximum of the view's minimum width
20748     * and the background's minimum width
20749     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
20750     * <p>
20751     * When being used in {@link #onMeasure(int, int)}, the caller should still
20752     * ensure the returned width is within the requirements of the parent.
20753     *
20754     * @return The suggested minimum width of the view.
20755     */
20756    protected int getSuggestedMinimumWidth() {
20757        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
20758    }
20759
20760    /**
20761     * Returns the minimum height of the view.
20762     *
20763     * @return the minimum height the view will try to be, in pixels
20764     *
20765     * @see #setMinimumHeight(int)
20766     *
20767     * @attr ref android.R.styleable#View_minHeight
20768     */
20769    public int getMinimumHeight() {
20770        return mMinHeight;
20771    }
20772
20773    /**
20774     * Sets the minimum height of the view. It is not guaranteed the view will
20775     * be able to achieve this minimum height (for example, if its parent layout
20776     * constrains it with less available height).
20777     *
20778     * @param minHeight The minimum height the view will try to be, in pixels
20779     *
20780     * @see #getMinimumHeight()
20781     *
20782     * @attr ref android.R.styleable#View_minHeight
20783     */
20784    @RemotableViewMethod
20785    public void setMinimumHeight(int minHeight) {
20786        mMinHeight = minHeight;
20787        requestLayout();
20788    }
20789
20790    /**
20791     * Returns the minimum width of the view.
20792     *
20793     * @return the minimum width the view will try to be, in pixels
20794     *
20795     * @see #setMinimumWidth(int)
20796     *
20797     * @attr ref android.R.styleable#View_minWidth
20798     */
20799    public int getMinimumWidth() {
20800        return mMinWidth;
20801    }
20802
20803    /**
20804     * Sets the minimum width of the view. It is not guaranteed the view will
20805     * be able to achieve this minimum width (for example, if its parent layout
20806     * constrains it with less available width).
20807     *
20808     * @param minWidth The minimum width the view will try to be, in pixels
20809     *
20810     * @see #getMinimumWidth()
20811     *
20812     * @attr ref android.R.styleable#View_minWidth
20813     */
20814    public void setMinimumWidth(int minWidth) {
20815        mMinWidth = minWidth;
20816        requestLayout();
20817
20818    }
20819
20820    /**
20821     * Get the animation currently associated with this view.
20822     *
20823     * @return The animation that is currently playing or
20824     *         scheduled to play for this view.
20825     */
20826    public Animation getAnimation() {
20827        return mCurrentAnimation;
20828    }
20829
20830    /**
20831     * Start the specified animation now.
20832     *
20833     * @param animation the animation to start now
20834     */
20835    public void startAnimation(Animation animation) {
20836        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20837        setAnimation(animation);
20838        invalidateParentCaches();
20839        invalidate(true);
20840    }
20841
20842    /**
20843     * Cancels any animations for this view.
20844     */
20845    public void clearAnimation() {
20846        if (mCurrentAnimation != null) {
20847            mCurrentAnimation.detach();
20848        }
20849        mCurrentAnimation = null;
20850        invalidateParentIfNeeded();
20851    }
20852
20853    /**
20854     * Sets the next animation to play for this view.
20855     * If you want the animation to play immediately, use
20856     * {@link #startAnimation(android.view.animation.Animation)} instead.
20857     * This method provides allows fine-grained
20858     * control over the start time and invalidation, but you
20859     * must make sure that 1) the animation has a start time set, and
20860     * 2) the view's parent (which controls animations on its children)
20861     * will be invalidated when the animation is supposed to
20862     * start.
20863     *
20864     * @param animation The next animation, or null.
20865     */
20866    public void setAnimation(Animation animation) {
20867        mCurrentAnimation = animation;
20868
20869        if (animation != null) {
20870            // If the screen is off assume the animation start time is now instead of
20871            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20872            // would cause the animation to start when the screen turns back on
20873            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20874                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20875                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20876            }
20877            animation.reset();
20878        }
20879    }
20880
20881    /**
20882     * Invoked by a parent ViewGroup to notify the start of the animation
20883     * currently associated with this view. If you override this method,
20884     * always call super.onAnimationStart();
20885     *
20886     * @see #setAnimation(android.view.animation.Animation)
20887     * @see #getAnimation()
20888     */
20889    @CallSuper
20890    protected void onAnimationStart() {
20891        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20892    }
20893
20894    /**
20895     * Invoked by a parent ViewGroup to notify the end of the animation
20896     * currently associated with this view. If you override this method,
20897     * always call super.onAnimationEnd();
20898     *
20899     * @see #setAnimation(android.view.animation.Animation)
20900     * @see #getAnimation()
20901     */
20902    @CallSuper
20903    protected void onAnimationEnd() {
20904        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20905    }
20906
20907    /**
20908     * Invoked if there is a Transform that involves alpha. Subclass that can
20909     * draw themselves with the specified alpha should return true, and then
20910     * respect that alpha when their onDraw() is called. If this returns false
20911     * then the view may be redirected to draw into an offscreen buffer to
20912     * fulfill the request, which will look fine, but may be slower than if the
20913     * subclass handles it internally. The default implementation returns false.
20914     *
20915     * @param alpha The alpha (0..255) to apply to the view's drawing
20916     * @return true if the view can draw with the specified alpha.
20917     */
20918    protected boolean onSetAlpha(int alpha) {
20919        return false;
20920    }
20921
20922    /**
20923     * This is used by the RootView to perform an optimization when
20924     * the view hierarchy contains one or several SurfaceView.
20925     * SurfaceView is always considered transparent, but its children are not,
20926     * therefore all View objects remove themselves from the global transparent
20927     * region (passed as a parameter to this function).
20928     *
20929     * @param region The transparent region for this ViewAncestor (window).
20930     *
20931     * @return Returns true if the effective visibility of the view at this
20932     * point is opaque, regardless of the transparent region; returns false
20933     * if it is possible for underlying windows to be seen behind the view.
20934     *
20935     * {@hide}
20936     */
20937    public boolean gatherTransparentRegion(Region region) {
20938        final AttachInfo attachInfo = mAttachInfo;
20939        if (region != null && attachInfo != null) {
20940            final int pflags = mPrivateFlags;
20941            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20942                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20943                // remove it from the transparent region.
20944                final int[] location = attachInfo.mTransparentLocation;
20945                getLocationInWindow(location);
20946                // When a view has Z value, then it will be better to leave some area below the view
20947                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
20948                // the bottom part needs more offset than the left, top and right parts due to the
20949                // spot light effects.
20950                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
20951                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
20952                        location[0] + mRight - mLeft + shadowOffset,
20953                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
20954            } else {
20955                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20956                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20957                    // the background drawable's non-transparent parts from this transparent region.
20958                    applyDrawableToTransparentRegion(mBackground, region);
20959                }
20960                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20961                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20962                    // Similarly, we remove the foreground drawable's non-transparent parts.
20963                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20964                }
20965            }
20966        }
20967        return true;
20968    }
20969
20970    /**
20971     * Play a sound effect for this view.
20972     *
20973     * <p>The framework will play sound effects for some built in actions, such as
20974     * clicking, but you may wish to play these effects in your widget,
20975     * for instance, for internal navigation.
20976     *
20977     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20978     * {@link #isSoundEffectsEnabled()} is true.
20979     *
20980     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20981     */
20982    public void playSoundEffect(int soundConstant) {
20983        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20984            return;
20985        }
20986        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20987    }
20988
20989    /**
20990     * BZZZTT!!1!
20991     *
20992     * <p>Provide haptic feedback to the user for this view.
20993     *
20994     * <p>The framework will provide haptic feedback for some built in actions,
20995     * such as long presses, but you may wish to provide feedback for your
20996     * own widget.
20997     *
20998     * <p>The feedback will only be performed if
20999     * {@link #isHapticFeedbackEnabled()} is true.
21000     *
21001     * @param feedbackConstant One of the constants defined in
21002     * {@link HapticFeedbackConstants}
21003     */
21004    public boolean performHapticFeedback(int feedbackConstant) {
21005        return performHapticFeedback(feedbackConstant, 0);
21006    }
21007
21008    /**
21009     * BZZZTT!!1!
21010     *
21011     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
21012     *
21013     * @param feedbackConstant One of the constants defined in
21014     * {@link HapticFeedbackConstants}
21015     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
21016     */
21017    public boolean performHapticFeedback(int feedbackConstant, int flags) {
21018        if (mAttachInfo == null) {
21019            return false;
21020        }
21021        //noinspection SimplifiableIfStatement
21022        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
21023                && !isHapticFeedbackEnabled()) {
21024            return false;
21025        }
21026        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
21027                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
21028    }
21029
21030    /**
21031     * Request that the visibility of the status bar or other screen/window
21032     * decorations be changed.
21033     *
21034     * <p>This method is used to put the over device UI into temporary modes
21035     * where the user's attention is focused more on the application content,
21036     * by dimming or hiding surrounding system affordances.  This is typically
21037     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
21038     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
21039     * to be placed behind the action bar (and with these flags other system
21040     * affordances) so that smooth transitions between hiding and showing them
21041     * can be done.
21042     *
21043     * <p>Two representative examples of the use of system UI visibility is
21044     * implementing a content browsing application (like a magazine reader)
21045     * and a video playing application.
21046     *
21047     * <p>The first code shows a typical implementation of a View in a content
21048     * browsing application.  In this implementation, the application goes
21049     * into a content-oriented mode by hiding the status bar and action bar,
21050     * and putting the navigation elements into lights out mode.  The user can
21051     * then interact with content while in this mode.  Such an application should
21052     * provide an easy way for the user to toggle out of the mode (such as to
21053     * check information in the status bar or access notifications).  In the
21054     * implementation here, this is done simply by tapping on the content.
21055     *
21056     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
21057     *      content}
21058     *
21059     * <p>This second code sample shows a typical implementation of a View
21060     * in a video playing application.  In this situation, while the video is
21061     * playing the application would like to go into a complete full-screen mode,
21062     * to use as much of the display as possible for the video.  When in this state
21063     * the user can not interact with the application; the system intercepts
21064     * touching on the screen to pop the UI out of full screen mode.  See
21065     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
21066     *
21067     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
21068     *      content}
21069     *
21070     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21071     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21072     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21073     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21074     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21075     */
21076    public void setSystemUiVisibility(int visibility) {
21077        if (visibility != mSystemUiVisibility) {
21078            mSystemUiVisibility = visibility;
21079            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21080                mParent.recomputeViewAttributes(this);
21081            }
21082        }
21083    }
21084
21085    /**
21086     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
21087     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21088     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21089     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21090     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21091     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21092     */
21093    public int getSystemUiVisibility() {
21094        return mSystemUiVisibility;
21095    }
21096
21097    /**
21098     * Returns the current system UI visibility that is currently set for
21099     * the entire window.  This is the combination of the
21100     * {@link #setSystemUiVisibility(int)} values supplied by all of the
21101     * views in the window.
21102     */
21103    public int getWindowSystemUiVisibility() {
21104        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
21105    }
21106
21107    /**
21108     * Override to find out when the window's requested system UI visibility
21109     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
21110     * This is different from the callbacks received through
21111     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
21112     * in that this is only telling you about the local request of the window,
21113     * not the actual values applied by the system.
21114     */
21115    public void onWindowSystemUiVisibilityChanged(int visible) {
21116    }
21117
21118    /**
21119     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
21120     * the view hierarchy.
21121     */
21122    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
21123        onWindowSystemUiVisibilityChanged(visible);
21124    }
21125
21126    /**
21127     * Set a listener to receive callbacks when the visibility of the system bar changes.
21128     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
21129     */
21130    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
21131        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
21132        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21133            mParent.recomputeViewAttributes(this);
21134        }
21135    }
21136
21137    /**
21138     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
21139     * the view hierarchy.
21140     */
21141    public void dispatchSystemUiVisibilityChanged(int visibility) {
21142        ListenerInfo li = mListenerInfo;
21143        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
21144            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
21145                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
21146        }
21147    }
21148
21149    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
21150        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
21151        if (val != mSystemUiVisibility) {
21152            setSystemUiVisibility(val);
21153            return true;
21154        }
21155        return false;
21156    }
21157
21158    /** @hide */
21159    public void setDisabledSystemUiVisibility(int flags) {
21160        if (mAttachInfo != null) {
21161            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
21162                mAttachInfo.mDisabledSystemUiVisibility = flags;
21163                if (mParent != null) {
21164                    mParent.recomputeViewAttributes(this);
21165                }
21166            }
21167        }
21168    }
21169
21170    /**
21171     * Creates an image that the system displays during the drag and drop
21172     * operation. This is called a &quot;drag shadow&quot;. The default implementation
21173     * for a DragShadowBuilder based on a View returns an image that has exactly the same
21174     * appearance as the given View. The default also positions the center of the drag shadow
21175     * directly under the touch point. If no View is provided (the constructor with no parameters
21176     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
21177     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
21178     * default is an invisible drag shadow.
21179     * <p>
21180     * You are not required to use the View you provide to the constructor as the basis of the
21181     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
21182     * anything you want as the drag shadow.
21183     * </p>
21184     * <p>
21185     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
21186     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
21187     *  size and position of the drag shadow. It uses this data to construct a
21188     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
21189     *  so that your application can draw the shadow image in the Canvas.
21190     * </p>
21191     *
21192     * <div class="special reference">
21193     * <h3>Developer Guides</h3>
21194     * <p>For a guide to implementing drag and drop features, read the
21195     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
21196     * </div>
21197     */
21198    public static class DragShadowBuilder {
21199        private final WeakReference<View> mView;
21200
21201        /**
21202         * Constructs a shadow image builder based on a View. By default, the resulting drag
21203         * shadow will have the same appearance and dimensions as the View, with the touch point
21204         * over the center of the View.
21205         * @param view A View. Any View in scope can be used.
21206         */
21207        public DragShadowBuilder(View view) {
21208            mView = new WeakReference<View>(view);
21209        }
21210
21211        /**
21212         * Construct a shadow builder object with no associated View.  This
21213         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
21214         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
21215         * to supply the drag shadow's dimensions and appearance without
21216         * reference to any View object. If they are not overridden, then the result is an
21217         * invisible drag shadow.
21218         */
21219        public DragShadowBuilder() {
21220            mView = new WeakReference<View>(null);
21221        }
21222
21223        /**
21224         * Returns the View object that had been passed to the
21225         * {@link #View.DragShadowBuilder(View)}
21226         * constructor.  If that View parameter was {@code null} or if the
21227         * {@link #View.DragShadowBuilder()}
21228         * constructor was used to instantiate the builder object, this method will return
21229         * null.
21230         *
21231         * @return The View object associate with this builder object.
21232         */
21233        @SuppressWarnings({"JavadocReference"})
21234        final public View getView() {
21235            return mView.get();
21236        }
21237
21238        /**
21239         * Provides the metrics for the shadow image. These include the dimensions of
21240         * the shadow image, and the point within that shadow that should
21241         * be centered under the touch location while dragging.
21242         * <p>
21243         * The default implementation sets the dimensions of the shadow to be the
21244         * same as the dimensions of the View itself and centers the shadow under
21245         * the touch point.
21246         * </p>
21247         *
21248         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
21249         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
21250         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
21251         * image.
21252         *
21253         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
21254         * shadow image that should be underneath the touch point during the drag and drop
21255         * operation. Your application must set {@link android.graphics.Point#x} to the
21256         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
21257         */
21258        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
21259            final View view = mView.get();
21260            if (view != null) {
21261                outShadowSize.set(view.getWidth(), view.getHeight());
21262                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
21263            } else {
21264                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
21265            }
21266        }
21267
21268        /**
21269         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
21270         * based on the dimensions it received from the
21271         * {@link #onProvideShadowMetrics(Point, Point)} callback.
21272         *
21273         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
21274         */
21275        public void onDrawShadow(Canvas canvas) {
21276            final View view = mView.get();
21277            if (view != null) {
21278                view.draw(canvas);
21279            } else {
21280                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
21281            }
21282        }
21283    }
21284
21285    /**
21286     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
21287     * startDragAndDrop()} for newer platform versions.
21288     */
21289    @Deprecated
21290    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
21291                                   Object myLocalState, int flags) {
21292        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
21293    }
21294
21295    /**
21296     * Starts a drag and drop operation. When your application calls this method, it passes a
21297     * {@link android.view.View.DragShadowBuilder} object to the system. The
21298     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
21299     * to get metrics for the drag shadow, and then calls the object's
21300     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
21301     * <p>
21302     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
21303     *  drag events to all the View objects in your application that are currently visible. It does
21304     *  this either by calling the View object's drag listener (an implementation of
21305     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
21306     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
21307     *  Both are passed a {@link android.view.DragEvent} object that has a
21308     *  {@link android.view.DragEvent#getAction()} value of
21309     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
21310     * </p>
21311     * <p>
21312     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
21313     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
21314     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
21315     * to the View the user selected for dragging.
21316     * </p>
21317     * @param data A {@link android.content.ClipData} object pointing to the data to be
21318     * transferred by the drag and drop operation.
21319     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21320     * drag shadow.
21321     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
21322     * drop operation. When dispatching drag events to views in the same activity this object
21323     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
21324     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
21325     * will return null).
21326     * <p>
21327     * myLocalState is a lightweight mechanism for the sending information from the dragged View
21328     * to the target Views. For example, it can contain flags that differentiate between a
21329     * a copy operation and a move operation.
21330     * </p>
21331     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
21332     * flags, or any combination of the following:
21333     *     <ul>
21334     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
21335     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
21336     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
21337     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
21338     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
21339     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
21340     *     </ul>
21341     * @return {@code true} if the method completes successfully, or
21342     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
21343     * do a drag, and so no drag operation is in progress.
21344     */
21345    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
21346            Object myLocalState, int flags) {
21347        if (ViewDebug.DEBUG_DRAG) {
21348            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
21349        }
21350        if (mAttachInfo == null) {
21351            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
21352            return false;
21353        }
21354
21355        if (data != null) {
21356            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
21357        }
21358
21359        boolean okay = false;
21360
21361        Point shadowSize = new Point();
21362        Point shadowTouchPoint = new Point();
21363        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
21364
21365        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
21366                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
21367            throw new IllegalStateException("Drag shadow dimensions must not be negative");
21368        }
21369
21370        if (ViewDebug.DEBUG_DRAG) {
21371            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
21372                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
21373        }
21374        if (mAttachInfo.mDragSurface != null) {
21375            mAttachInfo.mDragSurface.release();
21376        }
21377        mAttachInfo.mDragSurface = new Surface();
21378        try {
21379            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
21380                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
21381            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
21382                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
21383            if (mAttachInfo.mDragToken != null) {
21384                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21385                try {
21386                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21387                    shadowBuilder.onDrawShadow(canvas);
21388                } finally {
21389                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21390                }
21391
21392                final ViewRootImpl root = getViewRootImpl();
21393
21394                // Cache the local state object for delivery with DragEvents
21395                root.setLocalDragState(myLocalState);
21396
21397                // repurpose 'shadowSize' for the last touch point
21398                root.getLastTouchPoint(shadowSize);
21399
21400                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
21401                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
21402                        shadowTouchPoint.x, shadowTouchPoint.y, data);
21403                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
21404            }
21405        } catch (Exception e) {
21406            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
21407            mAttachInfo.mDragSurface.destroy();
21408            mAttachInfo.mDragSurface = null;
21409        }
21410
21411        return okay;
21412    }
21413
21414    /**
21415     * Cancels an ongoing drag and drop operation.
21416     * <p>
21417     * A {@link android.view.DragEvent} object with
21418     * {@link android.view.DragEvent#getAction()} value of
21419     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
21420     * {@link android.view.DragEvent#getResult()} value of {@code false}
21421     * will be sent to every
21422     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
21423     * even if they are not currently visible.
21424     * </p>
21425     * <p>
21426     * This method can be called on any View in the same window as the View on which
21427     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
21428     * was called.
21429     * </p>
21430     */
21431    public final void cancelDragAndDrop() {
21432        if (ViewDebug.DEBUG_DRAG) {
21433            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
21434        }
21435        if (mAttachInfo == null) {
21436            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
21437            return;
21438        }
21439        if (mAttachInfo.mDragToken != null) {
21440            try {
21441                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
21442            } catch (Exception e) {
21443                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
21444            }
21445            mAttachInfo.mDragToken = null;
21446        } else {
21447            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
21448        }
21449    }
21450
21451    /**
21452     * Updates the drag shadow for the ongoing drag and drop operation.
21453     *
21454     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21455     * new drag shadow.
21456     */
21457    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
21458        if (ViewDebug.DEBUG_DRAG) {
21459            Log.d(VIEW_LOG_TAG, "updateDragShadow");
21460        }
21461        if (mAttachInfo == null) {
21462            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
21463            return;
21464        }
21465        if (mAttachInfo.mDragToken != null) {
21466            try {
21467                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21468                try {
21469                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21470                    shadowBuilder.onDrawShadow(canvas);
21471                } finally {
21472                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21473                }
21474            } catch (Exception e) {
21475                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
21476            }
21477        } else {
21478            Log.e(VIEW_LOG_TAG, "No active drag");
21479        }
21480    }
21481
21482    /**
21483     * Starts a move from {startX, startY}, the amount of the movement will be the offset
21484     * between {startX, startY} and the new cursor positon.
21485     * @param startX horizontal coordinate where the move started.
21486     * @param startY vertical coordinate where the move started.
21487     * @return whether moving was started successfully.
21488     * @hide
21489     */
21490    public final boolean startMovingTask(float startX, float startY) {
21491        if (ViewDebug.DEBUG_POSITIONING) {
21492            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
21493        }
21494        try {
21495            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
21496        } catch (RemoteException e) {
21497            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
21498        }
21499        return false;
21500    }
21501
21502    /**
21503     * Handles drag events sent by the system following a call to
21504     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
21505     * startDragAndDrop()}.
21506     *<p>
21507     * When the system calls this method, it passes a
21508     * {@link android.view.DragEvent} object. A call to
21509     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
21510     * in DragEvent. The method uses these to determine what is happening in the drag and drop
21511     * operation.
21512     * @param event The {@link android.view.DragEvent} sent by the system.
21513     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
21514     * in DragEvent, indicating the type of drag event represented by this object.
21515     * @return {@code true} if the method was successful, otherwise {@code false}.
21516     * <p>
21517     *  The method should return {@code true} in response to an action type of
21518     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
21519     *  operation.
21520     * </p>
21521     * <p>
21522     *  The method should also return {@code true} in response to an action type of
21523     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
21524     *  {@code false} if it didn't.
21525     * </p>
21526     * <p>
21527     *  For all other events, the return value is ignored.
21528     * </p>
21529     */
21530    public boolean onDragEvent(DragEvent event) {
21531        return false;
21532    }
21533
21534    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
21535    boolean dispatchDragEnterExitInPreN(DragEvent event) {
21536        return callDragEventHandler(event);
21537    }
21538
21539    /**
21540     * Detects if this View is enabled and has a drag event listener.
21541     * If both are true, then it calls the drag event listener with the
21542     * {@link android.view.DragEvent} it received. If the drag event listener returns
21543     * {@code true}, then dispatchDragEvent() returns {@code true}.
21544     * <p>
21545     * For all other cases, the method calls the
21546     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
21547     * method and returns its result.
21548     * </p>
21549     * <p>
21550     * This ensures that a drag event is always consumed, even if the View does not have a drag
21551     * event listener. However, if the View has a listener and the listener returns true, then
21552     * onDragEvent() is not called.
21553     * </p>
21554     */
21555    public boolean dispatchDragEvent(DragEvent event) {
21556        event.mEventHandlerWasCalled = true;
21557        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
21558            event.mAction == DragEvent.ACTION_DROP) {
21559            // About to deliver an event with coordinates to this view. Notify that now this view
21560            // has drag focus. This will send exit/enter events as needed.
21561            getViewRootImpl().setDragFocus(this, event);
21562        }
21563        return callDragEventHandler(event);
21564    }
21565
21566    final boolean callDragEventHandler(DragEvent event) {
21567        final boolean result;
21568
21569        ListenerInfo li = mListenerInfo;
21570        //noinspection SimplifiableIfStatement
21571        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
21572                && li.mOnDragListener.onDrag(this, event)) {
21573            result = true;
21574        } else {
21575            result = onDragEvent(event);
21576        }
21577
21578        switch (event.mAction) {
21579            case DragEvent.ACTION_DRAG_ENTERED: {
21580                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
21581                refreshDrawableState();
21582            } break;
21583            case DragEvent.ACTION_DRAG_EXITED: {
21584                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
21585                refreshDrawableState();
21586            } break;
21587            case DragEvent.ACTION_DRAG_ENDED: {
21588                mPrivateFlags2 &= ~View.DRAG_MASK;
21589                refreshDrawableState();
21590            } break;
21591        }
21592
21593        return result;
21594    }
21595
21596    boolean canAcceptDrag() {
21597        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
21598    }
21599
21600    /**
21601     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
21602     * it is ever exposed at all.
21603     * @hide
21604     */
21605    public void onCloseSystemDialogs(String reason) {
21606    }
21607
21608    /**
21609     * Given a Drawable whose bounds have been set to draw into this view,
21610     * update a Region being computed for
21611     * {@link #gatherTransparentRegion(android.graphics.Region)} so
21612     * that any non-transparent parts of the Drawable are removed from the
21613     * given transparent region.
21614     *
21615     * @param dr The Drawable whose transparency is to be applied to the region.
21616     * @param region A Region holding the current transparency information,
21617     * where any parts of the region that are set are considered to be
21618     * transparent.  On return, this region will be modified to have the
21619     * transparency information reduced by the corresponding parts of the
21620     * Drawable that are not transparent.
21621     * {@hide}
21622     */
21623    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
21624        if (DBG) {
21625            Log.i("View", "Getting transparent region for: " + this);
21626        }
21627        final Region r = dr.getTransparentRegion();
21628        final Rect db = dr.getBounds();
21629        final AttachInfo attachInfo = mAttachInfo;
21630        if (r != null && attachInfo != null) {
21631            final int w = getRight()-getLeft();
21632            final int h = getBottom()-getTop();
21633            if (db.left > 0) {
21634                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
21635                r.op(0, 0, db.left, h, Region.Op.UNION);
21636            }
21637            if (db.right < w) {
21638                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
21639                r.op(db.right, 0, w, h, Region.Op.UNION);
21640            }
21641            if (db.top > 0) {
21642                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
21643                r.op(0, 0, w, db.top, Region.Op.UNION);
21644            }
21645            if (db.bottom < h) {
21646                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
21647                r.op(0, db.bottom, w, h, Region.Op.UNION);
21648            }
21649            final int[] location = attachInfo.mTransparentLocation;
21650            getLocationInWindow(location);
21651            r.translate(location[0], location[1]);
21652            region.op(r, Region.Op.INTERSECT);
21653        } else {
21654            region.op(db, Region.Op.DIFFERENCE);
21655        }
21656    }
21657
21658    private void checkForLongClick(int delayOffset, float x, float y) {
21659        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
21660            mHasPerformedLongPress = false;
21661
21662            if (mPendingCheckForLongPress == null) {
21663                mPendingCheckForLongPress = new CheckForLongPress();
21664            }
21665            mPendingCheckForLongPress.setAnchor(x, y);
21666            mPendingCheckForLongPress.rememberWindowAttachCount();
21667            mPendingCheckForLongPress.rememberPressedState();
21668            postDelayed(mPendingCheckForLongPress,
21669                    ViewConfiguration.getLongPressTimeout() - delayOffset);
21670        }
21671    }
21672
21673    /**
21674     * Inflate a view from an XML resource.  This convenience method wraps the {@link
21675     * LayoutInflater} class, which provides a full range of options for view inflation.
21676     *
21677     * @param context The Context object for your activity or application.
21678     * @param resource The resource ID to inflate
21679     * @param root A view group that will be the parent.  Used to properly inflate the
21680     * layout_* parameters.
21681     * @see LayoutInflater
21682     */
21683    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
21684        LayoutInflater factory = LayoutInflater.from(context);
21685        return factory.inflate(resource, root);
21686    }
21687
21688    /**
21689     * Scroll the view with standard behavior for scrolling beyond the normal
21690     * content boundaries. Views that call this method should override
21691     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
21692     * results of an over-scroll operation.
21693     *
21694     * Views can use this method to handle any touch or fling-based scrolling.
21695     *
21696     * @param deltaX Change in X in pixels
21697     * @param deltaY Change in Y in pixels
21698     * @param scrollX Current X scroll value in pixels before applying deltaX
21699     * @param scrollY Current Y scroll value in pixels before applying deltaY
21700     * @param scrollRangeX Maximum content scroll range along the X axis
21701     * @param scrollRangeY Maximum content scroll range along the Y axis
21702     * @param maxOverScrollX Number of pixels to overscroll by in either direction
21703     *          along the X axis.
21704     * @param maxOverScrollY Number of pixels to overscroll by in either direction
21705     *          along the Y axis.
21706     * @param isTouchEvent true if this scroll operation is the result of a touch event.
21707     * @return true if scrolling was clamped to an over-scroll boundary along either
21708     *          axis, false otherwise.
21709     */
21710    @SuppressWarnings({"UnusedParameters"})
21711    protected boolean overScrollBy(int deltaX, int deltaY,
21712            int scrollX, int scrollY,
21713            int scrollRangeX, int scrollRangeY,
21714            int maxOverScrollX, int maxOverScrollY,
21715            boolean isTouchEvent) {
21716        final int overScrollMode = mOverScrollMode;
21717        final boolean canScrollHorizontal =
21718                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21719        final boolean canScrollVertical =
21720                computeVerticalScrollRange() > computeVerticalScrollExtent();
21721        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21722                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21723        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21724                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21725
21726        int newScrollX = scrollX + deltaX;
21727        if (!overScrollHorizontal) {
21728            maxOverScrollX = 0;
21729        }
21730
21731        int newScrollY = scrollY + deltaY;
21732        if (!overScrollVertical) {
21733            maxOverScrollY = 0;
21734        }
21735
21736        // Clamp values if at the limits and record
21737        final int left = -maxOverScrollX;
21738        final int right = maxOverScrollX + scrollRangeX;
21739        final int top = -maxOverScrollY;
21740        final int bottom = maxOverScrollY + scrollRangeY;
21741
21742        boolean clampedX = false;
21743        if (newScrollX > right) {
21744            newScrollX = right;
21745            clampedX = true;
21746        } else if (newScrollX < left) {
21747            newScrollX = left;
21748            clampedX = true;
21749        }
21750
21751        boolean clampedY = false;
21752        if (newScrollY > bottom) {
21753            newScrollY = bottom;
21754            clampedY = true;
21755        } else if (newScrollY < top) {
21756            newScrollY = top;
21757            clampedY = true;
21758        }
21759
21760        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
21761
21762        return clampedX || clampedY;
21763    }
21764
21765    /**
21766     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
21767     * respond to the results of an over-scroll operation.
21768     *
21769     * @param scrollX New X scroll value in pixels
21770     * @param scrollY New Y scroll value in pixels
21771     * @param clampedX True if scrollX was clamped to an over-scroll boundary
21772     * @param clampedY True if scrollY was clamped to an over-scroll boundary
21773     */
21774    protected void onOverScrolled(int scrollX, int scrollY,
21775            boolean clampedX, boolean clampedY) {
21776        // Intentionally empty.
21777    }
21778
21779    /**
21780     * Returns the over-scroll mode for this view. The result will be
21781     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21782     * (allow over-scrolling only if the view content is larger than the container),
21783     * or {@link #OVER_SCROLL_NEVER}.
21784     *
21785     * @return This view's over-scroll mode.
21786     */
21787    public int getOverScrollMode() {
21788        return mOverScrollMode;
21789    }
21790
21791    /**
21792     * Set the over-scroll mode for this view. Valid over-scroll modes are
21793     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21794     * (allow over-scrolling only if the view content is larger than the container),
21795     * or {@link #OVER_SCROLL_NEVER}.
21796     *
21797     * Setting the over-scroll mode of a view will have an effect only if the
21798     * view is capable of scrolling.
21799     *
21800     * @param overScrollMode The new over-scroll mode for this view.
21801     */
21802    public void setOverScrollMode(int overScrollMode) {
21803        if (overScrollMode != OVER_SCROLL_ALWAYS &&
21804                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
21805                overScrollMode != OVER_SCROLL_NEVER) {
21806            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
21807        }
21808        mOverScrollMode = overScrollMode;
21809    }
21810
21811    /**
21812     * Enable or disable nested scrolling for this view.
21813     *
21814     * <p>If this property is set to true the view will be permitted to initiate nested
21815     * scrolling operations with a compatible parent view in the current hierarchy. If this
21816     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
21817     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
21818     * the nested scroll.</p>
21819     *
21820     * @param enabled true to enable nested scrolling, false to disable
21821     *
21822     * @see #isNestedScrollingEnabled()
21823     */
21824    public void setNestedScrollingEnabled(boolean enabled) {
21825        if (enabled) {
21826            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
21827        } else {
21828            stopNestedScroll();
21829            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
21830        }
21831    }
21832
21833    /**
21834     * Returns true if nested scrolling is enabled for this view.
21835     *
21836     * <p>If nested scrolling is enabled and this View class implementation supports it,
21837     * this view will act as a nested scrolling child view when applicable, forwarding data
21838     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21839     * parent.</p>
21840     *
21841     * @return true if nested scrolling is enabled
21842     *
21843     * @see #setNestedScrollingEnabled(boolean)
21844     */
21845    public boolean isNestedScrollingEnabled() {
21846        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21847                PFLAG3_NESTED_SCROLLING_ENABLED;
21848    }
21849
21850    /**
21851     * Begin a nestable scroll operation along the given axes.
21852     *
21853     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21854     *
21855     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21856     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21857     * In the case of touch scrolling the nested scroll will be terminated automatically in
21858     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21859     * In the event of programmatic scrolling the caller must explicitly call
21860     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21861     *
21862     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21863     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21864     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21865     *
21866     * <p>At each incremental step of the scroll the caller should invoke
21867     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21868     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21869     * parent at least partially consumed the scroll and the caller should adjust the amount it
21870     * scrolls by.</p>
21871     *
21872     * <p>After applying the remainder of the scroll delta the caller should invoke
21873     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21874     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21875     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21876     * </p>
21877     *
21878     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21879     *             {@link #SCROLL_AXIS_VERTICAL}.
21880     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21881     *         the current gesture.
21882     *
21883     * @see #stopNestedScroll()
21884     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21885     * @see #dispatchNestedScroll(int, int, int, int, int[])
21886     */
21887    public boolean startNestedScroll(int axes) {
21888        if (hasNestedScrollingParent()) {
21889            // Already in progress
21890            return true;
21891        }
21892        if (isNestedScrollingEnabled()) {
21893            ViewParent p = getParent();
21894            View child = this;
21895            while (p != null) {
21896                try {
21897                    if (p.onStartNestedScroll(child, this, axes)) {
21898                        mNestedScrollingParent = p;
21899                        p.onNestedScrollAccepted(child, this, axes);
21900                        return true;
21901                    }
21902                } catch (AbstractMethodError e) {
21903                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21904                            "method onStartNestedScroll", e);
21905                    // Allow the search upward to continue
21906                }
21907                if (p instanceof View) {
21908                    child = (View) p;
21909                }
21910                p = p.getParent();
21911            }
21912        }
21913        return false;
21914    }
21915
21916    /**
21917     * Stop a nested scroll in progress.
21918     *
21919     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21920     *
21921     * @see #startNestedScroll(int)
21922     */
21923    public void stopNestedScroll() {
21924        if (mNestedScrollingParent != null) {
21925            mNestedScrollingParent.onStopNestedScroll(this);
21926            mNestedScrollingParent = null;
21927        }
21928    }
21929
21930    /**
21931     * Returns true if this view has a nested scrolling parent.
21932     *
21933     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21934     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21935     *
21936     * @return whether this view has a nested scrolling parent
21937     */
21938    public boolean hasNestedScrollingParent() {
21939        return mNestedScrollingParent != null;
21940    }
21941
21942    /**
21943     * Dispatch one step of a nested scroll in progress.
21944     *
21945     * <p>Implementations of views that support nested scrolling should call this to report
21946     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21947     * is not currently in progress or nested scrolling is not
21948     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21949     *
21950     * <p>Compatible View implementations should also call
21951     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21952     * consuming a component of the scroll event themselves.</p>
21953     *
21954     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21955     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21956     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21957     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21958     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21959     *                       in local view coordinates of this view from before this operation
21960     *                       to after it completes. View implementations may use this to adjust
21961     *                       expected input coordinate tracking.
21962     * @return true if the event was dispatched, false if it could not be dispatched.
21963     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21964     */
21965    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21966            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21967        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21968            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21969                int startX = 0;
21970                int startY = 0;
21971                if (offsetInWindow != null) {
21972                    getLocationInWindow(offsetInWindow);
21973                    startX = offsetInWindow[0];
21974                    startY = offsetInWindow[1];
21975                }
21976
21977                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21978                        dxUnconsumed, dyUnconsumed);
21979
21980                if (offsetInWindow != null) {
21981                    getLocationInWindow(offsetInWindow);
21982                    offsetInWindow[0] -= startX;
21983                    offsetInWindow[1] -= startY;
21984                }
21985                return true;
21986            } else if (offsetInWindow != null) {
21987                // No motion, no dispatch. Keep offsetInWindow up to date.
21988                offsetInWindow[0] = 0;
21989                offsetInWindow[1] = 0;
21990            }
21991        }
21992        return false;
21993    }
21994
21995    /**
21996     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21997     *
21998     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21999     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
22000     * scrolling operation to consume some or all of the scroll operation before the child view
22001     * consumes it.</p>
22002     *
22003     * @param dx Horizontal scroll distance in pixels
22004     * @param dy Vertical scroll distance in pixels
22005     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
22006     *                 and consumed[1] the consumed dy.
22007     * @param offsetInWindow Optional. If not null, on return this will contain the offset
22008     *                       in local view coordinates of this view from before this operation
22009     *                       to after it completes. View implementations may use this to adjust
22010     *                       expected input coordinate tracking.
22011     * @return true if the parent consumed some or all of the scroll delta
22012     * @see #dispatchNestedScroll(int, int, int, int, int[])
22013     */
22014    public boolean dispatchNestedPreScroll(int dx, int dy,
22015            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
22016        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22017            if (dx != 0 || dy != 0) {
22018                int startX = 0;
22019                int startY = 0;
22020                if (offsetInWindow != null) {
22021                    getLocationInWindow(offsetInWindow);
22022                    startX = offsetInWindow[0];
22023                    startY = offsetInWindow[1];
22024                }
22025
22026                if (consumed == null) {
22027                    if (mTempNestedScrollConsumed == null) {
22028                        mTempNestedScrollConsumed = new int[2];
22029                    }
22030                    consumed = mTempNestedScrollConsumed;
22031                }
22032                consumed[0] = 0;
22033                consumed[1] = 0;
22034                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
22035
22036                if (offsetInWindow != null) {
22037                    getLocationInWindow(offsetInWindow);
22038                    offsetInWindow[0] -= startX;
22039                    offsetInWindow[1] -= startY;
22040                }
22041                return consumed[0] != 0 || consumed[1] != 0;
22042            } else if (offsetInWindow != null) {
22043                offsetInWindow[0] = 0;
22044                offsetInWindow[1] = 0;
22045            }
22046        }
22047        return false;
22048    }
22049
22050    /**
22051     * Dispatch a fling to a nested scrolling parent.
22052     *
22053     * <p>This method should be used to indicate that a nested scrolling child has detected
22054     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
22055     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
22056     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
22057     * along a scrollable axis.</p>
22058     *
22059     * <p>If a nested scrolling child view would normally fling but it is at the edge of
22060     * its own content, it can use this method to delegate the fling to its nested scrolling
22061     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
22062     *
22063     * @param velocityX Horizontal fling velocity in pixels per second
22064     * @param velocityY Vertical fling velocity in pixels per second
22065     * @param consumed true if the child consumed the fling, false otherwise
22066     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
22067     */
22068    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
22069        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22070            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
22071        }
22072        return false;
22073    }
22074
22075    /**
22076     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
22077     *
22078     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
22079     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
22080     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
22081     * before the child view consumes it. If this method returns <code>true</code>, a nested
22082     * parent view consumed the fling and this view should not scroll as a result.</p>
22083     *
22084     * <p>For a better user experience, only one view in a nested scrolling chain should consume
22085     * the fling at a time. If a parent view consumed the fling this method will return false.
22086     * Custom view implementations should account for this in two ways:</p>
22087     *
22088     * <ul>
22089     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
22090     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
22091     *     position regardless.</li>
22092     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
22093     *     even to settle back to a valid idle position.</li>
22094     * </ul>
22095     *
22096     * <p>Views should also not offer fling velocities to nested parent views along an axis
22097     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
22098     * should not offer a horizontal fling velocity to its parents since scrolling along that
22099     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
22100     *
22101     * @param velocityX Horizontal fling velocity in pixels per second
22102     * @param velocityY Vertical fling velocity in pixels per second
22103     * @return true if a nested scrolling parent consumed the fling
22104     */
22105    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
22106        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22107            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
22108        }
22109        return false;
22110    }
22111
22112    /**
22113     * Gets a scale factor that determines the distance the view should scroll
22114     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
22115     * @return The vertical scroll scale factor.
22116     * @hide
22117     */
22118    protected float getVerticalScrollFactor() {
22119        if (mVerticalScrollFactor == 0) {
22120            TypedValue outValue = new TypedValue();
22121            if (!mContext.getTheme().resolveAttribute(
22122                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
22123                throw new IllegalStateException(
22124                        "Expected theme to define listPreferredItemHeight.");
22125            }
22126            mVerticalScrollFactor = outValue.getDimension(
22127                    mContext.getResources().getDisplayMetrics());
22128        }
22129        return mVerticalScrollFactor;
22130    }
22131
22132    /**
22133     * Gets a scale factor that determines the distance the view should scroll
22134     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
22135     * @return The horizontal scroll scale factor.
22136     * @hide
22137     */
22138    protected float getHorizontalScrollFactor() {
22139        // TODO: Should use something else.
22140        return getVerticalScrollFactor();
22141    }
22142
22143    /**
22144     * Return the value specifying the text direction or policy that was set with
22145     * {@link #setTextDirection(int)}.
22146     *
22147     * @return the defined text direction. It can be one of:
22148     *
22149     * {@link #TEXT_DIRECTION_INHERIT},
22150     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22151     * {@link #TEXT_DIRECTION_ANY_RTL},
22152     * {@link #TEXT_DIRECTION_LTR},
22153     * {@link #TEXT_DIRECTION_RTL},
22154     * {@link #TEXT_DIRECTION_LOCALE},
22155     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22156     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22157     *
22158     * @attr ref android.R.styleable#View_textDirection
22159     *
22160     * @hide
22161     */
22162    @ViewDebug.ExportedProperty(category = "text", mapping = {
22163            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22164            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22165            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22166            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22167            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22168            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22169            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22170            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22171    })
22172    public int getRawTextDirection() {
22173        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
22174    }
22175
22176    /**
22177     * Set the text direction.
22178     *
22179     * @param textDirection the direction to set. Should be one of:
22180     *
22181     * {@link #TEXT_DIRECTION_INHERIT},
22182     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22183     * {@link #TEXT_DIRECTION_ANY_RTL},
22184     * {@link #TEXT_DIRECTION_LTR},
22185     * {@link #TEXT_DIRECTION_RTL},
22186     * {@link #TEXT_DIRECTION_LOCALE}
22187     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22188     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
22189     *
22190     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
22191     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
22192     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
22193     *
22194     * @attr ref android.R.styleable#View_textDirection
22195     */
22196    public void setTextDirection(int textDirection) {
22197        if (getRawTextDirection() != textDirection) {
22198            // Reset the current text direction and the resolved one
22199            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
22200            resetResolvedTextDirection();
22201            // Set the new text direction
22202            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
22203            // Do resolution
22204            resolveTextDirection();
22205            // Notify change
22206            onRtlPropertiesChanged(getLayoutDirection());
22207            // Refresh
22208            requestLayout();
22209            invalidate(true);
22210        }
22211    }
22212
22213    /**
22214     * Return the resolved text direction.
22215     *
22216     * @return the resolved text direction. Returns one of:
22217     *
22218     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22219     * {@link #TEXT_DIRECTION_ANY_RTL},
22220     * {@link #TEXT_DIRECTION_LTR},
22221     * {@link #TEXT_DIRECTION_RTL},
22222     * {@link #TEXT_DIRECTION_LOCALE},
22223     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22224     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22225     *
22226     * @attr ref android.R.styleable#View_textDirection
22227     */
22228    @ViewDebug.ExportedProperty(category = "text", mapping = {
22229            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22230            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22231            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22232            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22233            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22234            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22235            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22236            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22237    })
22238    public int getTextDirection() {
22239        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
22240    }
22241
22242    /**
22243     * Resolve the text direction.
22244     *
22245     * @return true if resolution has been done, false otherwise.
22246     *
22247     * @hide
22248     */
22249    public boolean resolveTextDirection() {
22250        // Reset any previous text direction resolution
22251        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22252
22253        if (hasRtlSupport()) {
22254            // Set resolved text direction flag depending on text direction flag
22255            final int textDirection = getRawTextDirection();
22256            switch(textDirection) {
22257                case TEXT_DIRECTION_INHERIT:
22258                    if (!canResolveTextDirection()) {
22259                        // We cannot do the resolution if there is no parent, so use the default one
22260                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22261                        // Resolution will need to happen again later
22262                        return false;
22263                    }
22264
22265                    // Parent has not yet resolved, so we still return the default
22266                    try {
22267                        if (!mParent.isTextDirectionResolved()) {
22268                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22269                            // Resolution will need to happen again later
22270                            return false;
22271                        }
22272                    } catch (AbstractMethodError e) {
22273                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22274                                " does not fully implement ViewParent", e);
22275                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
22276                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22277                        return true;
22278                    }
22279
22280                    // Set current resolved direction to the same value as the parent's one
22281                    int parentResolvedDirection;
22282                    try {
22283                        parentResolvedDirection = mParent.getTextDirection();
22284                    } catch (AbstractMethodError e) {
22285                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22286                                " does not fully implement ViewParent", e);
22287                        parentResolvedDirection = TEXT_DIRECTION_LTR;
22288                    }
22289                    switch (parentResolvedDirection) {
22290                        case TEXT_DIRECTION_FIRST_STRONG:
22291                        case TEXT_DIRECTION_ANY_RTL:
22292                        case TEXT_DIRECTION_LTR:
22293                        case TEXT_DIRECTION_RTL:
22294                        case TEXT_DIRECTION_LOCALE:
22295                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
22296                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
22297                            mPrivateFlags2 |=
22298                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22299                            break;
22300                        default:
22301                            // Default resolved direction is "first strong" heuristic
22302                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22303                    }
22304                    break;
22305                case TEXT_DIRECTION_FIRST_STRONG:
22306                case TEXT_DIRECTION_ANY_RTL:
22307                case TEXT_DIRECTION_LTR:
22308                case TEXT_DIRECTION_RTL:
22309                case TEXT_DIRECTION_LOCALE:
22310                case TEXT_DIRECTION_FIRST_STRONG_LTR:
22311                case TEXT_DIRECTION_FIRST_STRONG_RTL:
22312                    // Resolved direction is the same as text direction
22313                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22314                    break;
22315                default:
22316                    // Default resolved direction is "first strong" heuristic
22317                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22318            }
22319        } else {
22320            // Default resolved direction is "first strong" heuristic
22321            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22322        }
22323
22324        // Set to resolved
22325        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
22326        return true;
22327    }
22328
22329    /**
22330     * Check if text direction resolution can be done.
22331     *
22332     * @return true if text direction resolution can be done otherwise return false.
22333     */
22334    public boolean canResolveTextDirection() {
22335        switch (getRawTextDirection()) {
22336            case TEXT_DIRECTION_INHERIT:
22337                if (mParent != null) {
22338                    try {
22339                        return mParent.canResolveTextDirection();
22340                    } catch (AbstractMethodError e) {
22341                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22342                                " does not fully implement ViewParent", e);
22343                    }
22344                }
22345                return false;
22346
22347            default:
22348                return true;
22349        }
22350    }
22351
22352    /**
22353     * Reset resolved text direction. Text direction will be resolved during a call to
22354     * {@link #onMeasure(int, int)}.
22355     *
22356     * @hide
22357     */
22358    public void resetResolvedTextDirection() {
22359        // Reset any previous text direction resolution
22360        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22361        // Set to default value
22362        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22363    }
22364
22365    /**
22366     * @return true if text direction is inherited.
22367     *
22368     * @hide
22369     */
22370    public boolean isTextDirectionInherited() {
22371        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
22372    }
22373
22374    /**
22375     * @return true if text direction is resolved.
22376     */
22377    public boolean isTextDirectionResolved() {
22378        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
22379    }
22380
22381    /**
22382     * Return the value specifying the text alignment or policy that was set with
22383     * {@link #setTextAlignment(int)}.
22384     *
22385     * @return the defined text alignment. It can be one of:
22386     *
22387     * {@link #TEXT_ALIGNMENT_INHERIT},
22388     * {@link #TEXT_ALIGNMENT_GRAVITY},
22389     * {@link #TEXT_ALIGNMENT_CENTER},
22390     * {@link #TEXT_ALIGNMENT_TEXT_START},
22391     * {@link #TEXT_ALIGNMENT_TEXT_END},
22392     * {@link #TEXT_ALIGNMENT_VIEW_START},
22393     * {@link #TEXT_ALIGNMENT_VIEW_END}
22394     *
22395     * @attr ref android.R.styleable#View_textAlignment
22396     *
22397     * @hide
22398     */
22399    @ViewDebug.ExportedProperty(category = "text", mapping = {
22400            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22401            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22402            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22403            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22404            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22405            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22406            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22407    })
22408    @TextAlignment
22409    public int getRawTextAlignment() {
22410        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
22411    }
22412
22413    /**
22414     * Set the text alignment.
22415     *
22416     * @param textAlignment The text alignment to set. Should be one of
22417     *
22418     * {@link #TEXT_ALIGNMENT_INHERIT},
22419     * {@link #TEXT_ALIGNMENT_GRAVITY},
22420     * {@link #TEXT_ALIGNMENT_CENTER},
22421     * {@link #TEXT_ALIGNMENT_TEXT_START},
22422     * {@link #TEXT_ALIGNMENT_TEXT_END},
22423     * {@link #TEXT_ALIGNMENT_VIEW_START},
22424     * {@link #TEXT_ALIGNMENT_VIEW_END}
22425     *
22426     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
22427     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
22428     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
22429     *
22430     * @attr ref android.R.styleable#View_textAlignment
22431     */
22432    public void setTextAlignment(@TextAlignment int textAlignment) {
22433        if (textAlignment != getRawTextAlignment()) {
22434            // Reset the current and resolved text alignment
22435            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
22436            resetResolvedTextAlignment();
22437            // Set the new text alignment
22438            mPrivateFlags2 |=
22439                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
22440            // Do resolution
22441            resolveTextAlignment();
22442            // Notify change
22443            onRtlPropertiesChanged(getLayoutDirection());
22444            // Refresh
22445            requestLayout();
22446            invalidate(true);
22447        }
22448    }
22449
22450    /**
22451     * Return the resolved text alignment.
22452     *
22453     * @return the resolved text alignment. Returns one of:
22454     *
22455     * {@link #TEXT_ALIGNMENT_GRAVITY},
22456     * {@link #TEXT_ALIGNMENT_CENTER},
22457     * {@link #TEXT_ALIGNMENT_TEXT_START},
22458     * {@link #TEXT_ALIGNMENT_TEXT_END},
22459     * {@link #TEXT_ALIGNMENT_VIEW_START},
22460     * {@link #TEXT_ALIGNMENT_VIEW_END}
22461     *
22462     * @attr ref android.R.styleable#View_textAlignment
22463     */
22464    @ViewDebug.ExportedProperty(category = "text", mapping = {
22465            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22466            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22467            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22468            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22469            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22470            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22471            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22472    })
22473    @TextAlignment
22474    public int getTextAlignment() {
22475        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
22476                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
22477    }
22478
22479    /**
22480     * Resolve the text alignment.
22481     *
22482     * @return true if resolution has been done, false otherwise.
22483     *
22484     * @hide
22485     */
22486    public boolean resolveTextAlignment() {
22487        // Reset any previous text alignment resolution
22488        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22489
22490        if (hasRtlSupport()) {
22491            // Set resolved text alignment flag depending on text alignment flag
22492            final int textAlignment = getRawTextAlignment();
22493            switch (textAlignment) {
22494                case TEXT_ALIGNMENT_INHERIT:
22495                    // Check if we can resolve the text alignment
22496                    if (!canResolveTextAlignment()) {
22497                        // We cannot do the resolution if there is no parent so use the default
22498                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22499                        // Resolution will need to happen again later
22500                        return false;
22501                    }
22502
22503                    // Parent has not yet resolved, so we still return the default
22504                    try {
22505                        if (!mParent.isTextAlignmentResolved()) {
22506                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22507                            // Resolution will need to happen again later
22508                            return false;
22509                        }
22510                    } catch (AbstractMethodError e) {
22511                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22512                                " does not fully implement ViewParent", e);
22513                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
22514                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22515                        return true;
22516                    }
22517
22518                    int parentResolvedTextAlignment;
22519                    try {
22520                        parentResolvedTextAlignment = mParent.getTextAlignment();
22521                    } catch (AbstractMethodError e) {
22522                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22523                                " does not fully implement ViewParent", e);
22524                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
22525                    }
22526                    switch (parentResolvedTextAlignment) {
22527                        case TEXT_ALIGNMENT_GRAVITY:
22528                        case TEXT_ALIGNMENT_TEXT_START:
22529                        case TEXT_ALIGNMENT_TEXT_END:
22530                        case TEXT_ALIGNMENT_CENTER:
22531                        case TEXT_ALIGNMENT_VIEW_START:
22532                        case TEXT_ALIGNMENT_VIEW_END:
22533                            // Resolved text alignment is the same as the parent resolved
22534                            // text alignment
22535                            mPrivateFlags2 |=
22536                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22537                            break;
22538                        default:
22539                            // Use default resolved text alignment
22540                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22541                    }
22542                    break;
22543                case TEXT_ALIGNMENT_GRAVITY:
22544                case TEXT_ALIGNMENT_TEXT_START:
22545                case TEXT_ALIGNMENT_TEXT_END:
22546                case TEXT_ALIGNMENT_CENTER:
22547                case TEXT_ALIGNMENT_VIEW_START:
22548                case TEXT_ALIGNMENT_VIEW_END:
22549                    // Resolved text alignment is the same as text alignment
22550                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22551                    break;
22552                default:
22553                    // Use default resolved text alignment
22554                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22555            }
22556        } else {
22557            // Use default resolved text alignment
22558            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22559        }
22560
22561        // Set the resolved
22562        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22563        return true;
22564    }
22565
22566    /**
22567     * Check if text alignment resolution can be done.
22568     *
22569     * @return true if text alignment resolution can be done otherwise return false.
22570     */
22571    public boolean canResolveTextAlignment() {
22572        switch (getRawTextAlignment()) {
22573            case TEXT_DIRECTION_INHERIT:
22574                if (mParent != null) {
22575                    try {
22576                        return mParent.canResolveTextAlignment();
22577                    } catch (AbstractMethodError e) {
22578                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22579                                " does not fully implement ViewParent", e);
22580                    }
22581                }
22582                return false;
22583
22584            default:
22585                return true;
22586        }
22587    }
22588
22589    /**
22590     * Reset resolved text alignment. Text alignment will be resolved during a call to
22591     * {@link #onMeasure(int, int)}.
22592     *
22593     * @hide
22594     */
22595    public void resetResolvedTextAlignment() {
22596        // Reset any previous text alignment resolution
22597        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22598        // Set to default
22599        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22600    }
22601
22602    /**
22603     * @return true if text alignment is inherited.
22604     *
22605     * @hide
22606     */
22607    public boolean isTextAlignmentInherited() {
22608        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
22609    }
22610
22611    /**
22612     * @return true if text alignment is resolved.
22613     */
22614    public boolean isTextAlignmentResolved() {
22615        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22616    }
22617
22618    /**
22619     * Generate a value suitable for use in {@link #setId(int)}.
22620     * This value will not collide with ID values generated at build time by aapt for R.id.
22621     *
22622     * @return a generated ID value
22623     */
22624    public static int generateViewId() {
22625        for (;;) {
22626            final int result = sNextGeneratedId.get();
22627            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
22628            int newValue = result + 1;
22629            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
22630            if (sNextGeneratedId.compareAndSet(result, newValue)) {
22631                return result;
22632            }
22633        }
22634    }
22635
22636    private static boolean isViewIdGenerated(int id) {
22637        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
22638    }
22639
22640    /**
22641     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
22642     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
22643     *                           a normal View or a ViewGroup with
22644     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
22645     * @hide
22646     */
22647    public void captureTransitioningViews(List<View> transitioningViews) {
22648        if (getVisibility() == View.VISIBLE) {
22649            transitioningViews.add(this);
22650        }
22651    }
22652
22653    /**
22654     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
22655     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
22656     * @hide
22657     */
22658    public void findNamedViews(Map<String, View> namedElements) {
22659        if (getVisibility() == VISIBLE || mGhostView != null) {
22660            String transitionName = getTransitionName();
22661            if (transitionName != null) {
22662                namedElements.put(transitionName, this);
22663            }
22664        }
22665    }
22666
22667    /**
22668     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
22669     * The default implementation does not care the location or event types, but some subclasses
22670     * may use it (such as WebViews).
22671     * @param event The MotionEvent from a mouse
22672     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
22673     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
22674     * @see PointerIcon
22675     */
22676    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
22677        final float x = event.getX(pointerIndex);
22678        final float y = event.getY(pointerIndex);
22679        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
22680            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
22681        }
22682        return mPointerIcon;
22683    }
22684
22685    /**
22686     * Set the pointer icon for the current view.
22687     * Passing {@code null} will restore the pointer icon to its default value.
22688     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
22689     */
22690    public void setPointerIcon(PointerIcon pointerIcon) {
22691        mPointerIcon = pointerIcon;
22692        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
22693            return;
22694        }
22695        try {
22696            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
22697        } catch (RemoteException e) {
22698        }
22699    }
22700
22701    /**
22702     * Gets the pointer icon for the current view.
22703     */
22704    public PointerIcon getPointerIcon() {
22705        return mPointerIcon;
22706    }
22707
22708    /**
22709     * Checks pointer capture status.
22710     *
22711     * @return true if the view has pointer capture.
22712     * @see #requestPointerCapture()
22713     * @see #hasPointerCapture()
22714     */
22715    public boolean hasPointerCapture() {
22716        final ViewRootImpl viewRootImpl = getViewRootImpl();
22717        if (viewRootImpl == null) {
22718            return false;
22719        }
22720        return viewRootImpl.hasPointerCapture();
22721    }
22722
22723    /**
22724     * Requests pointer capture mode.
22725     * <p>
22726     * When the window has pointer capture, the mouse pointer icon will disappear and will not
22727     * change its position. Further mouse will be dispatched with the source
22728     * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available
22729     * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events
22730     * (touchscreens, or stylus) will not be affected.
22731     * <p>
22732     * If the window already has pointer capture, this call does nothing.
22733     * <p>
22734     * The capture may be released through {@link #releasePointerCapture()}, or will be lost
22735     * automatically when the window loses focus.
22736     *
22737     * @see #releasePointerCapture()
22738     * @see #hasPointerCapture()
22739     */
22740    public void requestPointerCapture() {
22741        final ViewRootImpl viewRootImpl = getViewRootImpl();
22742        if (viewRootImpl != null) {
22743            viewRootImpl.requestPointerCapture(true);
22744        }
22745    }
22746
22747
22748    /**
22749     * Releases the pointer capture.
22750     * <p>
22751     * If the window does not have pointer capture, this call will do nothing.
22752     * @see #requestPointerCapture()
22753     * @see #hasPointerCapture()
22754     */
22755    public void releasePointerCapture() {
22756        final ViewRootImpl viewRootImpl = getViewRootImpl();
22757        if (viewRootImpl != null) {
22758            viewRootImpl.requestPointerCapture(false);
22759        }
22760    }
22761
22762    /**
22763     * Called when the window has just acquired or lost pointer capture.
22764     *
22765     * @param hasCapture True if the view now has pointerCapture, false otherwise.
22766     */
22767    @CallSuper
22768    public void onPointerCaptureChange(boolean hasCapture) {
22769    }
22770
22771    /**
22772     * @see #onPointerCaptureChange
22773     */
22774    public void dispatchPointerCaptureChanged(boolean hasCapture) {
22775        onPointerCaptureChange(hasCapture);
22776    }
22777
22778    /**
22779     * Implement this method to handle captured pointer events
22780     *
22781     * @param event The captured pointer event.
22782     * @return True if the event was handled, false otherwise.
22783     * @see #requestPointerCapture()
22784     */
22785    public boolean onCapturedPointerEvent(MotionEvent event) {
22786        return false;
22787    }
22788
22789    /**
22790     * Interface definition for a callback to be invoked when a captured pointer event
22791     * is being dispatched this view. The callback will be invoked before the event is
22792     * given to the view.
22793     */
22794    public interface OnCapturedPointerListener {
22795        /**
22796         * Called when a captured pointer event is dispatched to a view.
22797         * @param view The view this event has been dispatched to.
22798         * @param event The captured event.
22799         * @return True if the listener has consumed the event, false otherwise.
22800         */
22801        boolean onCapturedPointer(View view, MotionEvent event);
22802    }
22803
22804    /**
22805     * Set a listener to receive callbacks when the pointer capture state of a view changes.
22806     * @param l  The {@link OnCapturedPointerListener} to receive callbacks.
22807     */
22808    public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
22809        getListenerInfo().mOnCapturedPointerListener = l;
22810    }
22811
22812    // Properties
22813    //
22814    /**
22815     * A Property wrapper around the <code>alpha</code> functionality handled by the
22816     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
22817     */
22818    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
22819        @Override
22820        public void setValue(View object, float value) {
22821            object.setAlpha(value);
22822        }
22823
22824        @Override
22825        public Float get(View object) {
22826            return object.getAlpha();
22827        }
22828    };
22829
22830    /**
22831     * A Property wrapper around the <code>translationX</code> functionality handled by the
22832     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
22833     */
22834    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
22835        @Override
22836        public void setValue(View object, float value) {
22837            object.setTranslationX(value);
22838        }
22839
22840                @Override
22841        public Float get(View object) {
22842            return object.getTranslationX();
22843        }
22844    };
22845
22846    /**
22847     * A Property wrapper around the <code>translationY</code> functionality handled by the
22848     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
22849     */
22850    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
22851        @Override
22852        public void setValue(View object, float value) {
22853            object.setTranslationY(value);
22854        }
22855
22856        @Override
22857        public Float get(View object) {
22858            return object.getTranslationY();
22859        }
22860    };
22861
22862    /**
22863     * A Property wrapper around the <code>translationZ</code> functionality handled by the
22864     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
22865     */
22866    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
22867        @Override
22868        public void setValue(View object, float value) {
22869            object.setTranslationZ(value);
22870        }
22871
22872        @Override
22873        public Float get(View object) {
22874            return object.getTranslationZ();
22875        }
22876    };
22877
22878    /**
22879     * A Property wrapper around the <code>x</code> functionality handled by the
22880     * {@link View#setX(float)} and {@link View#getX()} methods.
22881     */
22882    public static final Property<View, Float> X = new FloatProperty<View>("x") {
22883        @Override
22884        public void setValue(View object, float value) {
22885            object.setX(value);
22886        }
22887
22888        @Override
22889        public Float get(View object) {
22890            return object.getX();
22891        }
22892    };
22893
22894    /**
22895     * A Property wrapper around the <code>y</code> functionality handled by the
22896     * {@link View#setY(float)} and {@link View#getY()} methods.
22897     */
22898    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
22899        @Override
22900        public void setValue(View object, float value) {
22901            object.setY(value);
22902        }
22903
22904        @Override
22905        public Float get(View object) {
22906            return object.getY();
22907        }
22908    };
22909
22910    /**
22911     * A Property wrapper around the <code>z</code> functionality handled by the
22912     * {@link View#setZ(float)} and {@link View#getZ()} methods.
22913     */
22914    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
22915        @Override
22916        public void setValue(View object, float value) {
22917            object.setZ(value);
22918        }
22919
22920        @Override
22921        public Float get(View object) {
22922            return object.getZ();
22923        }
22924    };
22925
22926    /**
22927     * A Property wrapper around the <code>rotation</code> functionality handled by the
22928     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
22929     */
22930    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
22931        @Override
22932        public void setValue(View object, float value) {
22933            object.setRotation(value);
22934        }
22935
22936        @Override
22937        public Float get(View object) {
22938            return object.getRotation();
22939        }
22940    };
22941
22942    /**
22943     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22944     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22945     */
22946    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22947        @Override
22948        public void setValue(View object, float value) {
22949            object.setRotationX(value);
22950        }
22951
22952        @Override
22953        public Float get(View object) {
22954            return object.getRotationX();
22955        }
22956    };
22957
22958    /**
22959     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22960     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22961     */
22962    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22963        @Override
22964        public void setValue(View object, float value) {
22965            object.setRotationY(value);
22966        }
22967
22968        @Override
22969        public Float get(View object) {
22970            return object.getRotationY();
22971        }
22972    };
22973
22974    /**
22975     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22976     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22977     */
22978    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22979        @Override
22980        public void setValue(View object, float value) {
22981            object.setScaleX(value);
22982        }
22983
22984        @Override
22985        public Float get(View object) {
22986            return object.getScaleX();
22987        }
22988    };
22989
22990    /**
22991     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22992     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22993     */
22994    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22995        @Override
22996        public void setValue(View object, float value) {
22997            object.setScaleY(value);
22998        }
22999
23000        @Override
23001        public Float get(View object) {
23002            return object.getScaleY();
23003        }
23004    };
23005
23006    /**
23007     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
23008     * Each MeasureSpec represents a requirement for either the width or the height.
23009     * A MeasureSpec is comprised of a size and a mode. There are three possible
23010     * modes:
23011     * <dl>
23012     * <dt>UNSPECIFIED</dt>
23013     * <dd>
23014     * The parent has not imposed any constraint on the child. It can be whatever size
23015     * it wants.
23016     * </dd>
23017     *
23018     * <dt>EXACTLY</dt>
23019     * <dd>
23020     * The parent has determined an exact size for the child. The child is going to be
23021     * given those bounds regardless of how big it wants to be.
23022     * </dd>
23023     *
23024     * <dt>AT_MOST</dt>
23025     * <dd>
23026     * The child can be as large as it wants up to the specified size.
23027     * </dd>
23028     * </dl>
23029     *
23030     * MeasureSpecs are implemented as ints to reduce object allocation. This class
23031     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
23032     */
23033    public static class MeasureSpec {
23034        private static final int MODE_SHIFT = 30;
23035        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
23036
23037        /** @hide */
23038        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
23039        @Retention(RetentionPolicy.SOURCE)
23040        public @interface MeasureSpecMode {}
23041
23042        /**
23043         * Measure specification mode: The parent has not imposed any constraint
23044         * on the child. It can be whatever size it wants.
23045         */
23046        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
23047
23048        /**
23049         * Measure specification mode: The parent has determined an exact size
23050         * for the child. The child is going to be given those bounds regardless
23051         * of how big it wants to be.
23052         */
23053        public static final int EXACTLY     = 1 << MODE_SHIFT;
23054
23055        /**
23056         * Measure specification mode: The child can be as large as it wants up
23057         * to the specified size.
23058         */
23059        public static final int AT_MOST     = 2 << MODE_SHIFT;
23060
23061        /**
23062         * Creates a measure specification based on the supplied size and mode.
23063         *
23064         * The mode must always be one of the following:
23065         * <ul>
23066         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
23067         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
23068         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
23069         * </ul>
23070         *
23071         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
23072         * implementation was such that the order of arguments did not matter
23073         * and overflow in either value could impact the resulting MeasureSpec.
23074         * {@link android.widget.RelativeLayout} was affected by this bug.
23075         * Apps targeting API levels greater than 17 will get the fixed, more strict
23076         * behavior.</p>
23077         *
23078         * @param size the size of the measure specification
23079         * @param mode the mode of the measure specification
23080         * @return the measure specification based on size and mode
23081         */
23082        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
23083                                          @MeasureSpecMode int mode) {
23084            if (sUseBrokenMakeMeasureSpec) {
23085                return size + mode;
23086            } else {
23087                return (size & ~MODE_MASK) | (mode & MODE_MASK);
23088            }
23089        }
23090
23091        /**
23092         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
23093         * will automatically get a size of 0. Older apps expect this.
23094         *
23095         * @hide internal use only for compatibility with system widgets and older apps
23096         */
23097        public static int makeSafeMeasureSpec(int size, int mode) {
23098            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
23099                return 0;
23100            }
23101            return makeMeasureSpec(size, mode);
23102        }
23103
23104        /**
23105         * Extracts the mode from the supplied measure specification.
23106         *
23107         * @param measureSpec the measure specification to extract the mode from
23108         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
23109         *         {@link android.view.View.MeasureSpec#AT_MOST} or
23110         *         {@link android.view.View.MeasureSpec#EXACTLY}
23111         */
23112        @MeasureSpecMode
23113        public static int getMode(int measureSpec) {
23114            //noinspection ResourceType
23115            return (measureSpec & MODE_MASK);
23116        }
23117
23118        /**
23119         * Extracts the size from the supplied measure specification.
23120         *
23121         * @param measureSpec the measure specification to extract the size from
23122         * @return the size in pixels defined in the supplied measure specification
23123         */
23124        public static int getSize(int measureSpec) {
23125            return (measureSpec & ~MODE_MASK);
23126        }
23127
23128        static int adjust(int measureSpec, int delta) {
23129            final int mode = getMode(measureSpec);
23130            int size = getSize(measureSpec);
23131            if (mode == UNSPECIFIED) {
23132                // No need to adjust size for UNSPECIFIED mode.
23133                return makeMeasureSpec(size, UNSPECIFIED);
23134            }
23135            size += delta;
23136            if (size < 0) {
23137                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
23138                        ") spec: " + toString(measureSpec) + " delta: " + delta);
23139                size = 0;
23140            }
23141            return makeMeasureSpec(size, mode);
23142        }
23143
23144        /**
23145         * Returns a String representation of the specified measure
23146         * specification.
23147         *
23148         * @param measureSpec the measure specification to convert to a String
23149         * @return a String with the following format: "MeasureSpec: MODE SIZE"
23150         */
23151        public static String toString(int measureSpec) {
23152            int mode = getMode(measureSpec);
23153            int size = getSize(measureSpec);
23154
23155            StringBuilder sb = new StringBuilder("MeasureSpec: ");
23156
23157            if (mode == UNSPECIFIED)
23158                sb.append("UNSPECIFIED ");
23159            else if (mode == EXACTLY)
23160                sb.append("EXACTLY ");
23161            else if (mode == AT_MOST)
23162                sb.append("AT_MOST ");
23163            else
23164                sb.append(mode).append(" ");
23165
23166            sb.append(size);
23167            return sb.toString();
23168        }
23169    }
23170
23171    private final class CheckForLongPress implements Runnable {
23172        private int mOriginalWindowAttachCount;
23173        private float mX;
23174        private float mY;
23175        private boolean mOriginalPressedState;
23176
23177        @Override
23178        public void run() {
23179            if ((mOriginalPressedState == isPressed()) && (mParent != null)
23180                    && mOriginalWindowAttachCount == mWindowAttachCount) {
23181                if (performLongClick(mX, mY)) {
23182                    mHasPerformedLongPress = true;
23183                }
23184            }
23185        }
23186
23187        public void setAnchor(float x, float y) {
23188            mX = x;
23189            mY = y;
23190        }
23191
23192        public void rememberWindowAttachCount() {
23193            mOriginalWindowAttachCount = mWindowAttachCount;
23194        }
23195
23196        public void rememberPressedState() {
23197            mOriginalPressedState = isPressed();
23198        }
23199    }
23200
23201    private final class CheckForTap implements Runnable {
23202        public float x;
23203        public float y;
23204
23205        @Override
23206        public void run() {
23207            mPrivateFlags &= ~PFLAG_PREPRESSED;
23208            setPressed(true, x, y);
23209            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
23210        }
23211    }
23212
23213    private final class PerformClick implements Runnable {
23214        @Override
23215        public void run() {
23216            performClick();
23217        }
23218    }
23219
23220    /**
23221     * This method returns a ViewPropertyAnimator object, which can be used to animate
23222     * specific properties on this View.
23223     *
23224     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
23225     */
23226    public ViewPropertyAnimator animate() {
23227        if (mAnimator == null) {
23228            mAnimator = new ViewPropertyAnimator(this);
23229        }
23230        return mAnimator;
23231    }
23232
23233    /**
23234     * Sets the name of the View to be used to identify Views in Transitions.
23235     * Names should be unique in the View hierarchy.
23236     *
23237     * @param transitionName The name of the View to uniquely identify it for Transitions.
23238     */
23239    public final void setTransitionName(String transitionName) {
23240        mTransitionName = transitionName;
23241    }
23242
23243    /**
23244     * Returns the name of the View to be used to identify Views in Transitions.
23245     * Names should be unique in the View hierarchy.
23246     *
23247     * <p>This returns null if the View has not been given a name.</p>
23248     *
23249     * @return The name used of the View to be used to identify Views in Transitions or null
23250     * if no name has been given.
23251     */
23252    @ViewDebug.ExportedProperty
23253    public String getTransitionName() {
23254        return mTransitionName;
23255    }
23256
23257    /**
23258     * @hide
23259     */
23260    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
23261        // Do nothing.
23262    }
23263
23264    /**
23265     * Interface definition for a callback to be invoked when a hardware key event is
23266     * dispatched to this view. The callback will be invoked before the key event is
23267     * given to the view. This is only useful for hardware keyboards; a software input
23268     * method has no obligation to trigger this listener.
23269     */
23270    public interface OnKeyListener {
23271        /**
23272         * Called when a hardware key is dispatched to a view. This allows listeners to
23273         * get a chance to respond before the target view.
23274         * <p>Key presses in software keyboards will generally NOT trigger this method,
23275         * although some may elect to do so in some situations. Do not assume a
23276         * software input method has to be key-based; even if it is, it may use key presses
23277         * in a different way than you expect, so there is no way to reliably catch soft
23278         * input key presses.
23279         *
23280         * @param v The view the key has been dispatched to.
23281         * @param keyCode The code for the physical key that was pressed
23282         * @param event The KeyEvent object containing full information about
23283         *        the event.
23284         * @return True if the listener has consumed the event, false otherwise.
23285         */
23286        boolean onKey(View v, int keyCode, KeyEvent event);
23287    }
23288
23289    /**
23290     * Interface definition for a callback to be invoked when a touch event is
23291     * dispatched to this view. The callback will be invoked before the touch
23292     * event is given to the view.
23293     */
23294    public interface OnTouchListener {
23295        /**
23296         * Called when a touch event is dispatched to a view. This allows listeners to
23297         * get a chance to respond before the target view.
23298         *
23299         * @param v The view the touch event has been dispatched to.
23300         * @param event The MotionEvent object containing full information about
23301         *        the event.
23302         * @return True if the listener has consumed the event, false otherwise.
23303         */
23304        boolean onTouch(View v, MotionEvent event);
23305    }
23306
23307    /**
23308     * Interface definition for a callback to be invoked when a hover event is
23309     * dispatched to this view. The callback will be invoked before the hover
23310     * event is given to the view.
23311     */
23312    public interface OnHoverListener {
23313        /**
23314         * Called when a hover event is dispatched to a view. This allows listeners to
23315         * get a chance to respond before the target view.
23316         *
23317         * @param v The view the hover event has been dispatched to.
23318         * @param event The MotionEvent object containing full information about
23319         *        the event.
23320         * @return True if the listener has consumed the event, false otherwise.
23321         */
23322        boolean onHover(View v, MotionEvent event);
23323    }
23324
23325    /**
23326     * Interface definition for a callback to be invoked when a generic motion event is
23327     * dispatched to this view. The callback will be invoked before the generic motion
23328     * event is given to the view.
23329     */
23330    public interface OnGenericMotionListener {
23331        /**
23332         * Called when a generic motion event is dispatched to a view. This allows listeners to
23333         * get a chance to respond before the target view.
23334         *
23335         * @param v The view the generic motion event has been dispatched to.
23336         * @param event The MotionEvent object containing full information about
23337         *        the event.
23338         * @return True if the listener has consumed the event, false otherwise.
23339         */
23340        boolean onGenericMotion(View v, MotionEvent event);
23341    }
23342
23343    /**
23344     * Interface definition for a callback to be invoked when a view has been clicked and held.
23345     */
23346    public interface OnLongClickListener {
23347        /**
23348         * Called when a view has been clicked and held.
23349         *
23350         * @param v The view that was clicked and held.
23351         *
23352         * @return true if the callback consumed the long click, false otherwise.
23353         */
23354        boolean onLongClick(View v);
23355    }
23356
23357    /**
23358     * Interface definition for a callback to be invoked when a drag is being dispatched
23359     * to this view.  The callback will be invoked before the hosting view's own
23360     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
23361     * onDrag(event) behavior, it should return 'false' from this callback.
23362     *
23363     * <div class="special reference">
23364     * <h3>Developer Guides</h3>
23365     * <p>For a guide to implementing drag and drop features, read the
23366     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
23367     * </div>
23368     */
23369    public interface OnDragListener {
23370        /**
23371         * Called when a drag event is dispatched to a view. This allows listeners
23372         * to get a chance to override base View behavior.
23373         *
23374         * @param v The View that received the drag event.
23375         * @param event The {@link android.view.DragEvent} object for the drag event.
23376         * @return {@code true} if the drag event was handled successfully, or {@code false}
23377         * if the drag event was not handled. Note that {@code false} will trigger the View
23378         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
23379         */
23380        boolean onDrag(View v, DragEvent event);
23381    }
23382
23383    /**
23384     * Interface definition for a callback to be invoked when the focus state of
23385     * a view changed.
23386     */
23387    public interface OnFocusChangeListener {
23388        /**
23389         * Called when the focus state of a view has changed.
23390         *
23391         * @param v The view whose state has changed.
23392         * @param hasFocus The new focus state of v.
23393         */
23394        void onFocusChange(View v, boolean hasFocus);
23395    }
23396
23397    /**
23398     * Interface definition for a callback to be invoked when a view is clicked.
23399     */
23400    public interface OnClickListener {
23401        /**
23402         * Called when a view has been clicked.
23403         *
23404         * @param v The view that was clicked.
23405         */
23406        void onClick(View v);
23407    }
23408
23409    /**
23410     * Interface definition for a callback to be invoked when a view is context clicked.
23411     */
23412    public interface OnContextClickListener {
23413        /**
23414         * Called when a view is context clicked.
23415         *
23416         * @param v The view that has been context clicked.
23417         * @return true if the callback consumed the context click, false otherwise.
23418         */
23419        boolean onContextClick(View v);
23420    }
23421
23422    /**
23423     * Interface definition for a callback to be invoked when the context menu
23424     * for this view is being built.
23425     */
23426    public interface OnCreateContextMenuListener {
23427        /**
23428         * Called when the context menu for this view is being built. It is not
23429         * safe to hold onto the menu after this method returns.
23430         *
23431         * @param menu The context menu that is being built
23432         * @param v The view for which the context menu is being built
23433         * @param menuInfo Extra information about the item for which the
23434         *            context menu should be shown. This information will vary
23435         *            depending on the class of v.
23436         */
23437        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
23438    }
23439
23440    /**
23441     * Interface definition for a callback to be invoked when the status bar changes
23442     * visibility.  This reports <strong>global</strong> changes to the system UI
23443     * state, not what the application is requesting.
23444     *
23445     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
23446     */
23447    public interface OnSystemUiVisibilityChangeListener {
23448        /**
23449         * Called when the status bar changes visibility because of a call to
23450         * {@link View#setSystemUiVisibility(int)}.
23451         *
23452         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23453         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
23454         * This tells you the <strong>global</strong> state of these UI visibility
23455         * flags, not what your app is currently applying.
23456         */
23457        public void onSystemUiVisibilityChange(int visibility);
23458    }
23459
23460    /**
23461     * Interface definition for a callback to be invoked when this view is attached
23462     * or detached from its window.
23463     */
23464    public interface OnAttachStateChangeListener {
23465        /**
23466         * Called when the view is attached to a window.
23467         * @param v The view that was attached
23468         */
23469        public void onViewAttachedToWindow(View v);
23470        /**
23471         * Called when the view is detached from a window.
23472         * @param v The view that was detached
23473         */
23474        public void onViewDetachedFromWindow(View v);
23475    }
23476
23477    /**
23478     * Listener for applying window insets on a view in a custom way.
23479     *
23480     * <p>Apps may choose to implement this interface if they want to apply custom policy
23481     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
23482     * is set, its
23483     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
23484     * method will be called instead of the View's own
23485     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
23486     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
23487     * the View's normal behavior as part of its own.</p>
23488     */
23489    public interface OnApplyWindowInsetsListener {
23490        /**
23491         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
23492         * on a View, this listener method will be called instead of the view's own
23493         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
23494         *
23495         * @param v The view applying window insets
23496         * @param insets The insets to apply
23497         * @return The insets supplied, minus any insets that were consumed
23498         */
23499        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
23500    }
23501
23502    private final class UnsetPressedState implements Runnable {
23503        @Override
23504        public void run() {
23505            setPressed(false);
23506        }
23507    }
23508
23509    /**
23510     * Base class for derived classes that want to save and restore their own
23511     * state in {@link android.view.View#onSaveInstanceState()}.
23512     */
23513    public static class BaseSavedState extends AbsSavedState {
23514        String mStartActivityRequestWhoSaved;
23515
23516        /**
23517         * Constructor used when reading from a parcel. Reads the state of the superclass.
23518         *
23519         * @param source parcel to read from
23520         */
23521        public BaseSavedState(Parcel source) {
23522            this(source, null);
23523        }
23524
23525        /**
23526         * Constructor used when reading from a parcel using a given class loader.
23527         * Reads the state of the superclass.
23528         *
23529         * @param source parcel to read from
23530         * @param loader ClassLoader to use for reading
23531         */
23532        public BaseSavedState(Parcel source, ClassLoader loader) {
23533            super(source, loader);
23534            mStartActivityRequestWhoSaved = source.readString();
23535        }
23536
23537        /**
23538         * Constructor called by derived classes when creating their SavedState objects
23539         *
23540         * @param superState The state of the superclass of this view
23541         */
23542        public BaseSavedState(Parcelable superState) {
23543            super(superState);
23544        }
23545
23546        @Override
23547        public void writeToParcel(Parcel out, int flags) {
23548            super.writeToParcel(out, flags);
23549            out.writeString(mStartActivityRequestWhoSaved);
23550        }
23551
23552        public static final Parcelable.Creator<BaseSavedState> CREATOR
23553                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
23554            @Override
23555            public BaseSavedState createFromParcel(Parcel in) {
23556                return new BaseSavedState(in);
23557            }
23558
23559            @Override
23560            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
23561                return new BaseSavedState(in, loader);
23562            }
23563
23564            @Override
23565            public BaseSavedState[] newArray(int size) {
23566                return new BaseSavedState[size];
23567            }
23568        };
23569    }
23570
23571    /**
23572     * A set of information given to a view when it is attached to its parent
23573     * window.
23574     */
23575    final static class AttachInfo {
23576        interface Callbacks {
23577            void playSoundEffect(int effectId);
23578            boolean performHapticFeedback(int effectId, boolean always);
23579        }
23580
23581        /**
23582         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
23583         * to a Handler. This class contains the target (View) to invalidate and
23584         * the coordinates of the dirty rectangle.
23585         *
23586         * For performance purposes, this class also implements a pool of up to
23587         * POOL_LIMIT objects that get reused. This reduces memory allocations
23588         * whenever possible.
23589         */
23590        static class InvalidateInfo {
23591            private static final int POOL_LIMIT = 10;
23592
23593            private static final SynchronizedPool<InvalidateInfo> sPool =
23594                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
23595
23596            View target;
23597
23598            int left;
23599            int top;
23600            int right;
23601            int bottom;
23602
23603            public static InvalidateInfo obtain() {
23604                InvalidateInfo instance = sPool.acquire();
23605                return (instance != null) ? instance : new InvalidateInfo();
23606            }
23607
23608            public void recycle() {
23609                target = null;
23610                sPool.release(this);
23611            }
23612        }
23613
23614        final IWindowSession mSession;
23615
23616        final IWindow mWindow;
23617
23618        final IBinder mWindowToken;
23619
23620        final Display mDisplay;
23621
23622        final Callbacks mRootCallbacks;
23623
23624        IWindowId mIWindowId;
23625        WindowId mWindowId;
23626
23627        /**
23628         * The top view of the hierarchy.
23629         */
23630        View mRootView;
23631
23632        IBinder mPanelParentWindowToken;
23633
23634        boolean mHardwareAccelerated;
23635        boolean mHardwareAccelerationRequested;
23636        ThreadedRenderer mThreadedRenderer;
23637        List<RenderNode> mPendingAnimatingRenderNodes;
23638
23639        /**
23640         * The state of the display to which the window is attached, as reported
23641         * by {@link Display#getState()}.  Note that the display state constants
23642         * declared by {@link Display} do not exactly line up with the screen state
23643         * constants declared by {@link View} (there are more display states than
23644         * screen states).
23645         */
23646        int mDisplayState = Display.STATE_UNKNOWN;
23647
23648        /**
23649         * Scale factor used by the compatibility mode
23650         */
23651        float mApplicationScale;
23652
23653        /**
23654         * Indicates whether the application is in compatibility mode
23655         */
23656        boolean mScalingRequired;
23657
23658        /**
23659         * Left position of this view's window
23660         */
23661        int mWindowLeft;
23662
23663        /**
23664         * Top position of this view's window
23665         */
23666        int mWindowTop;
23667
23668        /**
23669         * Indicates whether views need to use 32-bit drawing caches
23670         */
23671        boolean mUse32BitDrawingCache;
23672
23673        /**
23674         * For windows that are full-screen but using insets to layout inside
23675         * of the screen areas, these are the current insets to appear inside
23676         * the overscan area of the display.
23677         */
23678        final Rect mOverscanInsets = new Rect();
23679
23680        /**
23681         * For windows that are full-screen but using insets to layout inside
23682         * of the screen decorations, these are the current insets for the
23683         * content of the window.
23684         */
23685        final Rect mContentInsets = new Rect();
23686
23687        /**
23688         * For windows that are full-screen but using insets to layout inside
23689         * of the screen decorations, these are the current insets for the
23690         * actual visible parts of the window.
23691         */
23692        final Rect mVisibleInsets = new Rect();
23693
23694        /**
23695         * For windows that are full-screen but using insets to layout inside
23696         * of the screen decorations, these are the current insets for the
23697         * stable system windows.
23698         */
23699        final Rect mStableInsets = new Rect();
23700
23701        /**
23702         * For windows that include areas that are not covered by real surface these are the outsets
23703         * for real surface.
23704         */
23705        final Rect mOutsets = new Rect();
23706
23707        /**
23708         * In multi-window we force show the navigation bar. Because we don't want that the surface
23709         * size changes in this mode, we instead have a flag whether the navigation bar size should
23710         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
23711         */
23712        boolean mAlwaysConsumeNavBar;
23713
23714        /**
23715         * The internal insets given by this window.  This value is
23716         * supplied by the client (through
23717         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
23718         * be given to the window manager when changed to be used in laying
23719         * out windows behind it.
23720         */
23721        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
23722                = new ViewTreeObserver.InternalInsetsInfo();
23723
23724        /**
23725         * Set to true when mGivenInternalInsets is non-empty.
23726         */
23727        boolean mHasNonEmptyGivenInternalInsets;
23728
23729        /**
23730         * All views in the window's hierarchy that serve as scroll containers,
23731         * used to determine if the window can be resized or must be panned
23732         * to adjust for a soft input area.
23733         */
23734        final ArrayList<View> mScrollContainers = new ArrayList<View>();
23735
23736        final KeyEvent.DispatcherState mKeyDispatchState
23737                = new KeyEvent.DispatcherState();
23738
23739        /**
23740         * Indicates whether the view's window currently has the focus.
23741         */
23742        boolean mHasWindowFocus;
23743
23744        /**
23745         * The current visibility of the window.
23746         */
23747        int mWindowVisibility;
23748
23749        /**
23750         * Indicates the time at which drawing started to occur.
23751         */
23752        long mDrawingTime;
23753
23754        /**
23755         * Indicates whether or not ignoring the DIRTY_MASK flags.
23756         */
23757        boolean mIgnoreDirtyState;
23758
23759        /**
23760         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
23761         * to avoid clearing that flag prematurely.
23762         */
23763        boolean mSetIgnoreDirtyState = false;
23764
23765        /**
23766         * Indicates whether the view's window is currently in touch mode.
23767         */
23768        boolean mInTouchMode;
23769
23770        /**
23771         * Indicates whether the view has requested unbuffered input dispatching for the current
23772         * event stream.
23773         */
23774        boolean mUnbufferedDispatchRequested;
23775
23776        /**
23777         * Indicates that ViewAncestor should trigger a global layout change
23778         * the next time it performs a traversal
23779         */
23780        boolean mRecomputeGlobalAttributes;
23781
23782        /**
23783         * Always report new attributes at next traversal.
23784         */
23785        boolean mForceReportNewAttributes;
23786
23787        /**
23788         * Set during a traveral if any views want to keep the screen on.
23789         */
23790        boolean mKeepScreenOn;
23791
23792        /**
23793         * Set during a traveral if the light center needs to be updated.
23794         */
23795        boolean mNeedsUpdateLightCenter;
23796
23797        /**
23798         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
23799         */
23800        int mSystemUiVisibility;
23801
23802        /**
23803         * Hack to force certain system UI visibility flags to be cleared.
23804         */
23805        int mDisabledSystemUiVisibility;
23806
23807        /**
23808         * Last global system UI visibility reported by the window manager.
23809         */
23810        int mGlobalSystemUiVisibility = -1;
23811
23812        /**
23813         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
23814         * attached.
23815         */
23816        boolean mHasSystemUiListeners;
23817
23818        /**
23819         * Set if the window has requested to extend into the overscan region
23820         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
23821         */
23822        boolean mOverscanRequested;
23823
23824        /**
23825         * Set if the visibility of any views has changed.
23826         */
23827        boolean mViewVisibilityChanged;
23828
23829        /**
23830         * Set to true if a view has been scrolled.
23831         */
23832        boolean mViewScrollChanged;
23833
23834        /**
23835         * Set to true if high contrast mode enabled
23836         */
23837        boolean mHighContrastText;
23838
23839        /**
23840         * Set to true if a pointer event is currently being handled.
23841         */
23842        boolean mHandlingPointerEvent;
23843
23844        /**
23845         * Global to the view hierarchy used as a temporary for dealing with
23846         * x/y points in the transparent region computations.
23847         */
23848        final int[] mTransparentLocation = new int[2];
23849
23850        /**
23851         * Global to the view hierarchy used as a temporary for dealing with
23852         * x/y points in the ViewGroup.invalidateChild implementation.
23853         */
23854        final int[] mInvalidateChildLocation = new int[2];
23855
23856        /**
23857         * Global to the view hierarchy used as a temporary for dealing with
23858         * computing absolute on-screen location.
23859         */
23860        final int[] mTmpLocation = new int[2];
23861
23862        /**
23863         * Global to the view hierarchy used as a temporary for dealing with
23864         * x/y location when view is transformed.
23865         */
23866        final float[] mTmpTransformLocation = new float[2];
23867
23868        /**
23869         * The view tree observer used to dispatch global events like
23870         * layout, pre-draw, touch mode change, etc.
23871         */
23872        final ViewTreeObserver mTreeObserver;
23873
23874        /**
23875         * A Canvas used by the view hierarchy to perform bitmap caching.
23876         */
23877        Canvas mCanvas;
23878
23879        /**
23880         * The view root impl.
23881         */
23882        final ViewRootImpl mViewRootImpl;
23883
23884        /**
23885         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
23886         * handler can be used to pump events in the UI events queue.
23887         */
23888        final Handler mHandler;
23889
23890        /**
23891         * Temporary for use in computing invalidate rectangles while
23892         * calling up the hierarchy.
23893         */
23894        final Rect mTmpInvalRect = new Rect();
23895
23896        /**
23897         * Temporary for use in computing hit areas with transformed views
23898         */
23899        final RectF mTmpTransformRect = new RectF();
23900
23901        /**
23902         * Temporary for use in computing hit areas with transformed views
23903         */
23904        final RectF mTmpTransformRect1 = new RectF();
23905
23906        /**
23907         * Temporary list of rectanges.
23908         */
23909        final List<RectF> mTmpRectList = new ArrayList<>();
23910
23911        /**
23912         * Temporary for use in transforming invalidation rect
23913         */
23914        final Matrix mTmpMatrix = new Matrix();
23915
23916        /**
23917         * Temporary for use in transforming invalidation rect
23918         */
23919        final Transformation mTmpTransformation = new Transformation();
23920
23921        /**
23922         * Temporary for use in querying outlines from OutlineProviders
23923         */
23924        final Outline mTmpOutline = new Outline();
23925
23926        /**
23927         * Temporary list for use in collecting focusable descendents of a view.
23928         */
23929        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
23930
23931        /**
23932         * The id of the window for accessibility purposes.
23933         */
23934        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
23935
23936        /**
23937         * Flags related to accessibility processing.
23938         *
23939         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
23940         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
23941         */
23942        int mAccessibilityFetchFlags;
23943
23944        /**
23945         * The drawable for highlighting accessibility focus.
23946         */
23947        Drawable mAccessibilityFocusDrawable;
23948
23949        /**
23950         * Show where the margins, bounds and layout bounds are for each view.
23951         */
23952        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23953
23954        /**
23955         * Point used to compute visible regions.
23956         */
23957        final Point mPoint = new Point();
23958
23959        /**
23960         * Used to track which View originated a requestLayout() call, used when
23961         * requestLayout() is called during layout.
23962         */
23963        View mViewRequestingLayout;
23964
23965        /**
23966         * Used to track views that need (at least) a partial relayout at their current size
23967         * during the next traversal.
23968         */
23969        List<View> mPartialLayoutViews = new ArrayList<>();
23970
23971        /**
23972         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23973         * modification. Lazily assigned during ViewRootImpl layout.
23974         */
23975        List<View> mEmptyPartialLayoutViews;
23976
23977        /**
23978         * Used to track the identity of the current drag operation.
23979         */
23980        IBinder mDragToken;
23981
23982        /**
23983         * The drag shadow surface for the current drag operation.
23984         */
23985        public Surface mDragSurface;
23986
23987
23988        /**
23989         * The view that currently has a tooltip displayed.
23990         */
23991        View mTooltipHost;
23992
23993        /**
23994         * Creates a new set of attachment information with the specified
23995         * events handler and thread.
23996         *
23997         * @param handler the events handler the view must use
23998         */
23999        AttachInfo(IWindowSession session, IWindow window, Display display,
24000                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
24001                Context context) {
24002            mSession = session;
24003            mWindow = window;
24004            mWindowToken = window.asBinder();
24005            mDisplay = display;
24006            mViewRootImpl = viewRootImpl;
24007            mHandler = handler;
24008            mRootCallbacks = effectPlayer;
24009            mTreeObserver = new ViewTreeObserver(context);
24010        }
24011    }
24012
24013    /**
24014     * <p>ScrollabilityCache holds various fields used by a View when scrolling
24015     * is supported. This avoids keeping too many unused fields in most
24016     * instances of View.</p>
24017     */
24018    private static class ScrollabilityCache implements Runnable {
24019
24020        /**
24021         * Scrollbars are not visible
24022         */
24023        public static final int OFF = 0;
24024
24025        /**
24026         * Scrollbars are visible
24027         */
24028        public static final int ON = 1;
24029
24030        /**
24031         * Scrollbars are fading away
24032         */
24033        public static final int FADING = 2;
24034
24035        public boolean fadeScrollBars;
24036
24037        public int fadingEdgeLength;
24038        public int scrollBarDefaultDelayBeforeFade;
24039        public int scrollBarFadeDuration;
24040
24041        public int scrollBarSize;
24042        public ScrollBarDrawable scrollBar;
24043        public float[] interpolatorValues;
24044        public View host;
24045
24046        public final Paint paint;
24047        public final Matrix matrix;
24048        public Shader shader;
24049
24050        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
24051
24052        private static final float[] OPAQUE = { 255 };
24053        private static final float[] TRANSPARENT = { 0.0f };
24054
24055        /**
24056         * When fading should start. This time moves into the future every time
24057         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
24058         */
24059        public long fadeStartTime;
24060
24061
24062        /**
24063         * The current state of the scrollbars: ON, OFF, or FADING
24064         */
24065        public int state = OFF;
24066
24067        private int mLastColor;
24068
24069        public final Rect mScrollBarBounds = new Rect();
24070
24071        public static final int NOT_DRAGGING = 0;
24072        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
24073        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
24074        public int mScrollBarDraggingState = NOT_DRAGGING;
24075
24076        public float mScrollBarDraggingPos = 0;
24077
24078        public ScrollabilityCache(ViewConfiguration configuration, View host) {
24079            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
24080            scrollBarSize = configuration.getScaledScrollBarSize();
24081            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
24082            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
24083
24084            paint = new Paint();
24085            matrix = new Matrix();
24086            // use use a height of 1, and then wack the matrix each time we
24087            // actually use it.
24088            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
24089            paint.setShader(shader);
24090            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
24091
24092            this.host = host;
24093        }
24094
24095        public void setFadeColor(int color) {
24096            if (color != mLastColor) {
24097                mLastColor = color;
24098
24099                if (color != 0) {
24100                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
24101                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
24102                    paint.setShader(shader);
24103                    // Restore the default transfer mode (src_over)
24104                    paint.setXfermode(null);
24105                } else {
24106                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
24107                    paint.setShader(shader);
24108                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
24109                }
24110            }
24111        }
24112
24113        public void run() {
24114            long now = AnimationUtils.currentAnimationTimeMillis();
24115            if (now >= fadeStartTime) {
24116
24117                // the animation fades the scrollbars out by changing
24118                // the opacity (alpha) from fully opaque to fully
24119                // transparent
24120                int nextFrame = (int) now;
24121                int framesCount = 0;
24122
24123                Interpolator interpolator = scrollBarInterpolator;
24124
24125                // Start opaque
24126                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
24127
24128                // End transparent
24129                nextFrame += scrollBarFadeDuration;
24130                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
24131
24132                state = FADING;
24133
24134                // Kick off the fade animation
24135                host.invalidate(true);
24136            }
24137        }
24138    }
24139
24140    /**
24141     * Resuable callback for sending
24142     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
24143     */
24144    private class SendViewScrolledAccessibilityEvent implements Runnable {
24145        public volatile boolean mIsPending;
24146
24147        public void run() {
24148            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
24149            mIsPending = false;
24150        }
24151    }
24152
24153    /**
24154     * <p>
24155     * This class represents a delegate that can be registered in a {@link View}
24156     * to enhance accessibility support via composition rather via inheritance.
24157     * It is specifically targeted to widget developers that extend basic View
24158     * classes i.e. classes in package android.view, that would like their
24159     * applications to be backwards compatible.
24160     * </p>
24161     * <div class="special reference">
24162     * <h3>Developer Guides</h3>
24163     * <p>For more information about making applications accessible, read the
24164     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
24165     * developer guide.</p>
24166     * </div>
24167     * <p>
24168     * A scenario in which a developer would like to use an accessibility delegate
24169     * is overriding a method introduced in a later API version than the minimal API
24170     * version supported by the application. For example, the method
24171     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
24172     * in API version 4 when the accessibility APIs were first introduced. If a
24173     * developer would like his application to run on API version 4 devices (assuming
24174     * all other APIs used by the application are version 4 or lower) and take advantage
24175     * of this method, instead of overriding the method which would break the application's
24176     * backwards compatibility, he can override the corresponding method in this
24177     * delegate and register the delegate in the target View if the API version of
24178     * the system is high enough, i.e. the API version is the same as or higher than the API
24179     * version that introduced
24180     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
24181     * </p>
24182     * <p>
24183     * Here is an example implementation:
24184     * </p>
24185     * <code><pre><p>
24186     * if (Build.VERSION.SDK_INT >= 14) {
24187     *     // If the API version is equal of higher than the version in
24188     *     // which onInitializeAccessibilityNodeInfo was introduced we
24189     *     // register a delegate with a customized implementation.
24190     *     View view = findViewById(R.id.view_id);
24191     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
24192     *         public void onInitializeAccessibilityNodeInfo(View host,
24193     *                 AccessibilityNodeInfo info) {
24194     *             // Let the default implementation populate the info.
24195     *             super.onInitializeAccessibilityNodeInfo(host, info);
24196     *             // Set some other information.
24197     *             info.setEnabled(host.isEnabled());
24198     *         }
24199     *     });
24200     * }
24201     * </code></pre></p>
24202     * <p>
24203     * This delegate contains methods that correspond to the accessibility methods
24204     * in View. If a delegate has been specified the implementation in View hands
24205     * off handling to the corresponding method in this delegate. The default
24206     * implementation the delegate methods behaves exactly as the corresponding
24207     * method in View for the case of no accessibility delegate been set. Hence,
24208     * to customize the behavior of a View method, clients can override only the
24209     * corresponding delegate method without altering the behavior of the rest
24210     * accessibility related methods of the host view.
24211     * </p>
24212     * <p>
24213     * <strong>Note:</strong> On platform versions prior to
24214     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
24215     * views in the {@code android.widget.*} package are called <i>before</i>
24216     * host methods. This prevents certain properties such as class name from
24217     * being modified by overriding
24218     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
24219     * as any changes will be overwritten by the host class.
24220     * <p>
24221     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
24222     * methods are called <i>after</i> host methods, which all properties to be
24223     * modified without being overwritten by the host class.
24224     */
24225    public static class AccessibilityDelegate {
24226
24227        /**
24228         * Sends an accessibility event of the given type. If accessibility is not
24229         * enabled this method has no effect.
24230         * <p>
24231         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
24232         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
24233         * been set.
24234         * </p>
24235         *
24236         * @param host The View hosting the delegate.
24237         * @param eventType The type of the event to send.
24238         *
24239         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
24240         */
24241        public void sendAccessibilityEvent(View host, int eventType) {
24242            host.sendAccessibilityEventInternal(eventType);
24243        }
24244
24245        /**
24246         * Performs the specified accessibility action on the view. For
24247         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
24248         * <p>
24249         * The default implementation behaves as
24250         * {@link View#performAccessibilityAction(int, Bundle)
24251         *  View#performAccessibilityAction(int, Bundle)} for the case of
24252         *  no accessibility delegate been set.
24253         * </p>
24254         *
24255         * @param action The action to perform.
24256         * @return Whether the action was performed.
24257         *
24258         * @see View#performAccessibilityAction(int, Bundle)
24259         *      View#performAccessibilityAction(int, Bundle)
24260         */
24261        public boolean performAccessibilityAction(View host, int action, Bundle args) {
24262            return host.performAccessibilityActionInternal(action, args);
24263        }
24264
24265        /**
24266         * Sends an accessibility event. This method behaves exactly as
24267         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
24268         * empty {@link AccessibilityEvent} and does not perform a check whether
24269         * accessibility is enabled.
24270         * <p>
24271         * The default implementation behaves as
24272         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24273         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
24274         * the case of no accessibility delegate been set.
24275         * </p>
24276         *
24277         * @param host The View hosting the delegate.
24278         * @param event The event to send.
24279         *
24280         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24281         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24282         */
24283        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
24284            host.sendAccessibilityEventUncheckedInternal(event);
24285        }
24286
24287        /**
24288         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
24289         * to its children for adding their text content to the event.
24290         * <p>
24291         * The default implementation behaves as
24292         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24293         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
24294         * the case of no accessibility delegate been set.
24295         * </p>
24296         *
24297         * @param host The View hosting the delegate.
24298         * @param event The event.
24299         * @return True if the event population was completed.
24300         *
24301         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24302         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24303         */
24304        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24305            return host.dispatchPopulateAccessibilityEventInternal(event);
24306        }
24307
24308        /**
24309         * Gives a chance to the host View to populate the accessibility event with its
24310         * text content.
24311         * <p>
24312         * The default implementation behaves as
24313         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
24314         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
24315         * the case of no accessibility delegate been set.
24316         * </p>
24317         *
24318         * @param host The View hosting the delegate.
24319         * @param event The accessibility event which to populate.
24320         *
24321         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
24322         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
24323         */
24324        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24325            host.onPopulateAccessibilityEventInternal(event);
24326        }
24327
24328        /**
24329         * Initializes an {@link AccessibilityEvent} with information about the
24330         * the host View which is the event source.
24331         * <p>
24332         * The default implementation behaves as
24333         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
24334         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
24335         * the case of no accessibility delegate been set.
24336         * </p>
24337         *
24338         * @param host The View hosting the delegate.
24339         * @param event The event to initialize.
24340         *
24341         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
24342         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
24343         */
24344        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
24345            host.onInitializeAccessibilityEventInternal(event);
24346        }
24347
24348        /**
24349         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
24350         * <p>
24351         * The default implementation behaves as
24352         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24353         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
24354         * the case of no accessibility delegate been set.
24355         * </p>
24356         *
24357         * @param host The View hosting the delegate.
24358         * @param info The instance to initialize.
24359         *
24360         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24361         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24362         */
24363        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
24364            host.onInitializeAccessibilityNodeInfoInternal(info);
24365        }
24366
24367        /**
24368         * Called when a child of the host View has requested sending an
24369         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
24370         * to augment the event.
24371         * <p>
24372         * The default implementation behaves as
24373         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24374         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
24375         * the case of no accessibility delegate been set.
24376         * </p>
24377         *
24378         * @param host The View hosting the delegate.
24379         * @param child The child which requests sending the event.
24380         * @param event The event to be sent.
24381         * @return True if the event should be sent
24382         *
24383         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24384         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24385         */
24386        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
24387                AccessibilityEvent event) {
24388            return host.onRequestSendAccessibilityEventInternal(child, event);
24389        }
24390
24391        /**
24392         * Gets the provider for managing a virtual view hierarchy rooted at this View
24393         * and reported to {@link android.accessibilityservice.AccessibilityService}s
24394         * that explore the window content.
24395         * <p>
24396         * The default implementation behaves as
24397         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
24398         * the case of no accessibility delegate been set.
24399         * </p>
24400         *
24401         * @return The provider.
24402         *
24403         * @see AccessibilityNodeProvider
24404         */
24405        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
24406            return null;
24407        }
24408
24409        /**
24410         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
24411         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
24412         * This method is responsible for obtaining an accessibility node info from a
24413         * pool of reusable instances and calling
24414         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
24415         * view to initialize the former.
24416         * <p>
24417         * <strong>Note:</strong> The client is responsible for recycling the obtained
24418         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
24419         * creation.
24420         * </p>
24421         * <p>
24422         * The default implementation behaves as
24423         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
24424         * the case of no accessibility delegate been set.
24425         * </p>
24426         * @return A populated {@link AccessibilityNodeInfo}.
24427         *
24428         * @see AccessibilityNodeInfo
24429         *
24430         * @hide
24431         */
24432        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
24433            return host.createAccessibilityNodeInfoInternal();
24434        }
24435    }
24436
24437    private class MatchIdPredicate implements Predicate<View> {
24438        public int mId;
24439
24440        @Override
24441        public boolean apply(View view) {
24442            return (view.mID == mId);
24443        }
24444    }
24445
24446    private class MatchLabelForPredicate implements Predicate<View> {
24447        private int mLabeledId;
24448
24449        @Override
24450        public boolean apply(View view) {
24451            return (view.mLabelForId == mLabeledId);
24452        }
24453    }
24454
24455    private class SendViewStateChangedAccessibilityEvent implements Runnable {
24456        private int mChangeTypes = 0;
24457        private boolean mPosted;
24458        private boolean mPostedWithDelay;
24459        private long mLastEventTimeMillis;
24460
24461        @Override
24462        public void run() {
24463            mPosted = false;
24464            mPostedWithDelay = false;
24465            mLastEventTimeMillis = SystemClock.uptimeMillis();
24466            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
24467                final AccessibilityEvent event = AccessibilityEvent.obtain();
24468                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
24469                event.setContentChangeTypes(mChangeTypes);
24470                sendAccessibilityEventUnchecked(event);
24471            }
24472            mChangeTypes = 0;
24473        }
24474
24475        public void runOrPost(int changeType) {
24476            mChangeTypes |= changeType;
24477
24478            // If this is a live region or the child of a live region, collect
24479            // all events from this frame and send them on the next frame.
24480            if (inLiveRegion()) {
24481                // If we're already posted with a delay, remove that.
24482                if (mPostedWithDelay) {
24483                    removeCallbacks(this);
24484                    mPostedWithDelay = false;
24485                }
24486                // Only post if we're not already posted.
24487                if (!mPosted) {
24488                    post(this);
24489                    mPosted = true;
24490                }
24491                return;
24492            }
24493
24494            if (mPosted) {
24495                return;
24496            }
24497
24498            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
24499            final long minEventIntevalMillis =
24500                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
24501            if (timeSinceLastMillis >= minEventIntevalMillis) {
24502                removeCallbacks(this);
24503                run();
24504            } else {
24505                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
24506                mPostedWithDelay = true;
24507            }
24508        }
24509    }
24510
24511    private boolean inLiveRegion() {
24512        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24513            return true;
24514        }
24515
24516        ViewParent parent = getParent();
24517        while (parent instanceof View) {
24518            if (((View) parent).getAccessibilityLiveRegion()
24519                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24520                return true;
24521            }
24522            parent = parent.getParent();
24523        }
24524
24525        return false;
24526    }
24527
24528    /**
24529     * Dump all private flags in readable format, useful for documentation and
24530     * sanity checking.
24531     */
24532    private static void dumpFlags() {
24533        final HashMap<String, String> found = Maps.newHashMap();
24534        try {
24535            for (Field field : View.class.getDeclaredFields()) {
24536                final int modifiers = field.getModifiers();
24537                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
24538                    if (field.getType().equals(int.class)) {
24539                        final int value = field.getInt(null);
24540                        dumpFlag(found, field.getName(), value);
24541                    } else if (field.getType().equals(int[].class)) {
24542                        final int[] values = (int[]) field.get(null);
24543                        for (int i = 0; i < values.length; i++) {
24544                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
24545                        }
24546                    }
24547                }
24548            }
24549        } catch (IllegalAccessException e) {
24550            throw new RuntimeException(e);
24551        }
24552
24553        final ArrayList<String> keys = Lists.newArrayList();
24554        keys.addAll(found.keySet());
24555        Collections.sort(keys);
24556        for (String key : keys) {
24557            Log.d(VIEW_LOG_TAG, found.get(key));
24558        }
24559    }
24560
24561    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
24562        // Sort flags by prefix, then by bits, always keeping unique keys
24563        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
24564        final int prefix = name.indexOf('_');
24565        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
24566        final String output = bits + " " + name;
24567        found.put(key, output);
24568    }
24569
24570    /** {@hide} */
24571    public void encode(@NonNull ViewHierarchyEncoder stream) {
24572        stream.beginObject(this);
24573        encodeProperties(stream);
24574        stream.endObject();
24575    }
24576
24577    /** {@hide} */
24578    @CallSuper
24579    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
24580        Object resolveId = ViewDebug.resolveId(getContext(), mID);
24581        if (resolveId instanceof String) {
24582            stream.addProperty("id", (String) resolveId);
24583        } else {
24584            stream.addProperty("id", mID);
24585        }
24586
24587        stream.addProperty("misc:transformation.alpha",
24588                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
24589        stream.addProperty("misc:transitionName", getTransitionName());
24590
24591        // layout
24592        stream.addProperty("layout:left", mLeft);
24593        stream.addProperty("layout:right", mRight);
24594        stream.addProperty("layout:top", mTop);
24595        stream.addProperty("layout:bottom", mBottom);
24596        stream.addProperty("layout:width", getWidth());
24597        stream.addProperty("layout:height", getHeight());
24598        stream.addProperty("layout:layoutDirection", getLayoutDirection());
24599        stream.addProperty("layout:layoutRtl", isLayoutRtl());
24600        stream.addProperty("layout:hasTransientState", hasTransientState());
24601        stream.addProperty("layout:baseline", getBaseline());
24602
24603        // layout params
24604        ViewGroup.LayoutParams layoutParams = getLayoutParams();
24605        if (layoutParams != null) {
24606            stream.addPropertyKey("layoutParams");
24607            layoutParams.encode(stream);
24608        }
24609
24610        // scrolling
24611        stream.addProperty("scrolling:scrollX", mScrollX);
24612        stream.addProperty("scrolling:scrollY", mScrollY);
24613
24614        // padding
24615        stream.addProperty("padding:paddingLeft", mPaddingLeft);
24616        stream.addProperty("padding:paddingRight", mPaddingRight);
24617        stream.addProperty("padding:paddingTop", mPaddingTop);
24618        stream.addProperty("padding:paddingBottom", mPaddingBottom);
24619        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
24620        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
24621        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
24622        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
24623        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
24624
24625        // measurement
24626        stream.addProperty("measurement:minHeight", mMinHeight);
24627        stream.addProperty("measurement:minWidth", mMinWidth);
24628        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
24629        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
24630
24631        // drawing
24632        stream.addProperty("drawing:elevation", getElevation());
24633        stream.addProperty("drawing:translationX", getTranslationX());
24634        stream.addProperty("drawing:translationY", getTranslationY());
24635        stream.addProperty("drawing:translationZ", getTranslationZ());
24636        stream.addProperty("drawing:rotation", getRotation());
24637        stream.addProperty("drawing:rotationX", getRotationX());
24638        stream.addProperty("drawing:rotationY", getRotationY());
24639        stream.addProperty("drawing:scaleX", getScaleX());
24640        stream.addProperty("drawing:scaleY", getScaleY());
24641        stream.addProperty("drawing:pivotX", getPivotX());
24642        stream.addProperty("drawing:pivotY", getPivotY());
24643        stream.addProperty("drawing:opaque", isOpaque());
24644        stream.addProperty("drawing:alpha", getAlpha());
24645        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
24646        stream.addProperty("drawing:shadow", hasShadow());
24647        stream.addProperty("drawing:solidColor", getSolidColor());
24648        stream.addProperty("drawing:layerType", mLayerType);
24649        stream.addProperty("drawing:willNotDraw", willNotDraw());
24650        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
24651        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
24652        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
24653        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
24654
24655        // focus
24656        stream.addProperty("focus:hasFocus", hasFocus());
24657        stream.addProperty("focus:isFocused", isFocused());
24658        stream.addProperty("focus:isFocusable", isFocusable());
24659        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
24660
24661        stream.addProperty("misc:clickable", isClickable());
24662        stream.addProperty("misc:pressed", isPressed());
24663        stream.addProperty("misc:selected", isSelected());
24664        stream.addProperty("misc:touchMode", isInTouchMode());
24665        stream.addProperty("misc:hovered", isHovered());
24666        stream.addProperty("misc:activated", isActivated());
24667
24668        stream.addProperty("misc:visibility", getVisibility());
24669        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
24670        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
24671
24672        stream.addProperty("misc:enabled", isEnabled());
24673        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
24674        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
24675
24676        // theme attributes
24677        Resources.Theme theme = getContext().getTheme();
24678        if (theme != null) {
24679            stream.addPropertyKey("theme");
24680            theme.encode(stream);
24681        }
24682
24683        // view attribute information
24684        int n = mAttributes != null ? mAttributes.length : 0;
24685        stream.addProperty("meta:__attrCount__", n/2);
24686        for (int i = 0; i < n; i += 2) {
24687            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
24688        }
24689
24690        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
24691
24692        // text
24693        stream.addProperty("text:textDirection", getTextDirection());
24694        stream.addProperty("text:textAlignment", getTextAlignment());
24695
24696        // accessibility
24697        CharSequence contentDescription = getContentDescription();
24698        stream.addProperty("accessibility:contentDescription",
24699                contentDescription == null ? "" : contentDescription.toString());
24700        stream.addProperty("accessibility:labelFor", getLabelFor());
24701        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
24702    }
24703
24704    /**
24705     * Determine if this view is rendered on a round wearable device and is the main view
24706     * on the screen.
24707     */
24708    private boolean shouldDrawRoundScrollbar() {
24709        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
24710            return false;
24711        }
24712
24713        final View rootView = getRootView();
24714        final WindowInsets insets = getRootWindowInsets();
24715
24716        int height = getHeight();
24717        int width = getWidth();
24718        int displayHeight = rootView.getHeight();
24719        int displayWidth = rootView.getWidth();
24720
24721        if (height != displayHeight || width != displayWidth) {
24722            return false;
24723        }
24724
24725        getLocationOnScreen(mAttachInfo.mTmpLocation);
24726        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
24727                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
24728    }
24729
24730    /**
24731     * Sets the tooltip text which will be displayed in a small popup next to the view.
24732     * <p>
24733     * The tooltip will be displayed:
24734     * <li>On long click, unless is not handled otherwise (by OnLongClickListener or a context
24735     * menu). </li>
24736     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
24737     *
24738     * @param tooltipText the tooltip text, or null if no tooltip is required
24739     */
24740    public final void setTooltipText(@Nullable CharSequence tooltipText) {
24741        if (TextUtils.isEmpty(tooltipText)) {
24742            setFlags(0, TOOLTIP);
24743            hideTooltip();
24744            mTooltipInfo = null;
24745        } else {
24746            setFlags(TOOLTIP, TOOLTIP);
24747            if (mTooltipInfo == null) {
24748                mTooltipInfo = new TooltipInfo();
24749                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
24750                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
24751            }
24752            mTooltipInfo.mTooltipText = tooltipText;
24753            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
24754                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText);
24755            }
24756        }
24757    }
24758
24759    /**
24760     * Returns the view's tooltip text.
24761     *
24762     * @return the tooltip text
24763     */
24764    @Nullable
24765    public final CharSequence getTooltipText() {
24766        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
24767    }
24768
24769    private boolean showTooltip(int x, int y, boolean fromLongClick) {
24770        if (mAttachInfo == null) {
24771            return false;
24772        }
24773        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
24774            return false;
24775        }
24776        final CharSequence tooltipText = getTooltipText();
24777        if (TextUtils.isEmpty(tooltipText)) {
24778            return false;
24779        }
24780        hideTooltip();
24781        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
24782        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
24783        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
24784        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, tooltipText);
24785        mAttachInfo.mTooltipHost = this;
24786        return true;
24787    }
24788
24789    void hideTooltip() {
24790        if (mTooltipInfo == null) {
24791            return;
24792        }
24793        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24794        if (mTooltipInfo.mTooltipPopup == null) {
24795            return;
24796        }
24797        mTooltipInfo.mTooltipPopup.hide();
24798        mTooltipInfo.mTooltipPopup = null;
24799        mTooltipInfo.mTooltipFromLongClick = false;
24800        if (mAttachInfo != null) {
24801            mAttachInfo.mTooltipHost = null;
24802        }
24803    }
24804
24805    private boolean showLongClickTooltip(int x, int y) {
24806        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24807        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24808        return showTooltip(x, y, true);
24809    }
24810
24811    private void showHoverTooltip() {
24812        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
24813    }
24814
24815    boolean dispatchTooltipHoverEvent(MotionEvent event) {
24816        if (mTooltipInfo == null) {
24817            return false;
24818        }
24819        switch(event.getAction()) {
24820            case MotionEvent.ACTION_HOVER_MOVE:
24821                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
24822                    break;
24823                }
24824                if (!mTooltipInfo.mTooltipFromLongClick) {
24825                    if (mTooltipInfo.mTooltipPopup == null) {
24826                        // Schedule showing the tooltip after a timeout.
24827                        mTooltipInfo.mAnchorX = (int) event.getX();
24828                        mTooltipInfo.mAnchorY = (int) event.getY();
24829                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24830                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
24831                                ViewConfiguration.getHoverTooltipShowTimeout());
24832                    }
24833
24834                    // Hide hover-triggered tooltip after a period of inactivity.
24835                    // Match the timeout used by NativeInputManager to hide the mouse pointer
24836                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
24837                    final int timeout;
24838                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
24839                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
24840                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
24841                    } else {
24842                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
24843                    }
24844                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24845                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
24846                }
24847                return true;
24848
24849            case MotionEvent.ACTION_HOVER_EXIT:
24850                if (!mTooltipInfo.mTooltipFromLongClick) {
24851                    hideTooltip();
24852                }
24853                break;
24854        }
24855        return false;
24856    }
24857
24858    void handleTooltipKey(KeyEvent event) {
24859        switch (event.getAction()) {
24860            case KeyEvent.ACTION_DOWN:
24861                if (event.getRepeatCount() == 0) {
24862                    hideTooltip();
24863                }
24864                break;
24865
24866            case KeyEvent.ACTION_UP:
24867                handleTooltipUp();
24868                break;
24869        }
24870    }
24871
24872    private void handleTooltipUp() {
24873        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24874            return;
24875        }
24876        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24877        postDelayed(mTooltipInfo.mHideTooltipRunnable,
24878                ViewConfiguration.getLongPressTooltipHideTimeout());
24879    }
24880
24881    private int getFocusableAttribute(TypedArray attributes) {
24882        TypedValue val = new TypedValue();
24883        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
24884            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
24885                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
24886            } else {
24887                return val.data;
24888            }
24889        } else {
24890            return FOCUSABLE_AUTO;
24891        }
24892    }
24893
24894    /**
24895     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
24896     * is not showing.
24897     * @hide
24898     */
24899    @TestApi
24900    public View getTooltipView() {
24901        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24902            return null;
24903        }
24904        return mTooltipInfo.mTooltipPopup.getContentView();
24905    }
24906}
24907