View.java revision bd048c598dbf84552f579a05624ae844ff203ed5
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.CallSuper;
22import android.annotation.ColorInt;
23import android.annotation.DrawableRes;
24import android.annotation.FloatRange;
25import android.annotation.IdRes;
26import android.annotation.IntDef;
27import android.annotation.IntRange;
28import android.annotation.LayoutRes;
29import android.annotation.NonNull;
30import android.annotation.Nullable;
31import android.annotation.Size;
32import android.annotation.UiThread;
33import android.content.ClipData;
34import android.content.Context;
35import android.content.ContextWrapper;
36import android.content.Intent;
37import android.content.res.ColorStateList;
38import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.content.res.TypedArray;
41import android.graphics.Bitmap;
42import android.graphics.Canvas;
43import android.graphics.Insets;
44import android.graphics.Interpolator;
45import android.graphics.LinearGradient;
46import android.graphics.Matrix;
47import android.graphics.Outline;
48import android.graphics.Paint;
49import android.graphics.PixelFormat;
50import android.graphics.Point;
51import android.graphics.PorterDuff;
52import android.graphics.PorterDuffXfermode;
53import android.graphics.Rect;
54import android.graphics.RectF;
55import android.graphics.Region;
56import android.graphics.Shader;
57import android.graphics.drawable.ColorDrawable;
58import android.graphics.drawable.Drawable;
59import android.hardware.display.DisplayManagerGlobal;
60import android.os.Build.VERSION_CODES;
61import android.os.Bundle;
62import android.os.Handler;
63import android.os.IBinder;
64import android.os.Parcel;
65import android.os.Parcelable;
66import android.os.RemoteException;
67import android.os.SystemClock;
68import android.os.SystemProperties;
69import android.os.Trace;
70import android.text.TextUtils;
71import android.util.AttributeSet;
72import android.util.FloatProperty;
73import android.util.LayoutDirection;
74import android.util.Log;
75import android.util.LongSparseLongArray;
76import android.util.Pools.SynchronizedPool;
77import android.util.Property;
78import android.util.SparseArray;
79import android.util.StateSet;
80import android.util.SuperNotCalledException;
81import android.util.TypedValue;
82import android.view.ContextMenu.ContextMenuInfo;
83import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
85import android.view.AccessibilityIterators.TextSegmentIterator;
86import android.view.AccessibilityIterators.WordTextSegmentIterator;
87import android.view.accessibility.AccessibilityEvent;
88import android.view.accessibility.AccessibilityEventSource;
89import android.view.accessibility.AccessibilityManager;
90import android.view.accessibility.AccessibilityNodeInfo;
91import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
92import android.view.accessibility.AccessibilityNodeProvider;
93import android.view.animation.Animation;
94import android.view.animation.AnimationUtils;
95import android.view.animation.Transformation;
96import android.view.inputmethod.EditorInfo;
97import android.view.inputmethod.InputConnection;
98import android.view.inputmethod.InputMethodManager;
99import android.widget.Checkable;
100import android.widget.FrameLayout;
101import android.widget.ScrollBarDrawable;
102import static android.os.Build.VERSION_CODES.*;
103import static java.lang.Math.max;
104
105import com.android.internal.R;
106import com.android.internal.util.Predicate;
107import com.android.internal.view.menu.MenuBuilder;
108import com.android.internal.widget.ScrollBarUtils;
109import com.google.android.collect.Lists;
110import com.google.android.collect.Maps;
111
112import java.lang.NullPointerException;
113import java.lang.annotation.Retention;
114import java.lang.annotation.RetentionPolicy;
115import java.lang.ref.WeakReference;
116import java.lang.reflect.Field;
117import java.lang.reflect.InvocationTargetException;
118import java.lang.reflect.Method;
119import java.lang.reflect.Modifier;
120import java.util.ArrayList;
121import java.util.Arrays;
122import java.util.Collections;
123import java.util.HashMap;
124import java.util.List;
125import java.util.Locale;
126import java.util.Map;
127import java.util.concurrent.CopyOnWriteArrayList;
128import java.util.concurrent.atomic.AtomicInteger;
129
130/**
131 * <p>
132 * This class represents the basic building block for user interface components. A View
133 * occupies a rectangular area on the screen and is responsible for drawing and
134 * event handling. View is the base class for <em>widgets</em>, which are
135 * used to create interactive UI components (buttons, text fields, etc.). The
136 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
137 * are invisible containers that hold other Views (or other ViewGroups) and define
138 * their layout properties.
139 * </p>
140 *
141 * <div class="special reference">
142 * <h3>Developer Guides</h3>
143 * <p>For information about using this class to develop your application's user interface,
144 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
145 * </div>
146 *
147 * <a name="Using"></a>
148 * <h3>Using Views</h3>
149 * <p>
150 * All of the views in a window are arranged in a single tree. You can add views
151 * either from code or by specifying a tree of views in one or more XML layout
152 * files. There are many specialized subclasses of views that act as controls or
153 * are capable of displaying text, images, or other content.
154 * </p>
155 * <p>
156 * Once you have created a tree of views, there are typically a few types of
157 * common operations you may wish to perform:
158 * <ul>
159 * <li><strong>Set properties:</strong> for example setting the text of a
160 * {@link android.widget.TextView}. The available properties and the methods
161 * that set them will vary among the different subclasses of views. Note that
162 * properties that are known at build time can be set in the XML layout
163 * files.</li>
164 * <li><strong>Set focus:</strong> The framework will handle moving focus in
165 * response to user input. To force focus to a specific view, call
166 * {@link #requestFocus}.</li>
167 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
168 * that will be notified when something interesting happens to the view. For
169 * example, all views will let you set a listener to be notified when the view
170 * gains or loses focus. You can register such a listener using
171 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
172 * Other view subclasses offer more specialized listeners. For example, a Button
173 * exposes a listener to notify clients when the button is clicked.</li>
174 * <li><strong>Set visibility:</strong> You can hide or show views using
175 * {@link #setVisibility(int)}.</li>
176 * </ul>
177 * </p>
178 * <p><em>
179 * Note: The Android framework is responsible for measuring, laying out and
180 * drawing views. You should not call methods that perform these actions on
181 * views yourself unless you are actually implementing a
182 * {@link android.view.ViewGroup}.
183 * </em></p>
184 *
185 * <a name="Lifecycle"></a>
186 * <h3>Implementing a Custom View</h3>
187 *
188 * <p>
189 * To implement a custom view, you will usually begin by providing overrides for
190 * some of the standard methods that the framework calls on all views. You do
191 * not need to override all of these methods. In fact, you can start by just
192 * overriding {@link #onDraw(android.graphics.Canvas)}.
193 * <table border="2" width="85%" align="center" cellpadding="5">
194 *     <thead>
195 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
196 *     </thead>
197 *
198 *     <tbody>
199 *     <tr>
200 *         <td rowspan="2">Creation</td>
201 *         <td>Constructors</td>
202 *         <td>There is a form of the constructor that are called when the view
203 *         is created from code and a form that is called when the view is
204 *         inflated from a layout file. The second form should parse and apply
205 *         any attributes defined in the layout file.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onFinishInflate()}</code></td>
210 *         <td>Called after a view and all of its children has been inflated
211 *         from XML.</td>
212 *     </tr>
213 *
214 *     <tr>
215 *         <td rowspan="3">Layout</td>
216 *         <td><code>{@link #onMeasure(int, int)}</code></td>
217 *         <td>Called to determine the size requirements for this view and all
218 *         of its children.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
223 *         <td>Called when this view should assign a size and position to all
224 *         of its children.
225 *         </td>
226 *     </tr>
227 *     <tr>
228 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
229 *         <td>Called when the size of this view has changed.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td>Drawing</td>
235 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
236 *         <td>Called when the view should render its content.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td rowspan="4">Event processing</td>
242 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
243 *         <td>Called when a new hardware key event occurs.
244 *         </td>
245 *     </tr>
246 *     <tr>
247 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
248 *         <td>Called when a hardware key up event occurs.
249 *         </td>
250 *     </tr>
251 *     <tr>
252 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
253 *         <td>Called when a trackball motion event occurs.
254 *         </td>
255 *     </tr>
256 *     <tr>
257 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
258 *         <td>Called when a touch screen motion event occurs.
259 *         </td>
260 *     </tr>
261 *
262 *     <tr>
263 *         <td rowspan="2">Focus</td>
264 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
265 *         <td>Called when the view gains or loses focus.
266 *         </td>
267 *     </tr>
268 *
269 *     <tr>
270 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
271 *         <td>Called when the window containing the view gains or loses focus.
272 *         </td>
273 *     </tr>
274 *
275 *     <tr>
276 *         <td rowspan="3">Attaching</td>
277 *         <td><code>{@link #onAttachedToWindow()}</code></td>
278 *         <td>Called when the view is attached to a window.
279 *         </td>
280 *     </tr>
281 *
282 *     <tr>
283 *         <td><code>{@link #onDetachedFromWindow}</code></td>
284 *         <td>Called when the view is detached from its window.
285 *         </td>
286 *     </tr>
287 *
288 *     <tr>
289 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
290 *         <td>Called when the visibility of the window containing the view
291 *         has changed.
292 *         </td>
293 *     </tr>
294 *     </tbody>
295 *
296 * </table>
297 * </p>
298 *
299 * <a name="IDs"></a>
300 * <h3>IDs</h3>
301 * Views may have an integer id associated with them. These ids are typically
302 * assigned in the layout XML files, and are used to find specific views within
303 * the view tree. A common pattern is to:
304 * <ul>
305 * <li>Define a Button in the layout file and assign it a unique ID.
306 * <pre>
307 * &lt;Button
308 *     android:id="@+id/my_button"
309 *     android:layout_width="wrap_content"
310 *     android:layout_height="wrap_content"
311 *     android:text="@string/my_button_text"/&gt;
312 * </pre></li>
313 * <li>From the onCreate method of an Activity, find the Button
314 * <pre class="prettyprint">
315 *      Button myButton = (Button) findViewById(R.id.my_button);
316 * </pre></li>
317 * </ul>
318 * <p>
319 * View IDs need not be unique throughout the tree, but it is good practice to
320 * ensure that they are at least unique within the part of the tree you are
321 * searching.
322 * </p>
323 *
324 * <a name="Position"></a>
325 * <h3>Position</h3>
326 * <p>
327 * The geometry of a view is that of a rectangle. A view has a location,
328 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
329 * two dimensions, expressed as a width and a height. The unit for location
330 * and dimensions is the pixel.
331 * </p>
332 *
333 * <p>
334 * It is possible to retrieve the location of a view by invoking the methods
335 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
336 * coordinate of the rectangle representing the view. The latter returns the
337 * top, or Y, coordinate of the rectangle representing the view. These methods
338 * both return the location of the view relative to its parent. For instance,
339 * when getLeft() returns 20, that means the view is located 20 pixels to the
340 * right of the left edge of its direct parent.
341 * </p>
342 *
343 * <p>
344 * In addition, several convenience methods are offered to avoid unnecessary
345 * computations, namely {@link #getRight()} and {@link #getBottom()}.
346 * These methods return the coordinates of the right and bottom edges of the
347 * rectangle representing the view. For instance, calling {@link #getRight()}
348 * is similar to the following computation: <code>getLeft() + getWidth()</code>
349 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
350 * </p>
351 *
352 * <a name="SizePaddingMargins"></a>
353 * <h3>Size, padding and margins</h3>
354 * <p>
355 * The size of a view is expressed with a width and a height. A view actually
356 * possess two pairs of width and height values.
357 * </p>
358 *
359 * <p>
360 * The first pair is known as <em>measured width</em> and
361 * <em>measured height</em>. These dimensions define how big a view wants to be
362 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
363 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
364 * and {@link #getMeasuredHeight()}.
365 * </p>
366 *
367 * <p>
368 * The second pair is simply known as <em>width</em> and <em>height</em>, or
369 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
370 * dimensions define the actual size of the view on screen, at drawing time and
371 * after layout. These values may, but do not have to, be different from the
372 * measured width and height. The width and height can be obtained by calling
373 * {@link #getWidth()} and {@link #getHeight()}.
374 * </p>
375 *
376 * <p>
377 * To measure its dimensions, a view takes into account its padding. The padding
378 * is expressed in pixels for the left, top, right and bottom parts of the view.
379 * Padding can be used to offset the content of the view by a specific amount of
380 * pixels. For instance, a left padding of 2 will push the view's content by
381 * 2 pixels to the right of the left edge. Padding can be set using the
382 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
383 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
384 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
385 * {@link #getPaddingEnd()}.
386 * </p>
387 *
388 * <p>
389 * Even though a view can define a padding, it does not provide any support for
390 * margins. However, view groups provide such a support. Refer to
391 * {@link android.view.ViewGroup} and
392 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
393 * </p>
394 *
395 * <a name="Layout"></a>
396 * <h3>Layout</h3>
397 * <p>
398 * Layout is a two pass process: a measure pass and a layout pass. The measuring
399 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
400 * of the view tree. Each view pushes dimension specifications down the tree
401 * during the recursion. At the end of the measure pass, every view has stored
402 * its measurements. The second pass happens in
403 * {@link #layout(int,int,int,int)} and is also top-down. During
404 * this pass each parent is responsible for positioning all of its children
405 * using the sizes computed in the measure pass.
406 * </p>
407 *
408 * <p>
409 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
410 * {@link #getMeasuredHeight()} values must be set, along with those for all of
411 * that view's descendants. A view's measured width and measured height values
412 * must respect the constraints imposed by the view's parents. This guarantees
413 * that at the end of the measure pass, all parents accept all of their
414 * children's measurements. A parent view may call measure() more than once on
415 * its children. For example, the parent may measure each child once with
416 * unspecified dimensions to find out how big they want to be, then call
417 * measure() on them again with actual numbers if the sum of all the children's
418 * unconstrained sizes is too big or too small.
419 * </p>
420 *
421 * <p>
422 * The measure pass uses two classes to communicate dimensions. The
423 * {@link MeasureSpec} class is used by views to tell their parents how they
424 * want to be measured and positioned. The base LayoutParams class just
425 * describes how big the view wants to be for both width and height. For each
426 * dimension, it can specify one of:
427 * <ul>
428 * <li> an exact number
429 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
430 * (minus padding)
431 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
432 * enclose its content (plus padding).
433 * </ul>
434 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
435 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
436 * an X and Y value.
437 * </p>
438 *
439 * <p>
440 * MeasureSpecs are used to push requirements down the tree from parent to
441 * child. A MeasureSpec can be in one of three modes:
442 * <ul>
443 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
444 * of a child view. For example, a LinearLayout may call measure() on its child
445 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
446 * tall the child view wants to be given a width of 240 pixels.
447 * <li>EXACTLY: This is used by the parent to impose an exact size on the
448 * child. The child must use this size, and guarantee that all of its
449 * descendants will fit within this size.
450 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
451 * child. The child must guarantee that it and all of its descendants will fit
452 * within this size.
453 * </ul>
454 * </p>
455 *
456 * <p>
457 * To initiate a layout, call {@link #requestLayout}. This method is typically
458 * called by a view on itself when it believes that is can no longer fit within
459 * its current bounds.
460 * </p>
461 *
462 * <a name="Drawing"></a>
463 * <h3>Drawing</h3>
464 * <p>
465 * Drawing is handled by walking the tree and recording the drawing commands of
466 * any View that needs to update. After this, the drawing commands of the
467 * entire tree are issued to screen, clipped to the newly damaged area.
468 * </p>
469 *
470 * <p>
471 * The tree is largely recorded and drawn in order, with parents drawn before
472 * (i.e., behind) their children, with siblings drawn in the order they appear
473 * in the tree. If you set a background drawable for a View, then the View will
474 * draw it before calling back to its <code>onDraw()</code> method. The child
475 * drawing order can be overridden with
476 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
477 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
478 * </p>
479 *
480 * <p>
481 * To force a view to draw, call {@link #invalidate()}.
482 * </p>
483 *
484 * <a name="EventHandlingThreading"></a>
485 * <h3>Event Handling and Threading</h3>
486 * <p>
487 * The basic cycle of a view is as follows:
488 * <ol>
489 * <li>An event comes in and is dispatched to the appropriate view. The view
490 * handles the event and notifies any listeners.</li>
491 * <li>If in the course of processing the event, the view's bounds may need
492 * to be changed, the view will call {@link #requestLayout()}.</li>
493 * <li>Similarly, if in the course of processing the event the view's appearance
494 * may need to be changed, the view will call {@link #invalidate()}.</li>
495 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
496 * the framework will take care of measuring, laying out, and drawing the tree
497 * as appropriate.</li>
498 * </ol>
499 * </p>
500 *
501 * <p><em>Note: The entire view tree is single threaded. You must always be on
502 * the UI thread when calling any method on any view.</em>
503 * If you are doing work on other threads and want to update the state of a view
504 * from that thread, you should use a {@link Handler}.
505 * </p>
506 *
507 * <a name="FocusHandling"></a>
508 * <h3>Focus Handling</h3>
509 * <p>
510 * The framework will handle routine focus movement in response to user input.
511 * This includes changing the focus as views are removed or hidden, or as new
512 * views become available. Views indicate their willingness to take focus
513 * through the {@link #isFocusable} method. To change whether a view can take
514 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
515 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
516 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
517 * </p>
518 * <p>
519 * Focus movement is based on an algorithm which finds the nearest neighbor in a
520 * given direction. In rare cases, the default algorithm may not match the
521 * intended behavior of the developer. In these situations, you can provide
522 * explicit overrides by using these XML attributes in the layout file:
523 * <pre>
524 * nextFocusDown
525 * nextFocusLeft
526 * nextFocusRight
527 * nextFocusUp
528 * </pre>
529 * </p>
530 *
531 *
532 * <p>
533 * To get a particular view to take focus, call {@link #requestFocus()}.
534 * </p>
535 *
536 * <a name="TouchMode"></a>
537 * <h3>Touch Mode</h3>
538 * <p>
539 * When a user is navigating a user interface via directional keys such as a D-pad, it is
540 * necessary to give focus to actionable items such as buttons so the user can see
541 * what will take input.  If the device has touch capabilities, however, and the user
542 * begins interacting with the interface by touching it, it is no longer necessary to
543 * always highlight, or give focus to, a particular view.  This motivates a mode
544 * for interaction named 'touch mode'.
545 * </p>
546 * <p>
547 * For a touch capable device, once the user touches the screen, the device
548 * will enter touch mode.  From this point onward, only views for which
549 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
550 * Other views that are touchable, like buttons, will not take focus when touched; they will
551 * only fire the on click listeners.
552 * </p>
553 * <p>
554 * Any time a user hits a directional key, such as a D-pad direction, the view device will
555 * exit touch mode, and find a view to take focus, so that the user may resume interacting
556 * with the user interface without touching the screen again.
557 * </p>
558 * <p>
559 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
560 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
561 * </p>
562 *
563 * <a name="Scrolling"></a>
564 * <h3>Scrolling</h3>
565 * <p>
566 * The framework provides basic support for views that wish to internally
567 * scroll their content. This includes keeping track of the X and Y scroll
568 * offset as well as mechanisms for drawing scrollbars. See
569 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
570 * {@link #awakenScrollBars()} for more details.
571 * </p>
572 *
573 * <a name="Tags"></a>
574 * <h3>Tags</h3>
575 * <p>
576 * Unlike IDs, tags are not used to identify views. Tags are essentially an
577 * extra piece of information that can be associated with a view. They are most
578 * often used as a convenience to store data related to views in the views
579 * themselves rather than by putting them in a separate structure.
580 * </p>
581 * <p>
582 * Tags may be specified with character sequence values in layout XML as either
583 * a single tag using the {@link android.R.styleable#View_tag android:tag}
584 * attribute or multiple tags using the {@code <tag>} child element:
585 * <pre>
586 *     &ltView ...
587 *           android:tag="@string/mytag_value" /&gt;
588 *     &ltView ...&gt;
589 *         &lttag android:id="@+id/mytag"
590 *              android:value="@string/mytag_value" /&gt;
591 *     &lt/View>
592 * </pre>
593 * </p>
594 * <p>
595 * Tags may also be specified with arbitrary objects from code using
596 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
597 * </p>
598 *
599 * <a name="Themes"></a>
600 * <h3>Themes</h3>
601 * <p>
602 * By default, Views are created using the theme of the Context object supplied
603 * to their constructor; however, a different theme may be specified by using
604 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
605 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
606 * code.
607 * </p>
608 * <p>
609 * When the {@link android.R.styleable#View_theme android:theme} attribute is
610 * used in XML, the specified theme is applied on top of the inflation
611 * context's theme (see {@link LayoutInflater}) and used for the view itself as
612 * well as any child elements.
613 * </p>
614 * <p>
615 * In the following example, both views will be created using the Material dark
616 * color scheme; however, because an overlay theme is used which only defines a
617 * subset of attributes, the value of
618 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
619 * the inflation context's theme (e.g. the Activity theme) will be preserved.
620 * <pre>
621 *     &ltLinearLayout
622 *             ...
623 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
624 *         &ltView ...&gt;
625 *     &lt/LinearLayout&gt;
626 * </pre>
627 * </p>
628 *
629 * <a name="Properties"></a>
630 * <h3>Properties</h3>
631 * <p>
632 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
633 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
634 * available both in the {@link Property} form as well as in similarly-named setter/getter
635 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
636 * be used to set persistent state associated with these rendering-related properties on the view.
637 * The properties and methods can also be used in conjunction with
638 * {@link android.animation.Animator Animator}-based animations, described more in the
639 * <a href="#Animation">Animation</a> section.
640 * </p>
641 *
642 * <a name="Animation"></a>
643 * <h3>Animation</h3>
644 * <p>
645 * Starting with Android 3.0, the preferred way of animating views is to use the
646 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
647 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
648 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
649 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
650 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
651 * makes animating these View properties particularly easy and efficient.
652 * </p>
653 * <p>
654 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
655 * You can attach an {@link Animation} object to a view using
656 * {@link #setAnimation(Animation)} or
657 * {@link #startAnimation(Animation)}. The animation can alter the scale,
658 * rotation, translation and alpha of a view over time. If the animation is
659 * attached to a view that has children, the animation will affect the entire
660 * subtree rooted by that node. When an animation is started, the framework will
661 * take care of redrawing the appropriate views until the animation completes.
662 * </p>
663 *
664 * <a name="Security"></a>
665 * <h3>Security</h3>
666 * <p>
667 * Sometimes it is essential that an application be able to verify that an action
668 * is being performed with the full knowledge and consent of the user, such as
669 * granting a permission request, making a purchase or clicking on an advertisement.
670 * Unfortunately, a malicious application could try to spoof the user into
671 * performing these actions, unaware, by concealing the intended purpose of the view.
672 * As a remedy, the framework offers a touch filtering mechanism that can be used to
673 * improve the security of views that provide access to sensitive functionality.
674 * </p><p>
675 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
676 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
677 * will discard touches that are received whenever the view's window is obscured by
678 * another visible window.  As a result, the view will not receive touches whenever a
679 * toast, dialog or other window appears above the view's window.
680 * </p><p>
681 * For more fine-grained control over security, consider overriding the
682 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
683 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
684 * </p>
685 *
686 * @attr ref android.R.styleable#View_alpha
687 * @attr ref android.R.styleable#View_background
688 * @attr ref android.R.styleable#View_clickable
689 * @attr ref android.R.styleable#View_contentDescription
690 * @attr ref android.R.styleable#View_drawingCacheQuality
691 * @attr ref android.R.styleable#View_duplicateParentState
692 * @attr ref android.R.styleable#View_id
693 * @attr ref android.R.styleable#View_requiresFadingEdge
694 * @attr ref android.R.styleable#View_fadeScrollbars
695 * @attr ref android.R.styleable#View_fadingEdgeLength
696 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
697 * @attr ref android.R.styleable#View_fitsSystemWindows
698 * @attr ref android.R.styleable#View_isScrollContainer
699 * @attr ref android.R.styleable#View_focusable
700 * @attr ref android.R.styleable#View_focusableInTouchMode
701 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
702 * @attr ref android.R.styleable#View_keepScreenOn
703 * @attr ref android.R.styleable#View_layerType
704 * @attr ref android.R.styleable#View_layoutDirection
705 * @attr ref android.R.styleable#View_longClickable
706 * @attr ref android.R.styleable#View_minHeight
707 * @attr ref android.R.styleable#View_minWidth
708 * @attr ref android.R.styleable#View_nextFocusDown
709 * @attr ref android.R.styleable#View_nextFocusLeft
710 * @attr ref android.R.styleable#View_nextFocusRight
711 * @attr ref android.R.styleable#View_nextFocusUp
712 * @attr ref android.R.styleable#View_onClick
713 * @attr ref android.R.styleable#View_padding
714 * @attr ref android.R.styleable#View_paddingBottom
715 * @attr ref android.R.styleable#View_paddingLeft
716 * @attr ref android.R.styleable#View_paddingRight
717 * @attr ref android.R.styleable#View_paddingTop
718 * @attr ref android.R.styleable#View_paddingStart
719 * @attr ref android.R.styleable#View_paddingEnd
720 * @attr ref android.R.styleable#View_saveEnabled
721 * @attr ref android.R.styleable#View_rotation
722 * @attr ref android.R.styleable#View_rotationX
723 * @attr ref android.R.styleable#View_rotationY
724 * @attr ref android.R.styleable#View_scaleX
725 * @attr ref android.R.styleable#View_scaleY
726 * @attr ref android.R.styleable#View_scrollX
727 * @attr ref android.R.styleable#View_scrollY
728 * @attr ref android.R.styleable#View_scrollbarSize
729 * @attr ref android.R.styleable#View_scrollbarStyle
730 * @attr ref android.R.styleable#View_scrollbars
731 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
732 * @attr ref android.R.styleable#View_scrollbarFadeDuration
733 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
734 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
735 * @attr ref android.R.styleable#View_scrollbarThumbVertical
736 * @attr ref android.R.styleable#View_scrollbarTrackVertical
737 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
739 * @attr ref android.R.styleable#View_stateListAnimator
740 * @attr ref android.R.styleable#View_transitionName
741 * @attr ref android.R.styleable#View_soundEffectsEnabled
742 * @attr ref android.R.styleable#View_tag
743 * @attr ref android.R.styleable#View_textAlignment
744 * @attr ref android.R.styleable#View_textDirection
745 * @attr ref android.R.styleable#View_transformPivotX
746 * @attr ref android.R.styleable#View_transformPivotY
747 * @attr ref android.R.styleable#View_translationX
748 * @attr ref android.R.styleable#View_translationY
749 * @attr ref android.R.styleable#View_translationZ
750 * @attr ref android.R.styleable#View_visibility
751 * @attr ref android.R.styleable#View_theme
752 *
753 * @see android.view.ViewGroup
754 */
755@UiThread
756public class View implements Drawable.Callback, KeyEvent.Callback,
757        AccessibilityEventSource {
758    private static final boolean DBG = false;
759
760    /**
761     * The logging tag used by this class with android.util.Log.
762     */
763    protected static final String VIEW_LOG_TAG = "View";
764
765    /**
766     * When set to true, apps will draw debugging information about their layouts.
767     *
768     * @hide
769     */
770    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
771
772    /**
773     * When set to true, this view will save its attribute data.
774     *
775     * @hide
776     */
777    public static boolean mDebugViewAttributes = false;
778
779    /**
780     * Used to mark a View that has no ID.
781     */
782    public static final int NO_ID = -1;
783
784    /**
785     * Signals that compatibility booleans have been initialized according to
786     * target SDK versions.
787     */
788    private static boolean sCompatibilityDone = false;
789
790    /**
791     * Use the old (broken) way of building MeasureSpecs.
792     */
793    private static boolean sUseBrokenMakeMeasureSpec = false;
794
795    /**
796     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
797     */
798    static boolean sUseZeroUnspecifiedMeasureSpec = false;
799
800    /**
801     * Ignore any optimizations using the measure cache.
802     */
803    private static boolean sIgnoreMeasureCache = false;
804
805    /**
806     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
807     */
808    private static boolean sAlwaysRemeasureExactly = false;
809
810    /**
811     * Relax constraints around whether setLayoutParams() must be called after
812     * modifying the layout params.
813     */
814    private static boolean sLayoutParamsAlwaysChanged = false;
815
816    /**
817     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
818     * without throwing
819     */
820    static boolean sTextureViewIgnoresDrawableSetters = false;
821
822    /**
823     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
824     * calling setFlags.
825     */
826    private static final int NOT_FOCUSABLE = 0x00000000;
827
828    /**
829     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
830     * setFlags.
831     */
832    private static final int FOCUSABLE = 0x00000001;
833
834    /**
835     * Mask for use with setFlags indicating bits used for focus.
836     */
837    private static final int FOCUSABLE_MASK = 0x00000001;
838
839    /**
840     * This view will adjust its padding to fit sytem windows (e.g. status bar)
841     */
842    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
843
844    /** @hide */
845    @IntDef({VISIBLE, INVISIBLE, GONE})
846    @Retention(RetentionPolicy.SOURCE)
847    public @interface Visibility {}
848
849    /**
850     * This view is visible.
851     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
852     * android:visibility}.
853     */
854    public static final int VISIBLE = 0x00000000;
855
856    /**
857     * This view is invisible, but it still takes up space for layout purposes.
858     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
859     * android:visibility}.
860     */
861    public static final int INVISIBLE = 0x00000004;
862
863    /**
864     * This view is invisible, and it doesn't take any space for layout
865     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
866     * android:visibility}.
867     */
868    public static final int GONE = 0x00000008;
869
870    /**
871     * Mask for use with setFlags indicating bits used for visibility.
872     * {@hide}
873     */
874    static final int VISIBILITY_MASK = 0x0000000C;
875
876    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
877
878    /**
879     * This view is enabled. Interpretation varies by subclass.
880     * Use with ENABLED_MASK when calling setFlags.
881     * {@hide}
882     */
883    static final int ENABLED = 0x00000000;
884
885    /**
886     * This view is disabled. Interpretation varies by subclass.
887     * Use with ENABLED_MASK when calling setFlags.
888     * {@hide}
889     */
890    static final int DISABLED = 0x00000020;
891
892   /**
893    * Mask for use with setFlags indicating bits used for indicating whether
894    * this view is enabled
895    * {@hide}
896    */
897    static final int ENABLED_MASK = 0x00000020;
898
899    /**
900     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
901     * called and further optimizations will be performed. It is okay to have
902     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
903     * {@hide}
904     */
905    static final int WILL_NOT_DRAW = 0x00000080;
906
907    /**
908     * Mask for use with setFlags indicating bits used for indicating whether
909     * this view is will draw
910     * {@hide}
911     */
912    static final int DRAW_MASK = 0x00000080;
913
914    /**
915     * <p>This view doesn't show scrollbars.</p>
916     * {@hide}
917     */
918    static final int SCROLLBARS_NONE = 0x00000000;
919
920    /**
921     * <p>This view shows horizontal scrollbars.</p>
922     * {@hide}
923     */
924    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
925
926    /**
927     * <p>This view shows vertical scrollbars.</p>
928     * {@hide}
929     */
930    static final int SCROLLBARS_VERTICAL = 0x00000200;
931
932    /**
933     * <p>Mask for use with setFlags indicating bits used for indicating which
934     * scrollbars are enabled.</p>
935     * {@hide}
936     */
937    static final int SCROLLBARS_MASK = 0x00000300;
938
939    /**
940     * Indicates that the view should filter touches when its window is obscured.
941     * Refer to the class comments for more information about this security feature.
942     * {@hide}
943     */
944    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
945
946    /**
947     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
948     * that they are optional and should be skipped if the window has
949     * requested system UI flags that ignore those insets for layout.
950     */
951    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
952
953    /**
954     * <p>This view doesn't show fading edges.</p>
955     * {@hide}
956     */
957    static final int FADING_EDGE_NONE = 0x00000000;
958
959    /**
960     * <p>This view shows horizontal fading edges.</p>
961     * {@hide}
962     */
963    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
964
965    /**
966     * <p>This view shows vertical fading edges.</p>
967     * {@hide}
968     */
969    static final int FADING_EDGE_VERTICAL = 0x00002000;
970
971    /**
972     * <p>Mask for use with setFlags indicating bits used for indicating which
973     * fading edges are enabled.</p>
974     * {@hide}
975     */
976    static final int FADING_EDGE_MASK = 0x00003000;
977
978    /**
979     * <p>Indicates this view can be clicked. When clickable, a View reacts
980     * to clicks by notifying the OnClickListener.<p>
981     * {@hide}
982     */
983    static final int CLICKABLE = 0x00004000;
984
985    /**
986     * <p>Indicates this view is caching its drawing into a bitmap.</p>
987     * {@hide}
988     */
989    static final int DRAWING_CACHE_ENABLED = 0x00008000;
990
991    /**
992     * <p>Indicates that no icicle should be saved for this view.<p>
993     * {@hide}
994     */
995    static final int SAVE_DISABLED = 0x000010000;
996
997    /**
998     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
999     * property.</p>
1000     * {@hide}
1001     */
1002    static final int SAVE_DISABLED_MASK = 0x000010000;
1003
1004    /**
1005     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1006     * {@hide}
1007     */
1008    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1009
1010    /**
1011     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1012     * {@hide}
1013     */
1014    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1015
1016    /** @hide */
1017    @Retention(RetentionPolicy.SOURCE)
1018    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1019    public @interface DrawingCacheQuality {}
1020
1021    /**
1022     * <p>Enables low quality mode for the drawing cache.</p>
1023     */
1024    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1025
1026    /**
1027     * <p>Enables high quality mode for the drawing cache.</p>
1028     */
1029    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1030
1031    /**
1032     * <p>Enables automatic quality mode for the drawing cache.</p>
1033     */
1034    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1035
1036    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1037            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1038    };
1039
1040    /**
1041     * <p>Mask for use with setFlags indicating bits used for the cache
1042     * quality property.</p>
1043     * {@hide}
1044     */
1045    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1046
1047    /**
1048     * <p>
1049     * Indicates this view can be long clicked. When long clickable, a View
1050     * reacts to long clicks by notifying the OnLongClickListener or showing a
1051     * context menu.
1052     * </p>
1053     * {@hide}
1054     */
1055    static final int LONG_CLICKABLE = 0x00200000;
1056
1057    /**
1058     * <p>Indicates that this view gets its drawable states from its direct parent
1059     * and ignores its original internal states.</p>
1060     *
1061     * @hide
1062     */
1063    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1064
1065    /**
1066     * <p>
1067     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1068     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1069     * OnContextClickListener.
1070     * </p>
1071     * {@hide}
1072     */
1073    static final int CONTEXT_CLICKABLE = 0x00800000;
1074
1075
1076    /** @hide */
1077    @IntDef({
1078        SCROLLBARS_INSIDE_OVERLAY,
1079        SCROLLBARS_INSIDE_INSET,
1080        SCROLLBARS_OUTSIDE_OVERLAY,
1081        SCROLLBARS_OUTSIDE_INSET
1082    })
1083    @Retention(RetentionPolicy.SOURCE)
1084    public @interface ScrollBarStyle {}
1085
1086    /**
1087     * The scrollbar style to display the scrollbars inside the content area,
1088     * without increasing the padding. The scrollbars will be overlaid with
1089     * translucency on the view's content.
1090     */
1091    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1092
1093    /**
1094     * The scrollbar style to display the scrollbars inside the padded area,
1095     * increasing the padding of the view. The scrollbars will not overlap the
1096     * content area of the view.
1097     */
1098    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1099
1100    /**
1101     * The scrollbar style to display the scrollbars at the edge of the view,
1102     * without increasing the padding. The scrollbars will be overlaid with
1103     * translucency.
1104     */
1105    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1106
1107    /**
1108     * The scrollbar style to display the scrollbars at the edge of the view,
1109     * increasing the padding of the view. The scrollbars will only overlap the
1110     * background, if any.
1111     */
1112    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1113
1114    /**
1115     * Mask to check if the scrollbar style is overlay or inset.
1116     * {@hide}
1117     */
1118    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1119
1120    /**
1121     * Mask to check if the scrollbar style is inside or outside.
1122     * {@hide}
1123     */
1124    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1125
1126    /**
1127     * Mask for scrollbar style.
1128     * {@hide}
1129     */
1130    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1131
1132    /**
1133     * View flag indicating that the screen should remain on while the
1134     * window containing this view is visible to the user.  This effectively
1135     * takes care of automatically setting the WindowManager's
1136     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1137     */
1138    public static final int KEEP_SCREEN_ON = 0x04000000;
1139
1140    /**
1141     * View flag indicating whether this view should have sound effects enabled
1142     * for events such as clicking and touching.
1143     */
1144    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1145
1146    /**
1147     * View flag indicating whether this view should have haptic feedback
1148     * enabled for events such as long presses.
1149     */
1150    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1151
1152    /**
1153     * <p>Indicates that the view hierarchy should stop saving state when
1154     * it reaches this view.  If state saving is initiated immediately at
1155     * the view, it will be allowed.
1156     * {@hide}
1157     */
1158    static final int PARENT_SAVE_DISABLED = 0x20000000;
1159
1160    /**
1161     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1162     * {@hide}
1163     */
1164    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1165
1166    /** @hide */
1167    @IntDef(flag = true,
1168            value = {
1169                FOCUSABLES_ALL,
1170                FOCUSABLES_TOUCH_MODE
1171            })
1172    @Retention(RetentionPolicy.SOURCE)
1173    public @interface FocusableMode {}
1174
1175    /**
1176     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1177     * should add all focusable Views regardless if they are focusable in touch mode.
1178     */
1179    public static final int FOCUSABLES_ALL = 0x00000000;
1180
1181    /**
1182     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1183     * should add only Views focusable in touch mode.
1184     */
1185    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1186
1187    /** @hide */
1188    @IntDef({
1189            FOCUS_BACKWARD,
1190            FOCUS_FORWARD,
1191            FOCUS_LEFT,
1192            FOCUS_UP,
1193            FOCUS_RIGHT,
1194            FOCUS_DOWN
1195    })
1196    @Retention(RetentionPolicy.SOURCE)
1197    public @interface FocusDirection {}
1198
1199    /** @hide */
1200    @IntDef({
1201            FOCUS_LEFT,
1202            FOCUS_UP,
1203            FOCUS_RIGHT,
1204            FOCUS_DOWN
1205    })
1206    @Retention(RetentionPolicy.SOURCE)
1207    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1208
1209    /**
1210     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1211     * item.
1212     */
1213    public static final int FOCUS_BACKWARD = 0x00000001;
1214
1215    /**
1216     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1217     * item.
1218     */
1219    public static final int FOCUS_FORWARD = 0x00000002;
1220
1221    /**
1222     * Use with {@link #focusSearch(int)}. Move focus to the left.
1223     */
1224    public static final int FOCUS_LEFT = 0x00000011;
1225
1226    /**
1227     * Use with {@link #focusSearch(int)}. Move focus up.
1228     */
1229    public static final int FOCUS_UP = 0x00000021;
1230
1231    /**
1232     * Use with {@link #focusSearch(int)}. Move focus to the right.
1233     */
1234    public static final int FOCUS_RIGHT = 0x00000042;
1235
1236    /**
1237     * Use with {@link #focusSearch(int)}. Move focus down.
1238     */
1239    public static final int FOCUS_DOWN = 0x00000082;
1240
1241    /**
1242     * Bits of {@link #getMeasuredWidthAndState()} and
1243     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1244     */
1245    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1246
1247    /**
1248     * Bits of {@link #getMeasuredWidthAndState()} and
1249     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1250     */
1251    public static final int MEASURED_STATE_MASK = 0xff000000;
1252
1253    /**
1254     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1255     * for functions that combine both width and height into a single int,
1256     * such as {@link #getMeasuredState()} and the childState argument of
1257     * {@link #resolveSizeAndState(int, int, int)}.
1258     */
1259    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1260
1261    /**
1262     * Bit of {@link #getMeasuredWidthAndState()} and
1263     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1264     * is smaller that the space the view would like to have.
1265     */
1266    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1267
1268    /**
1269     * Base View state sets
1270     */
1271    // Singles
1272    /**
1273     * Indicates the view has no states set. States are used with
1274     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1275     * view depending on its state.
1276     *
1277     * @see android.graphics.drawable.Drawable
1278     * @see #getDrawableState()
1279     */
1280    protected static final int[] EMPTY_STATE_SET;
1281    /**
1282     * Indicates the view is enabled. States are used with
1283     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1284     * view depending on its state.
1285     *
1286     * @see android.graphics.drawable.Drawable
1287     * @see #getDrawableState()
1288     */
1289    protected static final int[] ENABLED_STATE_SET;
1290    /**
1291     * Indicates the view is focused. States are used with
1292     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1293     * view depending on its state.
1294     *
1295     * @see android.graphics.drawable.Drawable
1296     * @see #getDrawableState()
1297     */
1298    protected static final int[] FOCUSED_STATE_SET;
1299    /**
1300     * Indicates the view is selected. States are used with
1301     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1302     * view depending on its state.
1303     *
1304     * @see android.graphics.drawable.Drawable
1305     * @see #getDrawableState()
1306     */
1307    protected static final int[] SELECTED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed. States are used with
1310     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1311     * view depending on its state.
1312     *
1313     * @see android.graphics.drawable.Drawable
1314     * @see #getDrawableState()
1315     */
1316    protected static final int[] PRESSED_STATE_SET;
1317    /**
1318     * Indicates the view's window has focus. States are used with
1319     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1320     * view depending on its state.
1321     *
1322     * @see android.graphics.drawable.Drawable
1323     * @see #getDrawableState()
1324     */
1325    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1326    // Doubles
1327    /**
1328     * Indicates the view is enabled and has the focus.
1329     *
1330     * @see #ENABLED_STATE_SET
1331     * @see #FOCUSED_STATE_SET
1332     */
1333    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1334    /**
1335     * Indicates the view is enabled and selected.
1336     *
1337     * @see #ENABLED_STATE_SET
1338     * @see #SELECTED_STATE_SET
1339     */
1340    protected static final int[] ENABLED_SELECTED_STATE_SET;
1341    /**
1342     * Indicates the view is enabled and that its window has focus.
1343     *
1344     * @see #ENABLED_STATE_SET
1345     * @see #WINDOW_FOCUSED_STATE_SET
1346     */
1347    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1348    /**
1349     * Indicates the view is focused and selected.
1350     *
1351     * @see #FOCUSED_STATE_SET
1352     * @see #SELECTED_STATE_SET
1353     */
1354    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1355    /**
1356     * Indicates the view has the focus and that its window has the focus.
1357     *
1358     * @see #FOCUSED_STATE_SET
1359     * @see #WINDOW_FOCUSED_STATE_SET
1360     */
1361    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1362    /**
1363     * Indicates the view is selected and that its window has the focus.
1364     *
1365     * @see #SELECTED_STATE_SET
1366     * @see #WINDOW_FOCUSED_STATE_SET
1367     */
1368    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1369    // Triples
1370    /**
1371     * Indicates the view is enabled, focused and selected.
1372     *
1373     * @see #ENABLED_STATE_SET
1374     * @see #FOCUSED_STATE_SET
1375     * @see #SELECTED_STATE_SET
1376     */
1377    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1378    /**
1379     * Indicates the view is enabled, focused and its window has the focus.
1380     *
1381     * @see #ENABLED_STATE_SET
1382     * @see #FOCUSED_STATE_SET
1383     * @see #WINDOW_FOCUSED_STATE_SET
1384     */
1385    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1386    /**
1387     * Indicates the view is enabled, selected and its window has the focus.
1388     *
1389     * @see #ENABLED_STATE_SET
1390     * @see #SELECTED_STATE_SET
1391     * @see #WINDOW_FOCUSED_STATE_SET
1392     */
1393    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1394    /**
1395     * Indicates the view is focused, selected and its window has the focus.
1396     *
1397     * @see #FOCUSED_STATE_SET
1398     * @see #SELECTED_STATE_SET
1399     * @see #WINDOW_FOCUSED_STATE_SET
1400     */
1401    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1402    /**
1403     * Indicates the view is enabled, focused, selected and its window
1404     * has the focus.
1405     *
1406     * @see #ENABLED_STATE_SET
1407     * @see #FOCUSED_STATE_SET
1408     * @see #SELECTED_STATE_SET
1409     * @see #WINDOW_FOCUSED_STATE_SET
1410     */
1411    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1412    /**
1413     * Indicates the view is pressed and its window has the focus.
1414     *
1415     * @see #PRESSED_STATE_SET
1416     * @see #WINDOW_FOCUSED_STATE_SET
1417     */
1418    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1419    /**
1420     * Indicates the view is pressed and selected.
1421     *
1422     * @see #PRESSED_STATE_SET
1423     * @see #SELECTED_STATE_SET
1424     */
1425    protected static final int[] PRESSED_SELECTED_STATE_SET;
1426    /**
1427     * Indicates the view is pressed, selected and its window has the focus.
1428     *
1429     * @see #PRESSED_STATE_SET
1430     * @see #SELECTED_STATE_SET
1431     * @see #WINDOW_FOCUSED_STATE_SET
1432     */
1433    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1434    /**
1435     * Indicates the view is pressed and focused.
1436     *
1437     * @see #PRESSED_STATE_SET
1438     * @see #FOCUSED_STATE_SET
1439     */
1440    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1441    /**
1442     * Indicates the view is pressed, focused and its window has the focus.
1443     *
1444     * @see #PRESSED_STATE_SET
1445     * @see #FOCUSED_STATE_SET
1446     * @see #WINDOW_FOCUSED_STATE_SET
1447     */
1448    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1449    /**
1450     * Indicates the view is pressed, focused and selected.
1451     *
1452     * @see #PRESSED_STATE_SET
1453     * @see #SELECTED_STATE_SET
1454     * @see #FOCUSED_STATE_SET
1455     */
1456    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1457    /**
1458     * Indicates the view is pressed, focused, selected and its window has the focus.
1459     *
1460     * @see #PRESSED_STATE_SET
1461     * @see #FOCUSED_STATE_SET
1462     * @see #SELECTED_STATE_SET
1463     * @see #WINDOW_FOCUSED_STATE_SET
1464     */
1465    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1466    /**
1467     * Indicates the view is pressed and enabled.
1468     *
1469     * @see #PRESSED_STATE_SET
1470     * @see #ENABLED_STATE_SET
1471     */
1472    protected static final int[] PRESSED_ENABLED_STATE_SET;
1473    /**
1474     * Indicates the view is pressed, enabled and its window has the focus.
1475     *
1476     * @see #PRESSED_STATE_SET
1477     * @see #ENABLED_STATE_SET
1478     * @see #WINDOW_FOCUSED_STATE_SET
1479     */
1480    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1481    /**
1482     * Indicates the view is pressed, enabled and selected.
1483     *
1484     * @see #PRESSED_STATE_SET
1485     * @see #ENABLED_STATE_SET
1486     * @see #SELECTED_STATE_SET
1487     */
1488    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1489    /**
1490     * Indicates the view is pressed, enabled, selected and its window has the
1491     * focus.
1492     *
1493     * @see #PRESSED_STATE_SET
1494     * @see #ENABLED_STATE_SET
1495     * @see #SELECTED_STATE_SET
1496     * @see #WINDOW_FOCUSED_STATE_SET
1497     */
1498    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1499    /**
1500     * Indicates the view is pressed, enabled and focused.
1501     *
1502     * @see #PRESSED_STATE_SET
1503     * @see #ENABLED_STATE_SET
1504     * @see #FOCUSED_STATE_SET
1505     */
1506    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1507    /**
1508     * Indicates the view is pressed, enabled, focused and its window has the
1509     * focus.
1510     *
1511     * @see #PRESSED_STATE_SET
1512     * @see #ENABLED_STATE_SET
1513     * @see #FOCUSED_STATE_SET
1514     * @see #WINDOW_FOCUSED_STATE_SET
1515     */
1516    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1517    /**
1518     * Indicates the view is pressed, enabled, focused and selected.
1519     *
1520     * @see #PRESSED_STATE_SET
1521     * @see #ENABLED_STATE_SET
1522     * @see #SELECTED_STATE_SET
1523     * @see #FOCUSED_STATE_SET
1524     */
1525    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1526    /**
1527     * Indicates the view is pressed, enabled, focused, selected and its window
1528     * has the focus.
1529     *
1530     * @see #PRESSED_STATE_SET
1531     * @see #ENABLED_STATE_SET
1532     * @see #SELECTED_STATE_SET
1533     * @see #FOCUSED_STATE_SET
1534     * @see #WINDOW_FOCUSED_STATE_SET
1535     */
1536    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1537
1538    static {
1539        EMPTY_STATE_SET = StateSet.get(0);
1540
1541        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1542
1543        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1544        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1545                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1546
1547        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1548        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1549                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1550        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1551                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1552        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1553                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1554                        | StateSet.VIEW_STATE_FOCUSED);
1555
1556        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1557        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1558                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1559        ENABLED_SELECTED_STATE_SET = StateSet.get(
1560                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1561        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1562                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1563                        | StateSet.VIEW_STATE_ENABLED);
1564        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1565                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1566        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1567                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1568                        | StateSet.VIEW_STATE_ENABLED);
1569        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1570                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1571                        | StateSet.VIEW_STATE_ENABLED);
1572        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1573                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1574                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1575
1576        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1577        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1578                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1579        PRESSED_SELECTED_STATE_SET = StateSet.get(
1580                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1581        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1582                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1583                        | StateSet.VIEW_STATE_PRESSED);
1584        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1585                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1586        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1587                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1588                        | StateSet.VIEW_STATE_PRESSED);
1589        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1590                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1591                        | StateSet.VIEW_STATE_PRESSED);
1592        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1593                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1594                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1595        PRESSED_ENABLED_STATE_SET = StateSet.get(
1596                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1597        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1598                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1599                        | StateSet.VIEW_STATE_PRESSED);
1600        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1601                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1602                        | StateSet.VIEW_STATE_PRESSED);
1603        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1604                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1605                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1606        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1607                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1608                        | StateSet.VIEW_STATE_PRESSED);
1609        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1610                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1611                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1612        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1613                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1614                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1615        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1616                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1617                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1618                        | StateSet.VIEW_STATE_PRESSED);
1619    }
1620
1621    /**
1622     * Accessibility event types that are dispatched for text population.
1623     */
1624    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1625            AccessibilityEvent.TYPE_VIEW_CLICKED
1626            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1627            | AccessibilityEvent.TYPE_VIEW_SELECTED
1628            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1629            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1630            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1631            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1632            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1633            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1634            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1635            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1636
1637    /**
1638     * Temporary Rect currently for use in setBackground().  This will probably
1639     * be extended in the future to hold our own class with more than just
1640     * a Rect. :)
1641     */
1642    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1643
1644    /**
1645     * Map used to store views' tags.
1646     */
1647    private SparseArray<Object> mKeyedTags;
1648
1649    /**
1650     * The next available accessibility id.
1651     */
1652    private static int sNextAccessibilityViewId;
1653
1654    /**
1655     * The animation currently associated with this view.
1656     * @hide
1657     */
1658    protected Animation mCurrentAnimation = null;
1659
1660    /**
1661     * Width as measured during measure pass.
1662     * {@hide}
1663     */
1664    @ViewDebug.ExportedProperty(category = "measurement")
1665    int mMeasuredWidth;
1666
1667    /**
1668     * Height as measured during measure pass.
1669     * {@hide}
1670     */
1671    @ViewDebug.ExportedProperty(category = "measurement")
1672    int mMeasuredHeight;
1673
1674    /**
1675     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1676     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1677     * its display list. This flag, used only when hw accelerated, allows us to clear the
1678     * flag while retaining this information until it's needed (at getDisplayList() time and
1679     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1680     *
1681     * {@hide}
1682     */
1683    boolean mRecreateDisplayList = false;
1684
1685    /**
1686     * The view's identifier.
1687     * {@hide}
1688     *
1689     * @see #setId(int)
1690     * @see #getId()
1691     */
1692    @IdRes
1693    @ViewDebug.ExportedProperty(resolveId = true)
1694    int mID = NO_ID;
1695
1696    /**
1697     * The stable ID of this view for accessibility purposes.
1698     */
1699    int mAccessibilityViewId = NO_ID;
1700
1701    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1702
1703    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1704
1705    /**
1706     * The view's tag.
1707     * {@hide}
1708     *
1709     * @see #setTag(Object)
1710     * @see #getTag()
1711     */
1712    protected Object mTag = null;
1713
1714    // for mPrivateFlags:
1715    /** {@hide} */
1716    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1717    /** {@hide} */
1718    static final int PFLAG_FOCUSED                     = 0x00000002;
1719    /** {@hide} */
1720    static final int PFLAG_SELECTED                    = 0x00000004;
1721    /** {@hide} */
1722    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1723    /** {@hide} */
1724    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1725    /** {@hide} */
1726    static final int PFLAG_DRAWN                       = 0x00000020;
1727    /**
1728     * When this flag is set, this view is running an animation on behalf of its
1729     * children and should therefore not cancel invalidate requests, even if they
1730     * lie outside of this view's bounds.
1731     *
1732     * {@hide}
1733     */
1734    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1735    /** {@hide} */
1736    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1737    /** {@hide} */
1738    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1739    /** {@hide} */
1740    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1741    /** {@hide} */
1742    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1743    /** {@hide} */
1744    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1745    /** {@hide} */
1746    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1747
1748    private static final int PFLAG_PRESSED             = 0x00004000;
1749
1750    /** {@hide} */
1751    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1752    /**
1753     * Flag used to indicate that this view should be drawn once more (and only once
1754     * more) after its animation has completed.
1755     * {@hide}
1756     */
1757    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1758
1759    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1760
1761    /**
1762     * Indicates that the View returned true when onSetAlpha() was called and that
1763     * the alpha must be restored.
1764     * {@hide}
1765     */
1766    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1767
1768    /**
1769     * Set by {@link #setScrollContainer(boolean)}.
1770     */
1771    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1772
1773    /**
1774     * Set by {@link #setScrollContainer(boolean)}.
1775     */
1776    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1777
1778    /**
1779     * View flag indicating whether this view was invalidated (fully or partially.)
1780     *
1781     * @hide
1782     */
1783    static final int PFLAG_DIRTY                       = 0x00200000;
1784
1785    /**
1786     * View flag indicating whether this view was invalidated by an opaque
1787     * invalidate request.
1788     *
1789     * @hide
1790     */
1791    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1792
1793    /**
1794     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1795     *
1796     * @hide
1797     */
1798    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1799
1800    /**
1801     * Indicates whether the background is opaque.
1802     *
1803     * @hide
1804     */
1805    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1806
1807    /**
1808     * Indicates whether the scrollbars are opaque.
1809     *
1810     * @hide
1811     */
1812    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1813
1814    /**
1815     * Indicates whether the view is opaque.
1816     *
1817     * @hide
1818     */
1819    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1820
1821    /**
1822     * Indicates a prepressed state;
1823     * the short time between ACTION_DOWN and recognizing
1824     * a 'real' press. Prepressed is used to recognize quick taps
1825     * even when they are shorter than ViewConfiguration.getTapTimeout().
1826     *
1827     * @hide
1828     */
1829    private static final int PFLAG_PREPRESSED          = 0x02000000;
1830
1831    /**
1832     * Indicates whether the view is temporarily detached.
1833     *
1834     * @hide
1835     */
1836    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1837
1838    /**
1839     * Indicates that we should awaken scroll bars once attached
1840     *
1841     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1842     * during window attachment and it is no longer needed. Feel free to repurpose it.
1843     *
1844     * @hide
1845     */
1846    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1847
1848    /**
1849     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1850     * @hide
1851     */
1852    private static final int PFLAG_HOVERED             = 0x10000000;
1853
1854    /**
1855     * no longer needed, should be reused
1856     */
1857    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1858
1859    /** {@hide} */
1860    static final int PFLAG_ACTIVATED                   = 0x40000000;
1861
1862    /**
1863     * Indicates that this view was specifically invalidated, not just dirtied because some
1864     * child view was invalidated. The flag is used to determine when we need to recreate
1865     * a view's display list (as opposed to just returning a reference to its existing
1866     * display list).
1867     *
1868     * @hide
1869     */
1870    static final int PFLAG_INVALIDATED                 = 0x80000000;
1871
1872    /**
1873     * Masks for mPrivateFlags2, as generated by dumpFlags():
1874     *
1875     * |-------|-------|-------|-------|
1876     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1877     *                                1  PFLAG2_DRAG_HOVERED
1878     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1879     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1880     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1881     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1882     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1883     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1884     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1885     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1886     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1887     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1888     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1889     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1890     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1891     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1892     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1893     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1894     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1895     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1896     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1897     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1898     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1899     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1900     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1901     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1902     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1903     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1904     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1905     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1906     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1907     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1908     *    1                              PFLAG2_PADDING_RESOLVED
1909     *   1                               PFLAG2_DRAWABLE_RESOLVED
1910     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1911     * |-------|-------|-------|-------|
1912     */
1913
1914    /**
1915     * Indicates that this view has reported that it can accept the current drag's content.
1916     * Cleared when the drag operation concludes.
1917     * @hide
1918     */
1919    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1920
1921    /**
1922     * Indicates that this view is currently directly under the drag location in a
1923     * drag-and-drop operation involving content that it can accept.  Cleared when
1924     * the drag exits the view, or when the drag operation concludes.
1925     * @hide
1926     */
1927    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1928
1929    /** @hide */
1930    @IntDef({
1931        LAYOUT_DIRECTION_LTR,
1932        LAYOUT_DIRECTION_RTL,
1933        LAYOUT_DIRECTION_INHERIT,
1934        LAYOUT_DIRECTION_LOCALE
1935    })
1936    @Retention(RetentionPolicy.SOURCE)
1937    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1938    public @interface LayoutDir {}
1939
1940    /** @hide */
1941    @IntDef({
1942        LAYOUT_DIRECTION_LTR,
1943        LAYOUT_DIRECTION_RTL
1944    })
1945    @Retention(RetentionPolicy.SOURCE)
1946    public @interface ResolvedLayoutDir {}
1947
1948    /**
1949     * A flag to indicate that the layout direction of this view has not been defined yet.
1950     * @hide
1951     */
1952    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
1953
1954    /**
1955     * Horizontal layout direction of this view is from Left to Right.
1956     * Use with {@link #setLayoutDirection}.
1957     */
1958    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1959
1960    /**
1961     * Horizontal layout direction of this view is from Right to Left.
1962     * Use with {@link #setLayoutDirection}.
1963     */
1964    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1965
1966    /**
1967     * Horizontal layout direction of this view is inherited from its parent.
1968     * Use with {@link #setLayoutDirection}.
1969     */
1970    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1971
1972    /**
1973     * Horizontal layout direction of this view is from deduced from the default language
1974     * script for the locale. Use with {@link #setLayoutDirection}.
1975     */
1976    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1977
1978    /**
1979     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1980     * @hide
1981     */
1982    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1983
1984    /**
1985     * Mask for use with private flags indicating bits used for horizontal layout direction.
1986     * @hide
1987     */
1988    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1989
1990    /**
1991     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1992     * right-to-left direction.
1993     * @hide
1994     */
1995    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1996
1997    /**
1998     * Indicates whether the view horizontal layout direction has been resolved.
1999     * @hide
2000     */
2001    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2002
2003    /**
2004     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2005     * @hide
2006     */
2007    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2008            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2009
2010    /*
2011     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2012     * flag value.
2013     * @hide
2014     */
2015    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2016            LAYOUT_DIRECTION_LTR,
2017            LAYOUT_DIRECTION_RTL,
2018            LAYOUT_DIRECTION_INHERIT,
2019            LAYOUT_DIRECTION_LOCALE
2020    };
2021
2022    /**
2023     * Default horizontal layout direction.
2024     */
2025    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2026
2027    /**
2028     * Default horizontal layout direction.
2029     * @hide
2030     */
2031    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2032
2033    /**
2034     * Text direction is inherited through {@link ViewGroup}
2035     */
2036    public static final int TEXT_DIRECTION_INHERIT = 0;
2037
2038    /**
2039     * Text direction is using "first strong algorithm". The first strong directional character
2040     * determines the paragraph direction. If there is no strong directional character, the
2041     * paragraph direction is the view's resolved layout direction.
2042     */
2043    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2044
2045    /**
2046     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2047     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2048     * If there are neither, the paragraph direction is the view's resolved layout direction.
2049     */
2050    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2051
2052    /**
2053     * Text direction is forced to LTR.
2054     */
2055    public static final int TEXT_DIRECTION_LTR = 3;
2056
2057    /**
2058     * Text direction is forced to RTL.
2059     */
2060    public static final int TEXT_DIRECTION_RTL = 4;
2061
2062    /**
2063     * Text direction is coming from the system Locale.
2064     */
2065    public static final int TEXT_DIRECTION_LOCALE = 5;
2066
2067    /**
2068     * Text direction is using "first strong algorithm". The first strong directional character
2069     * determines the paragraph direction. If there is no strong directional character, the
2070     * paragraph direction is LTR.
2071     */
2072    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2073
2074    /**
2075     * Text direction is using "first strong algorithm". The first strong directional character
2076     * determines the paragraph direction. If there is no strong directional character, the
2077     * paragraph direction is RTL.
2078     */
2079    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2080
2081    /**
2082     * Default text direction is inherited
2083     */
2084    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2085
2086    /**
2087     * Default resolved text direction
2088     * @hide
2089     */
2090    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2091
2092    /**
2093     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2094     * @hide
2095     */
2096    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2097
2098    /**
2099     * Mask for use with private flags indicating bits used for text direction.
2100     * @hide
2101     */
2102    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2103            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2104
2105    /**
2106     * Array of text direction flags for mapping attribute "textDirection" to correct
2107     * flag value.
2108     * @hide
2109     */
2110    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2111            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2112            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2113            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2114            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2115            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2116            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2117            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2118            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2119    };
2120
2121    /**
2122     * Indicates whether the view text direction has been resolved.
2123     * @hide
2124     */
2125    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2126            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2127
2128    /**
2129     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2130     * @hide
2131     */
2132    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2133
2134    /**
2135     * Mask for use with private flags indicating bits used for resolved text direction.
2136     * @hide
2137     */
2138    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2139            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2140
2141    /**
2142     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2143     * @hide
2144     */
2145    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2146            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2147
2148    /** @hide */
2149    @IntDef({
2150        TEXT_ALIGNMENT_INHERIT,
2151        TEXT_ALIGNMENT_GRAVITY,
2152        TEXT_ALIGNMENT_CENTER,
2153        TEXT_ALIGNMENT_TEXT_START,
2154        TEXT_ALIGNMENT_TEXT_END,
2155        TEXT_ALIGNMENT_VIEW_START,
2156        TEXT_ALIGNMENT_VIEW_END
2157    })
2158    @Retention(RetentionPolicy.SOURCE)
2159    public @interface TextAlignment {}
2160
2161    /**
2162     * Default text alignment. The text alignment of this View is inherited from its parent.
2163     * Use with {@link #setTextAlignment(int)}
2164     */
2165    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2166
2167    /**
2168     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2169     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2170     *
2171     * Use with {@link #setTextAlignment(int)}
2172     */
2173    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2174
2175    /**
2176     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2177     *
2178     * Use with {@link #setTextAlignment(int)}
2179     */
2180    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2181
2182    /**
2183     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2184     *
2185     * Use with {@link #setTextAlignment(int)}
2186     */
2187    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2188
2189    /**
2190     * Center the paragraph, e.g. ALIGN_CENTER.
2191     *
2192     * Use with {@link #setTextAlignment(int)}
2193     */
2194    public static final int TEXT_ALIGNMENT_CENTER = 4;
2195
2196    /**
2197     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2198     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2199     *
2200     * Use with {@link #setTextAlignment(int)}
2201     */
2202    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2203
2204    /**
2205     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2206     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2207     *
2208     * Use with {@link #setTextAlignment(int)}
2209     */
2210    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2211
2212    /**
2213     * Default text alignment is inherited
2214     */
2215    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2216
2217    /**
2218     * Default resolved text alignment
2219     * @hide
2220     */
2221    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2222
2223    /**
2224      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2225      * @hide
2226      */
2227    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2228
2229    /**
2230      * Mask for use with private flags indicating bits used for text alignment.
2231      * @hide
2232      */
2233    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2234
2235    /**
2236     * Array of text direction flags for mapping attribute "textAlignment" to correct
2237     * flag value.
2238     * @hide
2239     */
2240    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2241            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2242            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2243            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2244            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2245            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2246            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2247            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2248    };
2249
2250    /**
2251     * Indicates whether the view text alignment has been resolved.
2252     * @hide
2253     */
2254    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2255
2256    /**
2257     * Bit shift to get the resolved text alignment.
2258     * @hide
2259     */
2260    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2261
2262    /**
2263     * Mask for use with private flags indicating bits used for text alignment.
2264     * @hide
2265     */
2266    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2267            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2268
2269    /**
2270     * Indicates whether if the view text alignment has been resolved to gravity
2271     */
2272    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2273            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2274
2275    // Accessiblity constants for mPrivateFlags2
2276
2277    /**
2278     * Shift for the bits in {@link #mPrivateFlags2} related to the
2279     * "importantForAccessibility" attribute.
2280     */
2281    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2282
2283    /**
2284     * Automatically determine whether a view is important for accessibility.
2285     */
2286    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2287
2288    /**
2289     * The view is important for accessibility.
2290     */
2291    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2292
2293    /**
2294     * The view is not important for accessibility.
2295     */
2296    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2297
2298    /**
2299     * The view is not important for accessibility, nor are any of its
2300     * descendant views.
2301     */
2302    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2303
2304    /**
2305     * The default whether the view is important for accessibility.
2306     */
2307    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2308
2309    /**
2310     * Mask for obtainig the bits which specify how to determine
2311     * whether a view is important for accessibility.
2312     */
2313    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2314        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2315        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2316        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2317
2318    /**
2319     * Shift for the bits in {@link #mPrivateFlags2} related to the
2320     * "accessibilityLiveRegion" attribute.
2321     */
2322    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2323
2324    /**
2325     * Live region mode specifying that accessibility services should not
2326     * automatically announce changes to this view. This is the default live
2327     * region mode for most views.
2328     * <p>
2329     * Use with {@link #setAccessibilityLiveRegion(int)}.
2330     */
2331    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2332
2333    /**
2334     * Live region mode specifying that accessibility services should announce
2335     * changes to this view.
2336     * <p>
2337     * Use with {@link #setAccessibilityLiveRegion(int)}.
2338     */
2339    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2340
2341    /**
2342     * Live region mode specifying that accessibility services should interrupt
2343     * ongoing speech to immediately announce changes to this view.
2344     * <p>
2345     * Use with {@link #setAccessibilityLiveRegion(int)}.
2346     */
2347    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2348
2349    /**
2350     * The default whether the view is important for accessibility.
2351     */
2352    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2353
2354    /**
2355     * Mask for obtaining the bits which specify a view's accessibility live
2356     * region mode.
2357     */
2358    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2359            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2360            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2361
2362    /**
2363     * Flag indicating whether a view has accessibility focus.
2364     */
2365    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2366
2367    /**
2368     * Flag whether the accessibility state of the subtree rooted at this view changed.
2369     */
2370    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2371
2372    /**
2373     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2374     * is used to check whether later changes to the view's transform should invalidate the
2375     * view to force the quickReject test to run again.
2376     */
2377    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2378
2379    /**
2380     * Flag indicating that start/end padding has been resolved into left/right padding
2381     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2382     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2383     * during measurement. In some special cases this is required such as when an adapter-based
2384     * view measures prospective children without attaching them to a window.
2385     */
2386    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2387
2388    /**
2389     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2390     */
2391    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2392
2393    /**
2394     * Indicates that the view is tracking some sort of transient state
2395     * that the app should not need to be aware of, but that the framework
2396     * should take special care to preserve.
2397     */
2398    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2399
2400    /**
2401     * Group of bits indicating that RTL properties resolution is done.
2402     */
2403    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2404            PFLAG2_TEXT_DIRECTION_RESOLVED |
2405            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2406            PFLAG2_PADDING_RESOLVED |
2407            PFLAG2_DRAWABLE_RESOLVED;
2408
2409    // There are a couple of flags left in mPrivateFlags2
2410
2411    /* End of masks for mPrivateFlags2 */
2412
2413    /**
2414     * Masks for mPrivateFlags3, as generated by dumpFlags():
2415     *
2416     * |-------|-------|-------|-------|
2417     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2418     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2419     *                               1   PFLAG3_IS_LAID_OUT
2420     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2421     *                             1     PFLAG3_CALLED_SUPER
2422     *                            1      PFLAG3_APPLYING_INSETS
2423     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2424     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2425     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2426     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2427     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2428     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2429     *                     1             PFLAG3_SCROLL_INDICATOR_START
2430     *                    1              PFLAG3_SCROLL_INDICATOR_END
2431     *                   1               PFLAG3_ASSIST_BLOCKED
2432     *                  1                PFLAG3_POINTER_ICON_NULL
2433     *                 1                 PFLAG3_POINTER_ICON_VALUE_START
2434     *           11111111                PFLAG3_POINTER_ICON_MASK
2435     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2436     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2437     *        1                          PFLAG3_TEMPORARY_DETACH
2438     * |-------|-------|-------|-------|
2439     */
2440
2441    /**
2442     * Flag indicating that view has a transform animation set on it. This is used to track whether
2443     * an animation is cleared between successive frames, in order to tell the associated
2444     * DisplayList to clear its animation matrix.
2445     */
2446    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2447
2448    /**
2449     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2450     * animation is cleared between successive frames, in order to tell the associated
2451     * DisplayList to restore its alpha value.
2452     */
2453    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2454
2455    /**
2456     * Flag indicating that the view has been through at least one layout since it
2457     * was last attached to a window.
2458     */
2459    static final int PFLAG3_IS_LAID_OUT = 0x4;
2460
2461    /**
2462     * Flag indicating that a call to measure() was skipped and should be done
2463     * instead when layout() is invoked.
2464     */
2465    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2466
2467    /**
2468     * Flag indicating that an overridden method correctly called down to
2469     * the superclass implementation as required by the API spec.
2470     */
2471    static final int PFLAG3_CALLED_SUPER = 0x10;
2472
2473    /**
2474     * Flag indicating that we're in the process of applying window insets.
2475     */
2476    static final int PFLAG3_APPLYING_INSETS = 0x20;
2477
2478    /**
2479     * Flag indicating that we're in the process of fitting system windows using the old method.
2480     */
2481    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2482
2483    /**
2484     * Flag indicating that nested scrolling is enabled for this view.
2485     * The view will optionally cooperate with views up its parent chain to allow for
2486     * integrated nested scrolling along the same axis.
2487     */
2488    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2489
2490    /**
2491     * Flag indicating that the bottom scroll indicator should be displayed
2492     * when this view can scroll up.
2493     */
2494    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2495
2496    /**
2497     * Flag indicating that the bottom scroll indicator should be displayed
2498     * when this view can scroll down.
2499     */
2500    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2501
2502    /**
2503     * Flag indicating that the left scroll indicator should be displayed
2504     * when this view can scroll left.
2505     */
2506    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2507
2508    /**
2509     * Flag indicating that the right scroll indicator should be displayed
2510     * when this view can scroll right.
2511     */
2512    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2513
2514    /**
2515     * Flag indicating that the start scroll indicator should be displayed
2516     * when this view can scroll in the start direction.
2517     */
2518    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2519
2520    /**
2521     * Flag indicating that the end scroll indicator should be displayed
2522     * when this view can scroll in the end direction.
2523     */
2524    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2525
2526    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2527
2528    static final int SCROLL_INDICATORS_NONE = 0x0000;
2529
2530    /**
2531     * Mask for use with setFlags indicating bits used for indicating which
2532     * scroll indicators are enabled.
2533     */
2534    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2535            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2536            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2537            | PFLAG3_SCROLL_INDICATOR_END;
2538
2539    /**
2540     * Left-shift required to translate between public scroll indicator flags
2541     * and internal PFLAGS3 flags. When used as a right-shift, translates
2542     * PFLAGS3 flags to public flags.
2543     */
2544    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2545
2546    /** @hide */
2547    @Retention(RetentionPolicy.SOURCE)
2548    @IntDef(flag = true,
2549            value = {
2550                    SCROLL_INDICATOR_TOP,
2551                    SCROLL_INDICATOR_BOTTOM,
2552                    SCROLL_INDICATOR_LEFT,
2553                    SCROLL_INDICATOR_RIGHT,
2554                    SCROLL_INDICATOR_START,
2555                    SCROLL_INDICATOR_END,
2556            })
2557    public @interface ScrollIndicators {}
2558
2559    /**
2560     * Scroll indicator direction for the top edge of the view.
2561     *
2562     * @see #setScrollIndicators(int)
2563     * @see #setScrollIndicators(int, int)
2564     * @see #getScrollIndicators()
2565     */
2566    public static final int SCROLL_INDICATOR_TOP =
2567            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2568
2569    /**
2570     * Scroll indicator direction for the bottom edge of the view.
2571     *
2572     * @see #setScrollIndicators(int)
2573     * @see #setScrollIndicators(int, int)
2574     * @see #getScrollIndicators()
2575     */
2576    public static final int SCROLL_INDICATOR_BOTTOM =
2577            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2578
2579    /**
2580     * Scroll indicator direction for the left edge of the view.
2581     *
2582     * @see #setScrollIndicators(int)
2583     * @see #setScrollIndicators(int, int)
2584     * @see #getScrollIndicators()
2585     */
2586    public static final int SCROLL_INDICATOR_LEFT =
2587            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2588
2589    /**
2590     * Scroll indicator direction for the right edge of the view.
2591     *
2592     * @see #setScrollIndicators(int)
2593     * @see #setScrollIndicators(int, int)
2594     * @see #getScrollIndicators()
2595     */
2596    public static final int SCROLL_INDICATOR_RIGHT =
2597            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2598
2599    /**
2600     * Scroll indicator direction for the starting edge of the view.
2601     * <p>
2602     * Resolved according to the view's layout direction, see
2603     * {@link #getLayoutDirection()} for more information.
2604     *
2605     * @see #setScrollIndicators(int)
2606     * @see #setScrollIndicators(int, int)
2607     * @see #getScrollIndicators()
2608     */
2609    public static final int SCROLL_INDICATOR_START =
2610            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2611
2612    /**
2613     * Scroll indicator direction for the ending edge of the view.
2614     * <p>
2615     * Resolved according to the view's layout direction, see
2616     * {@link #getLayoutDirection()} for more information.
2617     *
2618     * @see #setScrollIndicators(int)
2619     * @see #setScrollIndicators(int, int)
2620     * @see #getScrollIndicators()
2621     */
2622    public static final int SCROLL_INDICATOR_END =
2623            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2624
2625    /**
2626     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2627     * into this view.<p>
2628     */
2629    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2630
2631    /**
2632     * The mask for use with private flags indicating bits used for pointer icon shapes.
2633     */
2634    static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000;
2635
2636    /**
2637     * Left-shift used for pointer icon shape values in private flags.
2638     */
2639    static final int PFLAG3_POINTER_ICON_LSHIFT = 15;
2640
2641    /**
2642     * Value indicating no specific pointer icons.
2643     */
2644    private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT;
2645
2646    /**
2647     * Value indicating {@link PointerIcon.STYLE_NULL}.
2648     */
2649    private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT;
2650
2651    /**
2652     * The base value for other pointer icon shapes.
2653     */
2654    private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT;
2655
2656    /**
2657     * Whether this view has rendered elements that overlap (see {@link
2658     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2659     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2660     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2661     * determined by whatever {@link #hasOverlappingRendering()} returns.
2662     */
2663    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2664
2665    /**
2666     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2667     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2668     */
2669    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2670
2671    /**
2672     * Flag indicating that the view is temporarily detached from the parent view.
2673     *
2674     * @see #onStartTemporaryDetach()
2675     * @see #onFinishTemporaryDetach()
2676     */
2677    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2678
2679    /* End of masks for mPrivateFlags3 */
2680
2681    /**
2682     * Always allow a user to over-scroll this view, provided it is a
2683     * view that can scroll.
2684     *
2685     * @see #getOverScrollMode()
2686     * @see #setOverScrollMode(int)
2687     */
2688    public static final int OVER_SCROLL_ALWAYS = 0;
2689
2690    /**
2691     * Allow a user to over-scroll this view only if the content is large
2692     * enough to meaningfully scroll, provided it is a view that can scroll.
2693     *
2694     * @see #getOverScrollMode()
2695     * @see #setOverScrollMode(int)
2696     */
2697    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2698
2699    /**
2700     * Never allow a user to over-scroll this view.
2701     *
2702     * @see #getOverScrollMode()
2703     * @see #setOverScrollMode(int)
2704     */
2705    public static final int OVER_SCROLL_NEVER = 2;
2706
2707    /**
2708     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2709     * requested the system UI (status bar) to be visible (the default).
2710     *
2711     * @see #setSystemUiVisibility(int)
2712     */
2713    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2714
2715    /**
2716     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2717     * system UI to enter an unobtrusive "low profile" mode.
2718     *
2719     * <p>This is for use in games, book readers, video players, or any other
2720     * "immersive" application where the usual system chrome is deemed too distracting.
2721     *
2722     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2723     *
2724     * @see #setSystemUiVisibility(int)
2725     */
2726    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2727
2728    /**
2729     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2730     * system navigation be temporarily hidden.
2731     *
2732     * <p>This is an even less obtrusive state than that called for by
2733     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2734     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2735     * those to disappear. This is useful (in conjunction with the
2736     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2737     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2738     * window flags) for displaying content using every last pixel on the display.
2739     *
2740     * <p>There is a limitation: because navigation controls are so important, the least user
2741     * interaction will cause them to reappear immediately.  When this happens, both
2742     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2743     * so that both elements reappear at the same time.
2744     *
2745     * @see #setSystemUiVisibility(int)
2746     */
2747    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2748
2749    /**
2750     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2751     * into the normal fullscreen mode so that its content can take over the screen
2752     * while still allowing the user to interact with the application.
2753     *
2754     * <p>This has the same visual effect as
2755     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2756     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2757     * meaning that non-critical screen decorations (such as the status bar) will be
2758     * hidden while the user is in the View's window, focusing the experience on
2759     * that content.  Unlike the window flag, if you are using ActionBar in
2760     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2761     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2762     * hide the action bar.
2763     *
2764     * <p>This approach to going fullscreen is best used over the window flag when
2765     * it is a transient state -- that is, the application does this at certain
2766     * points in its user interaction where it wants to allow the user to focus
2767     * on content, but not as a continuous state.  For situations where the application
2768     * would like to simply stay full screen the entire time (such as a game that
2769     * wants to take over the screen), the
2770     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2771     * is usually a better approach.  The state set here will be removed by the system
2772     * in various situations (such as the user moving to another application) like
2773     * the other system UI states.
2774     *
2775     * <p>When using this flag, the application should provide some easy facility
2776     * for the user to go out of it.  A common example would be in an e-book
2777     * reader, where tapping on the screen brings back whatever screen and UI
2778     * decorations that had been hidden while the user was immersed in reading
2779     * the book.
2780     *
2781     * @see #setSystemUiVisibility(int)
2782     */
2783    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2784
2785    /**
2786     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2787     * flags, we would like a stable view of the content insets given to
2788     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2789     * will always represent the worst case that the application can expect
2790     * as a continuous state.  In the stock Android UI this is the space for
2791     * the system bar, nav bar, and status bar, but not more transient elements
2792     * such as an input method.
2793     *
2794     * The stable layout your UI sees is based on the system UI modes you can
2795     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2796     * then you will get a stable layout for changes of the
2797     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2798     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2799     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2800     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2801     * with a stable layout.  (Note that you should avoid using
2802     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2803     *
2804     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2805     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2806     * then a hidden status bar will be considered a "stable" state for purposes
2807     * here.  This allows your UI to continually hide the status bar, while still
2808     * using the system UI flags to hide the action bar while still retaining
2809     * a stable layout.  Note that changing the window fullscreen flag will never
2810     * provide a stable layout for a clean transition.
2811     *
2812     * <p>If you are using ActionBar in
2813     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2814     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2815     * insets it adds to those given to the application.
2816     */
2817    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2818
2819    /**
2820     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2821     * to be laid out as if it has requested
2822     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2823     * allows it to avoid artifacts when switching in and out of that mode, at
2824     * the expense that some of its user interface may be covered by screen
2825     * decorations when they are shown.  You can perform layout of your inner
2826     * UI elements to account for the navigation system UI through the
2827     * {@link #fitSystemWindows(Rect)} method.
2828     */
2829    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2830
2831    /**
2832     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2833     * to be laid out as if it has requested
2834     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2835     * allows it to avoid artifacts when switching in and out of that mode, at
2836     * the expense that some of its user interface may be covered by screen
2837     * decorations when they are shown.  You can perform layout of your inner
2838     * UI elements to account for non-fullscreen system UI through the
2839     * {@link #fitSystemWindows(Rect)} method.
2840     */
2841    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2842
2843    /**
2844     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2845     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2846     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2847     * user interaction.
2848     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2849     * has an effect when used in combination with that flag.</p>
2850     */
2851    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2852
2853    /**
2854     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2855     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2856     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2857     * experience while also hiding the system bars.  If this flag is not set,
2858     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2859     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2860     * if the user swipes from the top of the screen.
2861     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2862     * system gestures, such as swiping from the top of the screen.  These transient system bars
2863     * will overlay app’s content, may have some degree of transparency, and will automatically
2864     * hide after a short timeout.
2865     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2866     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2867     * with one or both of those flags.</p>
2868     */
2869    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2870
2871    /**
2872     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2873     * is compatible with light status bar backgrounds.
2874     *
2875     * <p>For this to take effect, the window must request
2876     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2877     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2878     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2879     *         FLAG_TRANSLUCENT_STATUS}.
2880     *
2881     * @see android.R.attr#windowLightStatusBar
2882     */
2883    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2884
2885    /**
2886     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2887     */
2888    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2889
2890    /**
2891     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2892     */
2893    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2894
2895    /**
2896     * @hide
2897     *
2898     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2899     * out of the public fields to keep the undefined bits out of the developer's way.
2900     *
2901     * Flag to make the status bar not expandable.  Unless you also
2902     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2903     */
2904    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2905
2906    /**
2907     * @hide
2908     *
2909     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2910     * out of the public fields to keep the undefined bits out of the developer's way.
2911     *
2912     * Flag to hide notification icons and scrolling ticker text.
2913     */
2914    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2915
2916    /**
2917     * @hide
2918     *
2919     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2920     * out of the public fields to keep the undefined bits out of the developer's way.
2921     *
2922     * Flag to disable incoming notification alerts.  This will not block
2923     * icons, but it will block sound, vibrating and other visual or aural notifications.
2924     */
2925    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2926
2927    /**
2928     * @hide
2929     *
2930     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2931     * out of the public fields to keep the undefined bits out of the developer's way.
2932     *
2933     * Flag to hide only the scrolling ticker.  Note that
2934     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2935     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2936     */
2937    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2938
2939    /**
2940     * @hide
2941     *
2942     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2943     * out of the public fields to keep the undefined bits out of the developer's way.
2944     *
2945     * Flag to hide the center system info area.
2946     */
2947    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2948
2949    /**
2950     * @hide
2951     *
2952     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2953     * out of the public fields to keep the undefined bits out of the developer's way.
2954     *
2955     * Flag to hide only the home button.  Don't use this
2956     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2957     */
2958    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2959
2960    /**
2961     * @hide
2962     *
2963     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2964     * out of the public fields to keep the undefined bits out of the developer's way.
2965     *
2966     * Flag to hide only the back button. Don't use this
2967     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2968     */
2969    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2970
2971    /**
2972     * @hide
2973     *
2974     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2975     * out of the public fields to keep the undefined bits out of the developer's way.
2976     *
2977     * Flag to hide only the clock.  You might use this if your activity has
2978     * its own clock making the status bar's clock redundant.
2979     */
2980    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2981
2982    /**
2983     * @hide
2984     *
2985     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2986     * out of the public fields to keep the undefined bits out of the developer's way.
2987     *
2988     * Flag to hide only the recent apps button. Don't use this
2989     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2990     */
2991    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2992
2993    /**
2994     * @hide
2995     *
2996     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2997     * out of the public fields to keep the undefined bits out of the developer's way.
2998     *
2999     * Flag to disable the global search gesture. Don't use this
3000     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3001     */
3002    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3003
3004    /**
3005     * @hide
3006     *
3007     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3008     * out of the public fields to keep the undefined bits out of the developer's way.
3009     *
3010     * Flag to specify that the status bar is displayed in transient mode.
3011     */
3012    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3013
3014    /**
3015     * @hide
3016     *
3017     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3018     * out of the public fields to keep the undefined bits out of the developer's way.
3019     *
3020     * Flag to specify that the navigation bar is displayed in transient mode.
3021     */
3022    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3023
3024    /**
3025     * @hide
3026     *
3027     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3028     * out of the public fields to keep the undefined bits out of the developer's way.
3029     *
3030     * Flag to specify that the hidden status bar would like to be shown.
3031     */
3032    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3033
3034    /**
3035     * @hide
3036     *
3037     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3038     * out of the public fields to keep the undefined bits out of the developer's way.
3039     *
3040     * Flag to specify that the hidden navigation bar would like to be shown.
3041     */
3042    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3043
3044    /**
3045     * @hide
3046     *
3047     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3048     * out of the public fields to keep the undefined bits out of the developer's way.
3049     *
3050     * Flag to specify that the status bar is displayed in translucent mode.
3051     */
3052    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3053
3054    /**
3055     * @hide
3056     *
3057     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3058     * out of the public fields to keep the undefined bits out of the developer's way.
3059     *
3060     * Flag to specify that the navigation bar is displayed in translucent mode.
3061     */
3062    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3063
3064    /**
3065     * @hide
3066     *
3067     * Whether Recents is visible or not.
3068     */
3069    public static final int RECENT_APPS_VISIBLE = 0x00004000;
3070
3071    /**
3072     * @hide
3073     *
3074     * Makes navigation bar transparent (but not the status bar).
3075     */
3076    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3077
3078    /**
3079     * @hide
3080     *
3081     * Makes status bar transparent (but not the navigation bar).
3082     */
3083    public static final int STATUS_BAR_TRANSPARENT = 0x0000008;
3084
3085    /**
3086     * @hide
3087     *
3088     * Makes both status bar and navigation bar transparent.
3089     */
3090    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3091            | STATUS_BAR_TRANSPARENT;
3092
3093    /**
3094     * @hide
3095     */
3096    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3097
3098    /**
3099     * These are the system UI flags that can be cleared by events outside
3100     * of an application.  Currently this is just the ability to tap on the
3101     * screen while hiding the navigation bar to have it return.
3102     * @hide
3103     */
3104    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3105            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3106            | SYSTEM_UI_FLAG_FULLSCREEN;
3107
3108    /**
3109     * Flags that can impact the layout in relation to system UI.
3110     */
3111    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3112            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3113            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3114
3115    /** @hide */
3116    @IntDef(flag = true,
3117            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3118    @Retention(RetentionPolicy.SOURCE)
3119    public @interface FindViewFlags {}
3120
3121    /**
3122     * Find views that render the specified text.
3123     *
3124     * @see #findViewsWithText(ArrayList, CharSequence, int)
3125     */
3126    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3127
3128    /**
3129     * Find find views that contain the specified content description.
3130     *
3131     * @see #findViewsWithText(ArrayList, CharSequence, int)
3132     */
3133    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3134
3135    /**
3136     * Find views that contain {@link AccessibilityNodeProvider}. Such
3137     * a View is a root of virtual view hierarchy and may contain the searched
3138     * text. If this flag is set Views with providers are automatically
3139     * added and it is a responsibility of the client to call the APIs of
3140     * the provider to determine whether the virtual tree rooted at this View
3141     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3142     * representing the virtual views with this text.
3143     *
3144     * @see #findViewsWithText(ArrayList, CharSequence, int)
3145     *
3146     * @hide
3147     */
3148    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3149
3150    /**
3151     * The undefined cursor position.
3152     *
3153     * @hide
3154     */
3155    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3156
3157    /**
3158     * Indicates that the screen has changed state and is now off.
3159     *
3160     * @see #onScreenStateChanged(int)
3161     */
3162    public static final int SCREEN_STATE_OFF = 0x0;
3163
3164    /**
3165     * Indicates that the screen has changed state and is now on.
3166     *
3167     * @see #onScreenStateChanged(int)
3168     */
3169    public static final int SCREEN_STATE_ON = 0x1;
3170
3171    /**
3172     * Indicates no axis of view scrolling.
3173     */
3174    public static final int SCROLL_AXIS_NONE = 0;
3175
3176    /**
3177     * Indicates scrolling along the horizontal axis.
3178     */
3179    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3180
3181    /**
3182     * Indicates scrolling along the vertical axis.
3183     */
3184    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3185
3186    /**
3187     * Controls the over-scroll mode for this view.
3188     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3189     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3190     * and {@link #OVER_SCROLL_NEVER}.
3191     */
3192    private int mOverScrollMode;
3193
3194    /**
3195     * The parent this view is attached to.
3196     * {@hide}
3197     *
3198     * @see #getParent()
3199     */
3200    protected ViewParent mParent;
3201
3202    /**
3203     * {@hide}
3204     */
3205    AttachInfo mAttachInfo;
3206
3207    /**
3208     * {@hide}
3209     */
3210    @ViewDebug.ExportedProperty(flagMapping = {
3211        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3212                name = "FORCE_LAYOUT"),
3213        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3214                name = "LAYOUT_REQUIRED"),
3215        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3216            name = "DRAWING_CACHE_INVALID", outputIf = false),
3217        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3218        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3219        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3220        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3221    }, formatToHexString = true)
3222    int mPrivateFlags;
3223    int mPrivateFlags2;
3224    int mPrivateFlags3;
3225
3226    /**
3227     * This view's request for the visibility of the status bar.
3228     * @hide
3229     */
3230    @ViewDebug.ExportedProperty(flagMapping = {
3231        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3232                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3233                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3234        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3235                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3236                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3237        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3238                                equals = SYSTEM_UI_FLAG_VISIBLE,
3239                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3240    }, formatToHexString = true)
3241    int mSystemUiVisibility;
3242
3243    /**
3244     * Reference count for transient state.
3245     * @see #setHasTransientState(boolean)
3246     */
3247    int mTransientStateCount = 0;
3248
3249    /**
3250     * Count of how many windows this view has been attached to.
3251     */
3252    int mWindowAttachCount;
3253
3254    /**
3255     * The layout parameters associated with this view and used by the parent
3256     * {@link android.view.ViewGroup} to determine how this view should be
3257     * laid out.
3258     * {@hide}
3259     */
3260    protected ViewGroup.LayoutParams mLayoutParams;
3261
3262    /**
3263     * The view flags hold various views states.
3264     * {@hide}
3265     */
3266    @ViewDebug.ExportedProperty(formatToHexString = true)
3267    int mViewFlags;
3268
3269    static class TransformationInfo {
3270        /**
3271         * The transform matrix for the View. This transform is calculated internally
3272         * based on the translation, rotation, and scale properties.
3273         *
3274         * Do *not* use this variable directly; instead call getMatrix(), which will
3275         * load the value from the View's RenderNode.
3276         */
3277        private final Matrix mMatrix = new Matrix();
3278
3279        /**
3280         * The inverse transform matrix for the View. This transform is calculated
3281         * internally based on the translation, rotation, and scale properties.
3282         *
3283         * Do *not* use this variable directly; instead call getInverseMatrix(),
3284         * which will load the value from the View's RenderNode.
3285         */
3286        private Matrix mInverseMatrix;
3287
3288        /**
3289         * The opacity of the View. This is a value from 0 to 1, where 0 means
3290         * completely transparent and 1 means completely opaque.
3291         */
3292        @ViewDebug.ExportedProperty
3293        float mAlpha = 1f;
3294
3295        /**
3296         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3297         * property only used by transitions, which is composited with the other alpha
3298         * values to calculate the final visual alpha value.
3299         */
3300        float mTransitionAlpha = 1f;
3301    }
3302
3303    TransformationInfo mTransformationInfo;
3304
3305    /**
3306     * Current clip bounds. to which all drawing of this view are constrained.
3307     */
3308    Rect mClipBounds = null;
3309
3310    private boolean mLastIsOpaque;
3311
3312    /**
3313     * The distance in pixels from the left edge of this view's parent
3314     * to the left edge of this view.
3315     * {@hide}
3316     */
3317    @ViewDebug.ExportedProperty(category = "layout")
3318    protected int mLeft;
3319    /**
3320     * The distance in pixels from the left edge of this view's parent
3321     * to the right edge of this view.
3322     * {@hide}
3323     */
3324    @ViewDebug.ExportedProperty(category = "layout")
3325    protected int mRight;
3326    /**
3327     * The distance in pixels from the top edge of this view's parent
3328     * to the top edge of this view.
3329     * {@hide}
3330     */
3331    @ViewDebug.ExportedProperty(category = "layout")
3332    protected int mTop;
3333    /**
3334     * The distance in pixels from the top edge of this view's parent
3335     * to the bottom edge of this view.
3336     * {@hide}
3337     */
3338    @ViewDebug.ExportedProperty(category = "layout")
3339    protected int mBottom;
3340
3341    /**
3342     * The offset, in pixels, by which the content of this view is scrolled
3343     * horizontally.
3344     * {@hide}
3345     */
3346    @ViewDebug.ExportedProperty(category = "scrolling")
3347    protected int mScrollX;
3348    /**
3349     * The offset, in pixels, by which the content of this view is scrolled
3350     * vertically.
3351     * {@hide}
3352     */
3353    @ViewDebug.ExportedProperty(category = "scrolling")
3354    protected int mScrollY;
3355
3356    /**
3357     * The left padding in pixels, that is the distance in pixels between the
3358     * left edge of this view and the left edge of its content.
3359     * {@hide}
3360     */
3361    @ViewDebug.ExportedProperty(category = "padding")
3362    protected int mPaddingLeft = 0;
3363    /**
3364     * The right padding in pixels, that is the distance in pixels between the
3365     * right edge of this view and the right edge of its content.
3366     * {@hide}
3367     */
3368    @ViewDebug.ExportedProperty(category = "padding")
3369    protected int mPaddingRight = 0;
3370    /**
3371     * The top padding in pixels, that is the distance in pixels between the
3372     * top edge of this view and the top edge of its content.
3373     * {@hide}
3374     */
3375    @ViewDebug.ExportedProperty(category = "padding")
3376    protected int mPaddingTop;
3377    /**
3378     * The bottom padding in pixels, that is the distance in pixels between the
3379     * bottom edge of this view and the bottom edge of its content.
3380     * {@hide}
3381     */
3382    @ViewDebug.ExportedProperty(category = "padding")
3383    protected int mPaddingBottom;
3384
3385    /**
3386     * The layout insets in pixels, that is the distance in pixels between the
3387     * visible edges of this view its bounds.
3388     */
3389    private Insets mLayoutInsets;
3390
3391    /**
3392     * Briefly describes the view and is primarily used for accessibility support.
3393     */
3394    private CharSequence mContentDescription;
3395
3396    /**
3397     * Specifies the id of a view for which this view serves as a label for
3398     * accessibility purposes.
3399     */
3400    private int mLabelForId = View.NO_ID;
3401
3402    /**
3403     * Predicate for matching labeled view id with its label for
3404     * accessibility purposes.
3405     */
3406    private MatchLabelForPredicate mMatchLabelForPredicate;
3407
3408    /**
3409     * Specifies a view before which this one is visited in accessibility traversal.
3410     */
3411    private int mAccessibilityTraversalBeforeId = NO_ID;
3412
3413    /**
3414     * Specifies a view after which this one is visited in accessibility traversal.
3415     */
3416    private int mAccessibilityTraversalAfterId = NO_ID;
3417
3418    /**
3419     * Predicate for matching a view by its id.
3420     */
3421    private MatchIdPredicate mMatchIdPredicate;
3422
3423    /**
3424     * Cache the paddingRight set by the user to append to the scrollbar's size.
3425     *
3426     * @hide
3427     */
3428    @ViewDebug.ExportedProperty(category = "padding")
3429    protected int mUserPaddingRight;
3430
3431    /**
3432     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3433     *
3434     * @hide
3435     */
3436    @ViewDebug.ExportedProperty(category = "padding")
3437    protected int mUserPaddingBottom;
3438
3439    /**
3440     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3441     *
3442     * @hide
3443     */
3444    @ViewDebug.ExportedProperty(category = "padding")
3445    protected int mUserPaddingLeft;
3446
3447    /**
3448     * Cache the paddingStart set by the user to append to the scrollbar's size.
3449     *
3450     */
3451    @ViewDebug.ExportedProperty(category = "padding")
3452    int mUserPaddingStart;
3453
3454    /**
3455     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3456     *
3457     */
3458    @ViewDebug.ExportedProperty(category = "padding")
3459    int mUserPaddingEnd;
3460
3461    /**
3462     * Cache initial left padding.
3463     *
3464     * @hide
3465     */
3466    int mUserPaddingLeftInitial;
3467
3468    /**
3469     * Cache initial right padding.
3470     *
3471     * @hide
3472     */
3473    int mUserPaddingRightInitial;
3474
3475    /**
3476     * Default undefined padding
3477     */
3478    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3479
3480    /**
3481     * Cache if a left padding has been defined
3482     */
3483    private boolean mLeftPaddingDefined = false;
3484
3485    /**
3486     * Cache if a right padding has been defined
3487     */
3488    private boolean mRightPaddingDefined = false;
3489
3490    /**
3491     * @hide
3492     */
3493    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3494    /**
3495     * @hide
3496     */
3497    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3498
3499    private LongSparseLongArray mMeasureCache;
3500
3501    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3502    private Drawable mBackground;
3503    private TintInfo mBackgroundTint;
3504
3505    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3506    private ForegroundInfo mForegroundInfo;
3507
3508    private Drawable mScrollIndicatorDrawable;
3509
3510    /**
3511     * RenderNode used for backgrounds.
3512     * <p>
3513     * When non-null and valid, this is expected to contain an up-to-date copy
3514     * of the background drawable. It is cleared on temporary detach, and reset
3515     * on cleanup.
3516     */
3517    private RenderNode mBackgroundRenderNode;
3518
3519    private int mBackgroundResource;
3520    private boolean mBackgroundSizeChanged;
3521
3522    private String mTransitionName;
3523
3524    static class TintInfo {
3525        ColorStateList mTintList;
3526        PorterDuff.Mode mTintMode;
3527        boolean mHasTintMode;
3528        boolean mHasTintList;
3529    }
3530
3531    private static class ForegroundInfo {
3532        private Drawable mDrawable;
3533        private TintInfo mTintInfo;
3534        private int mGravity = Gravity.FILL;
3535        private boolean mInsidePadding = true;
3536        private boolean mBoundsChanged = true;
3537        private final Rect mSelfBounds = new Rect();
3538        private final Rect mOverlayBounds = new Rect();
3539    }
3540
3541    static class ListenerInfo {
3542        /**
3543         * Listener used to dispatch focus change events.
3544         * This field should be made private, so it is hidden from the SDK.
3545         * {@hide}
3546         */
3547        protected OnFocusChangeListener mOnFocusChangeListener;
3548
3549        /**
3550         * Listeners for layout change events.
3551         */
3552        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3553
3554        protected OnScrollChangeListener mOnScrollChangeListener;
3555
3556        /**
3557         * Listeners for attach events.
3558         */
3559        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3560
3561        /**
3562         * Listener used to dispatch click events.
3563         * This field should be made private, so it is hidden from the SDK.
3564         * {@hide}
3565         */
3566        public OnClickListener mOnClickListener;
3567
3568        /**
3569         * Listener used to dispatch long click events.
3570         * This field should be made private, so it is hidden from the SDK.
3571         * {@hide}
3572         */
3573        protected OnLongClickListener mOnLongClickListener;
3574
3575        /**
3576         * Listener used to dispatch context click events. This field should be made private, so it
3577         * is hidden from the SDK.
3578         * {@hide}
3579         */
3580        protected OnContextClickListener mOnContextClickListener;
3581
3582        /**
3583         * Listener used to build the context menu.
3584         * This field should be made private, so it is hidden from the SDK.
3585         * {@hide}
3586         */
3587        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3588
3589        private OnKeyListener mOnKeyListener;
3590
3591        private OnTouchListener mOnTouchListener;
3592
3593        private OnHoverListener mOnHoverListener;
3594
3595        private OnGenericMotionListener mOnGenericMotionListener;
3596
3597        private OnDragListener mOnDragListener;
3598
3599        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3600
3601        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3602    }
3603
3604    ListenerInfo mListenerInfo;
3605
3606    // Temporary values used to hold (x,y) coordinates when delegating from the
3607    // two-arg performLongClick() method to the legacy no-arg version.
3608    private float mLongClickX = Float.NaN;
3609    private float mLongClickY = Float.NaN;
3610
3611    /**
3612     * The application environment this view lives in.
3613     * This field should be made private, so it is hidden from the SDK.
3614     * {@hide}
3615     */
3616    @ViewDebug.ExportedProperty(deepExport = true)
3617    protected Context mContext;
3618
3619    private final Resources mResources;
3620
3621    private ScrollabilityCache mScrollCache;
3622
3623    private int[] mDrawableState = null;
3624
3625    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3626
3627    /**
3628     * Animator that automatically runs based on state changes.
3629     */
3630    private StateListAnimator mStateListAnimator;
3631
3632    /**
3633     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3634     * the user may specify which view to go to next.
3635     */
3636    private int mNextFocusLeftId = View.NO_ID;
3637
3638    /**
3639     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3640     * the user may specify which view to go to next.
3641     */
3642    private int mNextFocusRightId = View.NO_ID;
3643
3644    /**
3645     * When this view has focus and the next focus is {@link #FOCUS_UP},
3646     * the user may specify which view to go to next.
3647     */
3648    private int mNextFocusUpId = View.NO_ID;
3649
3650    /**
3651     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3652     * the user may specify which view to go to next.
3653     */
3654    private int mNextFocusDownId = View.NO_ID;
3655
3656    /**
3657     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3658     * the user may specify which view to go to next.
3659     */
3660    int mNextFocusForwardId = View.NO_ID;
3661
3662    private CheckForLongPress mPendingCheckForLongPress;
3663    private CheckForTap mPendingCheckForTap = null;
3664    private PerformClick mPerformClick;
3665    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3666
3667    private UnsetPressedState mUnsetPressedState;
3668
3669    /**
3670     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3671     * up event while a long press is invoked as soon as the long press duration is reached, so
3672     * a long press could be performed before the tap is checked, in which case the tap's action
3673     * should not be invoked.
3674     */
3675    private boolean mHasPerformedLongPress;
3676
3677    /**
3678     * Whether a context click button is currently pressed down. This is true when the stylus is
3679     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3680     * pressed. This is false once the button is released or if the stylus has been lifted.
3681     */
3682    private boolean mInContextButtonPress;
3683
3684    /**
3685     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3686     * true after a stylus button press has occured, when the next up event should not be recognized
3687     * as a tap.
3688     */
3689    private boolean mIgnoreNextUpEvent;
3690
3691    /**
3692     * The minimum height of the view. We'll try our best to have the height
3693     * of this view to at least this amount.
3694     */
3695    @ViewDebug.ExportedProperty(category = "measurement")
3696    private int mMinHeight;
3697
3698    /**
3699     * The minimum width of the view. We'll try our best to have the width
3700     * of this view to at least this amount.
3701     */
3702    @ViewDebug.ExportedProperty(category = "measurement")
3703    private int mMinWidth;
3704
3705    /**
3706     * The delegate to handle touch events that are physically in this view
3707     * but should be handled by another view.
3708     */
3709    private TouchDelegate mTouchDelegate = null;
3710
3711    /**
3712     * Solid color to use as a background when creating the drawing cache. Enables
3713     * the cache to use 16 bit bitmaps instead of 32 bit.
3714     */
3715    private int mDrawingCacheBackgroundColor = 0;
3716
3717    /**
3718     * Special tree observer used when mAttachInfo is null.
3719     */
3720    private ViewTreeObserver mFloatingTreeObserver;
3721
3722    /**
3723     * Cache the touch slop from the context that created the view.
3724     */
3725    private int mTouchSlop;
3726
3727    /**
3728     * Object that handles automatic animation of view properties.
3729     */
3730    private ViewPropertyAnimator mAnimator = null;
3731
3732    /**
3733     * List of registered FrameMetricsObservers.
3734     */
3735    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3736
3737    /**
3738     * Flag indicating that a drag can cross window boundaries.  When
3739     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3740     * with this flag set, all visible applications will be able to participate
3741     * in the drag operation and receive the dragged content.
3742     *
3743     * If this is the only flag set, then the drag recipient will only have access to text data
3744     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3745     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags.
3746     */
3747    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3748
3749    /**
3750     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3751     * request read access to the content URI(s) contained in the {@link ClipData} object.
3752     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3753     */
3754    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3755
3756    /**
3757     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3758     * request write access to the content URI(s) contained in the {@link ClipData} object.
3759     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3760     */
3761    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3762
3763    /**
3764     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3765     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3766     * reboots until explicitly revoked with
3767     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3768     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3769     */
3770    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3771            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3772
3773    /**
3774     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3775     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3776     * match against the original granted URI.
3777     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3778     */
3779    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3780            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3781
3782    /**
3783     * Flag indicating that the drag shadow will be opaque.  When
3784     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3785     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3786     */
3787    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3788
3789    /**
3790     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3791     */
3792    private float mVerticalScrollFactor;
3793
3794    /**
3795     * Position of the vertical scroll bar.
3796     */
3797    private int mVerticalScrollbarPosition;
3798
3799    /**
3800     * Position the scroll bar at the default position as determined by the system.
3801     */
3802    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3803
3804    /**
3805     * Position the scroll bar along the left edge.
3806     */
3807    public static final int SCROLLBAR_POSITION_LEFT = 1;
3808
3809    /**
3810     * Position the scroll bar along the right edge.
3811     */
3812    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3813
3814    /**
3815     * Indicates that the view does not have a layer.
3816     *
3817     * @see #getLayerType()
3818     * @see #setLayerType(int, android.graphics.Paint)
3819     * @see #LAYER_TYPE_SOFTWARE
3820     * @see #LAYER_TYPE_HARDWARE
3821     */
3822    public static final int LAYER_TYPE_NONE = 0;
3823
3824    /**
3825     * <p>Indicates that the view has a software layer. A software layer is backed
3826     * by a bitmap and causes the view to be rendered using Android's software
3827     * rendering pipeline, even if hardware acceleration is enabled.</p>
3828     *
3829     * <p>Software layers have various usages:</p>
3830     * <p>When the application is not using hardware acceleration, a software layer
3831     * is useful to apply a specific color filter and/or blending mode and/or
3832     * translucency to a view and all its children.</p>
3833     * <p>When the application is using hardware acceleration, a software layer
3834     * is useful to render drawing primitives not supported by the hardware
3835     * accelerated pipeline. It can also be used to cache a complex view tree
3836     * into a texture and reduce the complexity of drawing operations. For instance,
3837     * when animating a complex view tree with a translation, a software layer can
3838     * be used to render the view tree only once.</p>
3839     * <p>Software layers should be avoided when the affected view tree updates
3840     * often. Every update will require to re-render the software layer, which can
3841     * potentially be slow (particularly when hardware acceleration is turned on
3842     * since the layer will have to be uploaded into a hardware texture after every
3843     * update.)</p>
3844     *
3845     * @see #getLayerType()
3846     * @see #setLayerType(int, android.graphics.Paint)
3847     * @see #LAYER_TYPE_NONE
3848     * @see #LAYER_TYPE_HARDWARE
3849     */
3850    public static final int LAYER_TYPE_SOFTWARE = 1;
3851
3852    /**
3853     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3854     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3855     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3856     * rendering pipeline, but only if hardware acceleration is turned on for the
3857     * view hierarchy. When hardware acceleration is turned off, hardware layers
3858     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3859     *
3860     * <p>A hardware layer is useful to apply a specific color filter and/or
3861     * blending mode and/or translucency to a view and all its children.</p>
3862     * <p>A hardware layer can be used to cache a complex view tree into a
3863     * texture and reduce the complexity of drawing operations. For instance,
3864     * when animating a complex view tree with a translation, a hardware layer can
3865     * be used to render the view tree only once.</p>
3866     * <p>A hardware layer can also be used to increase the rendering quality when
3867     * rotation transformations are applied on a view. It can also be used to
3868     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3869     *
3870     * @see #getLayerType()
3871     * @see #setLayerType(int, android.graphics.Paint)
3872     * @see #LAYER_TYPE_NONE
3873     * @see #LAYER_TYPE_SOFTWARE
3874     */
3875    public static final int LAYER_TYPE_HARDWARE = 2;
3876
3877    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3878            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3879            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3880            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3881    })
3882    int mLayerType = LAYER_TYPE_NONE;
3883    Paint mLayerPaint;
3884
3885    /**
3886     * Set to true when drawing cache is enabled and cannot be created.
3887     *
3888     * @hide
3889     */
3890    public boolean mCachingFailed;
3891    private Bitmap mDrawingCache;
3892    private Bitmap mUnscaledDrawingCache;
3893
3894    /**
3895     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3896     * <p>
3897     * When non-null and valid, this is expected to contain an up-to-date copy
3898     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3899     * cleanup.
3900     */
3901    final RenderNode mRenderNode;
3902    private Runnable mRenderNodeDetachedCallback;
3903
3904    /**
3905     * Set to true when the view is sending hover accessibility events because it
3906     * is the innermost hovered view.
3907     */
3908    private boolean mSendingHoverAccessibilityEvents;
3909
3910    /**
3911     * Delegate for injecting accessibility functionality.
3912     */
3913    AccessibilityDelegate mAccessibilityDelegate;
3914
3915    /**
3916     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3917     * and add/remove objects to/from the overlay directly through the Overlay methods.
3918     */
3919    ViewOverlay mOverlay;
3920
3921    /**
3922     * The currently active parent view for receiving delegated nested scrolling events.
3923     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3924     * by {@link #stopNestedScroll()} at the same point where we clear
3925     * requestDisallowInterceptTouchEvent.
3926     */
3927    private ViewParent mNestedScrollingParent;
3928
3929    /**
3930     * Consistency verifier for debugging purposes.
3931     * @hide
3932     */
3933    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3934            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3935                    new InputEventConsistencyVerifier(this, 0) : null;
3936
3937    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3938
3939    private int[] mTempNestedScrollConsumed;
3940
3941    /**
3942     * An overlay is going to draw this View instead of being drawn as part of this
3943     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3944     * when this view is invalidated.
3945     */
3946    GhostView mGhostView;
3947
3948    /**
3949     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3950     * @hide
3951     */
3952    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3953    public String[] mAttributes;
3954
3955    /**
3956     * Maps a Resource id to its name.
3957     */
3958    private static SparseArray<String> mAttributeMap;
3959
3960    /**
3961     * Queue of pending runnables. Used to postpone calls to post() until this
3962     * view is attached and has a handler.
3963     */
3964    private HandlerActionQueue mRunQueue;
3965
3966    /**
3967     * The pointer icon when the mouse hovers on this view. The default is null.
3968     */
3969    private PointerIcon mPointerIcon;
3970
3971    /**
3972     * @hide
3973     */
3974    String mStartActivityRequestWho;
3975
3976    /**
3977     * Simple constructor to use when creating a view from code.
3978     *
3979     * @param context The Context the view is running in, through which it can
3980     *        access the current theme, resources, etc.
3981     */
3982    public View(Context context) {
3983        mContext = context;
3984        mResources = context != null ? context.getResources() : null;
3985        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3986        // Set some flags defaults
3987        mPrivateFlags2 =
3988                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3989                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3990                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3991                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3992                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3993                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3994        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3995        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3996        mUserPaddingStart = UNDEFINED_PADDING;
3997        mUserPaddingEnd = UNDEFINED_PADDING;
3998        mRenderNode = RenderNode.create(getClass().getName(), this);
3999
4000        if (!sCompatibilityDone && context != null) {
4001            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4002
4003            // Older apps may need this compatibility hack for measurement.
4004            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4005
4006            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4007            // of whether a layout was requested on that View.
4008            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4009
4010            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4011
4012            // In M and newer, our widgets can pass a "hint" value in the size
4013            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4014            // know what the expected parent size is going to be, so e.g. list items can size
4015            // themselves at 1/3 the size of their container. It breaks older apps though,
4016            // specifically apps that use some popular open source libraries.
4017            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4018
4019            // Old versions of the platform would give different results from
4020            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4021            // modes, so we always need to run an additional EXACTLY pass.
4022            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4023
4024            // Prior to N, layout params could change without requiring a
4025            // subsequent call to setLayoutParams() and they would usually
4026            // work. Partial layout breaks this assumption.
4027            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4028
4029            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4030            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4031            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4032
4033            sCompatibilityDone = true;
4034        }
4035    }
4036
4037    /**
4038     * Constructor that is called when inflating a view from XML. This is called
4039     * when a view is being constructed from an XML file, supplying attributes
4040     * that were specified in the XML file. This version uses a default style of
4041     * 0, so the only attribute values applied are those in the Context's Theme
4042     * and the given AttributeSet.
4043     *
4044     * <p>
4045     * The method onFinishInflate() will be called after all children have been
4046     * added.
4047     *
4048     * @param context The Context the view is running in, through which it can
4049     *        access the current theme, resources, etc.
4050     * @param attrs The attributes of the XML tag that is inflating the view.
4051     * @see #View(Context, AttributeSet, int)
4052     */
4053    public View(Context context, @Nullable AttributeSet attrs) {
4054        this(context, attrs, 0);
4055    }
4056
4057    /**
4058     * Perform inflation from XML and apply a class-specific base style from a
4059     * theme attribute. This constructor of View allows subclasses to use their
4060     * own base style when they are inflating. For example, a Button class's
4061     * constructor would call this version of the super class constructor and
4062     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4063     * allows the theme's button style to modify all of the base view attributes
4064     * (in particular its background) as well as the Button class's attributes.
4065     *
4066     * @param context The Context the view is running in, through which it can
4067     *        access the current theme, resources, etc.
4068     * @param attrs The attributes of the XML tag that is inflating the view.
4069     * @param defStyleAttr An attribute in the current theme that contains a
4070     *        reference to a style resource that supplies default values for
4071     *        the view. Can be 0 to not look for defaults.
4072     * @see #View(Context, AttributeSet)
4073     */
4074    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4075        this(context, attrs, defStyleAttr, 0);
4076    }
4077
4078    /**
4079     * Perform inflation from XML and apply a class-specific base style from a
4080     * theme attribute or style resource. This constructor of View allows
4081     * subclasses to use their own base style when they are inflating.
4082     * <p>
4083     * When determining the final value of a particular attribute, there are
4084     * four inputs that come into play:
4085     * <ol>
4086     * <li>Any attribute values in the given AttributeSet.
4087     * <li>The style resource specified in the AttributeSet (named "style").
4088     * <li>The default style specified by <var>defStyleAttr</var>.
4089     * <li>The default style specified by <var>defStyleRes</var>.
4090     * <li>The base values in this theme.
4091     * </ol>
4092     * <p>
4093     * Each of these inputs is considered in-order, with the first listed taking
4094     * precedence over the following ones. In other words, if in the
4095     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4096     * , then the button's text will <em>always</em> be black, regardless of
4097     * what is specified in any of the styles.
4098     *
4099     * @param context The Context the view is running in, through which it can
4100     *        access the current theme, resources, etc.
4101     * @param attrs The attributes of the XML tag that is inflating the view.
4102     * @param defStyleAttr An attribute in the current theme that contains a
4103     *        reference to a style resource that supplies default values for
4104     *        the view. Can be 0 to not look for defaults.
4105     * @param defStyleRes A resource identifier of a style resource that
4106     *        supplies default values for the view, used only if
4107     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4108     *        to not look for defaults.
4109     * @see #View(Context, AttributeSet, int)
4110     */
4111    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4112        this(context);
4113
4114        final TypedArray a = context.obtainStyledAttributes(
4115                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4116
4117        if (mDebugViewAttributes) {
4118            saveAttributeData(attrs, a);
4119        }
4120
4121        Drawable background = null;
4122
4123        int leftPadding = -1;
4124        int topPadding = -1;
4125        int rightPadding = -1;
4126        int bottomPadding = -1;
4127        int startPadding = UNDEFINED_PADDING;
4128        int endPadding = UNDEFINED_PADDING;
4129
4130        int padding = -1;
4131
4132        int viewFlagValues = 0;
4133        int viewFlagMasks = 0;
4134
4135        boolean setScrollContainer = false;
4136
4137        int x = 0;
4138        int y = 0;
4139
4140        float tx = 0;
4141        float ty = 0;
4142        float tz = 0;
4143        float elevation = 0;
4144        float rotation = 0;
4145        float rotationX = 0;
4146        float rotationY = 0;
4147        float sx = 1f;
4148        float sy = 1f;
4149        boolean transformSet = false;
4150
4151        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4152        int overScrollMode = mOverScrollMode;
4153        boolean initializeScrollbars = false;
4154        boolean initializeScrollIndicators = false;
4155
4156        boolean startPaddingDefined = false;
4157        boolean endPaddingDefined = false;
4158        boolean leftPaddingDefined = false;
4159        boolean rightPaddingDefined = false;
4160
4161        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4162
4163        final int N = a.getIndexCount();
4164        for (int i = 0; i < N; i++) {
4165            int attr = a.getIndex(i);
4166            switch (attr) {
4167                case com.android.internal.R.styleable.View_background:
4168                    background = a.getDrawable(attr);
4169                    break;
4170                case com.android.internal.R.styleable.View_padding:
4171                    padding = a.getDimensionPixelSize(attr, -1);
4172                    mUserPaddingLeftInitial = padding;
4173                    mUserPaddingRightInitial = padding;
4174                    leftPaddingDefined = true;
4175                    rightPaddingDefined = true;
4176                    break;
4177                 case com.android.internal.R.styleable.View_paddingLeft:
4178                    leftPadding = a.getDimensionPixelSize(attr, -1);
4179                    mUserPaddingLeftInitial = leftPadding;
4180                    leftPaddingDefined = true;
4181                    break;
4182                case com.android.internal.R.styleable.View_paddingTop:
4183                    topPadding = a.getDimensionPixelSize(attr, -1);
4184                    break;
4185                case com.android.internal.R.styleable.View_paddingRight:
4186                    rightPadding = a.getDimensionPixelSize(attr, -1);
4187                    mUserPaddingRightInitial = rightPadding;
4188                    rightPaddingDefined = true;
4189                    break;
4190                case com.android.internal.R.styleable.View_paddingBottom:
4191                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4192                    break;
4193                case com.android.internal.R.styleable.View_paddingStart:
4194                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4195                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4196                    break;
4197                case com.android.internal.R.styleable.View_paddingEnd:
4198                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4199                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4200                    break;
4201                case com.android.internal.R.styleable.View_scrollX:
4202                    x = a.getDimensionPixelOffset(attr, 0);
4203                    break;
4204                case com.android.internal.R.styleable.View_scrollY:
4205                    y = a.getDimensionPixelOffset(attr, 0);
4206                    break;
4207                case com.android.internal.R.styleable.View_alpha:
4208                    setAlpha(a.getFloat(attr, 1f));
4209                    break;
4210                case com.android.internal.R.styleable.View_transformPivotX:
4211                    setPivotX(a.getDimensionPixelOffset(attr, 0));
4212                    break;
4213                case com.android.internal.R.styleable.View_transformPivotY:
4214                    setPivotY(a.getDimensionPixelOffset(attr, 0));
4215                    break;
4216                case com.android.internal.R.styleable.View_translationX:
4217                    tx = a.getDimensionPixelOffset(attr, 0);
4218                    transformSet = true;
4219                    break;
4220                case com.android.internal.R.styleable.View_translationY:
4221                    ty = a.getDimensionPixelOffset(attr, 0);
4222                    transformSet = true;
4223                    break;
4224                case com.android.internal.R.styleable.View_translationZ:
4225                    tz = a.getDimensionPixelOffset(attr, 0);
4226                    transformSet = true;
4227                    break;
4228                case com.android.internal.R.styleable.View_elevation:
4229                    elevation = a.getDimensionPixelOffset(attr, 0);
4230                    transformSet = true;
4231                    break;
4232                case com.android.internal.R.styleable.View_rotation:
4233                    rotation = a.getFloat(attr, 0);
4234                    transformSet = true;
4235                    break;
4236                case com.android.internal.R.styleable.View_rotationX:
4237                    rotationX = a.getFloat(attr, 0);
4238                    transformSet = true;
4239                    break;
4240                case com.android.internal.R.styleable.View_rotationY:
4241                    rotationY = a.getFloat(attr, 0);
4242                    transformSet = true;
4243                    break;
4244                case com.android.internal.R.styleable.View_scaleX:
4245                    sx = a.getFloat(attr, 1f);
4246                    transformSet = true;
4247                    break;
4248                case com.android.internal.R.styleable.View_scaleY:
4249                    sy = a.getFloat(attr, 1f);
4250                    transformSet = true;
4251                    break;
4252                case com.android.internal.R.styleable.View_id:
4253                    mID = a.getResourceId(attr, NO_ID);
4254                    break;
4255                case com.android.internal.R.styleable.View_tag:
4256                    mTag = a.getText(attr);
4257                    break;
4258                case com.android.internal.R.styleable.View_fitsSystemWindows:
4259                    if (a.getBoolean(attr, false)) {
4260                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4261                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4262                    }
4263                    break;
4264                case com.android.internal.R.styleable.View_focusable:
4265                    if (a.getBoolean(attr, false)) {
4266                        viewFlagValues |= FOCUSABLE;
4267                        viewFlagMasks |= FOCUSABLE_MASK;
4268                    }
4269                    break;
4270                case com.android.internal.R.styleable.View_focusableInTouchMode:
4271                    if (a.getBoolean(attr, false)) {
4272                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4273                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4274                    }
4275                    break;
4276                case com.android.internal.R.styleable.View_clickable:
4277                    if (a.getBoolean(attr, false)) {
4278                        viewFlagValues |= CLICKABLE;
4279                        viewFlagMasks |= CLICKABLE;
4280                    }
4281                    break;
4282                case com.android.internal.R.styleable.View_longClickable:
4283                    if (a.getBoolean(attr, false)) {
4284                        viewFlagValues |= LONG_CLICKABLE;
4285                        viewFlagMasks |= LONG_CLICKABLE;
4286                    }
4287                    break;
4288                case com.android.internal.R.styleable.View_contextClickable:
4289                    if (a.getBoolean(attr, false)) {
4290                        viewFlagValues |= CONTEXT_CLICKABLE;
4291                        viewFlagMasks |= CONTEXT_CLICKABLE;
4292                    }
4293                    break;
4294                case com.android.internal.R.styleable.View_saveEnabled:
4295                    if (!a.getBoolean(attr, true)) {
4296                        viewFlagValues |= SAVE_DISABLED;
4297                        viewFlagMasks |= SAVE_DISABLED_MASK;
4298                    }
4299                    break;
4300                case com.android.internal.R.styleable.View_duplicateParentState:
4301                    if (a.getBoolean(attr, false)) {
4302                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4303                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4304                    }
4305                    break;
4306                case com.android.internal.R.styleable.View_visibility:
4307                    final int visibility = a.getInt(attr, 0);
4308                    if (visibility != 0) {
4309                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4310                        viewFlagMasks |= VISIBILITY_MASK;
4311                    }
4312                    break;
4313                case com.android.internal.R.styleable.View_layoutDirection:
4314                    // Clear any layout direction flags (included resolved bits) already set
4315                    mPrivateFlags2 &=
4316                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4317                    // Set the layout direction flags depending on the value of the attribute
4318                    final int layoutDirection = a.getInt(attr, -1);
4319                    final int value = (layoutDirection != -1) ?
4320                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4321                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4322                    break;
4323                case com.android.internal.R.styleable.View_drawingCacheQuality:
4324                    final int cacheQuality = a.getInt(attr, 0);
4325                    if (cacheQuality != 0) {
4326                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4327                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4328                    }
4329                    break;
4330                case com.android.internal.R.styleable.View_contentDescription:
4331                    setContentDescription(a.getString(attr));
4332                    break;
4333                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4334                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4335                    break;
4336                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4337                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4338                    break;
4339                case com.android.internal.R.styleable.View_labelFor:
4340                    setLabelFor(a.getResourceId(attr, NO_ID));
4341                    break;
4342                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4343                    if (!a.getBoolean(attr, true)) {
4344                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4345                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4346                    }
4347                    break;
4348                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4349                    if (!a.getBoolean(attr, true)) {
4350                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4351                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4352                    }
4353                    break;
4354                case R.styleable.View_scrollbars:
4355                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4356                    if (scrollbars != SCROLLBARS_NONE) {
4357                        viewFlagValues |= scrollbars;
4358                        viewFlagMasks |= SCROLLBARS_MASK;
4359                        initializeScrollbars = true;
4360                    }
4361                    break;
4362                //noinspection deprecation
4363                case R.styleable.View_fadingEdge:
4364                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4365                        // Ignore the attribute starting with ICS
4366                        break;
4367                    }
4368                    // With builds < ICS, fall through and apply fading edges
4369                case R.styleable.View_requiresFadingEdge:
4370                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4371                    if (fadingEdge != FADING_EDGE_NONE) {
4372                        viewFlagValues |= fadingEdge;
4373                        viewFlagMasks |= FADING_EDGE_MASK;
4374                        initializeFadingEdgeInternal(a);
4375                    }
4376                    break;
4377                case R.styleable.View_scrollbarStyle:
4378                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4379                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4380                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4381                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4382                    }
4383                    break;
4384                case R.styleable.View_isScrollContainer:
4385                    setScrollContainer = true;
4386                    if (a.getBoolean(attr, false)) {
4387                        setScrollContainer(true);
4388                    }
4389                    break;
4390                case com.android.internal.R.styleable.View_keepScreenOn:
4391                    if (a.getBoolean(attr, false)) {
4392                        viewFlagValues |= KEEP_SCREEN_ON;
4393                        viewFlagMasks |= KEEP_SCREEN_ON;
4394                    }
4395                    break;
4396                case R.styleable.View_filterTouchesWhenObscured:
4397                    if (a.getBoolean(attr, false)) {
4398                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4399                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4400                    }
4401                    break;
4402                case R.styleable.View_nextFocusLeft:
4403                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4404                    break;
4405                case R.styleable.View_nextFocusRight:
4406                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4407                    break;
4408                case R.styleable.View_nextFocusUp:
4409                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4410                    break;
4411                case R.styleable.View_nextFocusDown:
4412                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4413                    break;
4414                case R.styleable.View_nextFocusForward:
4415                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4416                    break;
4417                case R.styleable.View_minWidth:
4418                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4419                    break;
4420                case R.styleable.View_minHeight:
4421                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4422                    break;
4423                case R.styleable.View_onClick:
4424                    if (context.isRestricted()) {
4425                        throw new IllegalStateException("The android:onClick attribute cannot "
4426                                + "be used within a restricted context");
4427                    }
4428
4429                    final String handlerName = a.getString(attr);
4430                    if (handlerName != null) {
4431                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4432                    }
4433                    break;
4434                case R.styleable.View_overScrollMode:
4435                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4436                    break;
4437                case R.styleable.View_verticalScrollbarPosition:
4438                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4439                    break;
4440                case R.styleable.View_layerType:
4441                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4442                    break;
4443                case R.styleable.View_textDirection:
4444                    // Clear any text direction flag already set
4445                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4446                    // Set the text direction flags depending on the value of the attribute
4447                    final int textDirection = a.getInt(attr, -1);
4448                    if (textDirection != -1) {
4449                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4450                    }
4451                    break;
4452                case R.styleable.View_textAlignment:
4453                    // Clear any text alignment flag already set
4454                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4455                    // Set the text alignment flag depending on the value of the attribute
4456                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4457                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4458                    break;
4459                case R.styleable.View_importantForAccessibility:
4460                    setImportantForAccessibility(a.getInt(attr,
4461                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4462                    break;
4463                case R.styleable.View_accessibilityLiveRegion:
4464                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4465                    break;
4466                case R.styleable.View_transitionName:
4467                    setTransitionName(a.getString(attr));
4468                    break;
4469                case R.styleable.View_nestedScrollingEnabled:
4470                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4471                    break;
4472                case R.styleable.View_stateListAnimator:
4473                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4474                            a.getResourceId(attr, 0)));
4475                    break;
4476                case R.styleable.View_backgroundTint:
4477                    // This will get applied later during setBackground().
4478                    if (mBackgroundTint == null) {
4479                        mBackgroundTint = new TintInfo();
4480                    }
4481                    mBackgroundTint.mTintList = a.getColorStateList(
4482                            R.styleable.View_backgroundTint);
4483                    mBackgroundTint.mHasTintList = true;
4484                    break;
4485                case R.styleable.View_backgroundTintMode:
4486                    // This will get applied later during setBackground().
4487                    if (mBackgroundTint == null) {
4488                        mBackgroundTint = new TintInfo();
4489                    }
4490                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4491                            R.styleable.View_backgroundTintMode, -1), null);
4492                    mBackgroundTint.mHasTintMode = true;
4493                    break;
4494                case R.styleable.View_outlineProvider:
4495                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4496                            PROVIDER_BACKGROUND));
4497                    break;
4498                case R.styleable.View_foreground:
4499                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4500                        setForeground(a.getDrawable(attr));
4501                    }
4502                    break;
4503                case R.styleable.View_foregroundGravity:
4504                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4505                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4506                    }
4507                    break;
4508                case R.styleable.View_foregroundTintMode:
4509                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4510                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4511                    }
4512                    break;
4513                case R.styleable.View_foregroundTint:
4514                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4515                        setForegroundTintList(a.getColorStateList(attr));
4516                    }
4517                    break;
4518                case R.styleable.View_foregroundInsidePadding:
4519                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4520                        if (mForegroundInfo == null) {
4521                            mForegroundInfo = new ForegroundInfo();
4522                        }
4523                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4524                                mForegroundInfo.mInsidePadding);
4525                    }
4526                    break;
4527                case R.styleable.View_scrollIndicators:
4528                    final int scrollIndicators =
4529                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4530                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4531                    if (scrollIndicators != 0) {
4532                        mPrivateFlags3 |= scrollIndicators;
4533                        initializeScrollIndicators = true;
4534                    }
4535                    break;
4536                case R.styleable.View_pointerShape:
4537                    final int resourceId = a.getResourceId(attr, 0);
4538                    if (resourceId != 0) {
4539                        setPointerIcon(PointerIcon.loadCustomIcon(
4540                                context.getResources(), resourceId));
4541                    } else {
4542                        final int pointerShape = a.getInt(attr, PointerIcon.STYLE_NOT_SPECIFIED);
4543                        if (pointerShape != PointerIcon.STYLE_NOT_SPECIFIED) {
4544                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerShape));
4545                        }
4546                    }
4547                    break;
4548                case R.styleable.View_forceHasOverlappingRendering:
4549                    if (a.peekValue(attr) != null) {
4550                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4551                    }
4552                    break;
4553
4554            }
4555        }
4556
4557        setOverScrollMode(overScrollMode);
4558
4559        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4560        // the resolved layout direction). Those cached values will be used later during padding
4561        // resolution.
4562        mUserPaddingStart = startPadding;
4563        mUserPaddingEnd = endPadding;
4564
4565        if (background != null) {
4566            setBackground(background);
4567        }
4568
4569        // setBackground above will record that padding is currently provided by the background.
4570        // If we have padding specified via xml, record that here instead and use it.
4571        mLeftPaddingDefined = leftPaddingDefined;
4572        mRightPaddingDefined = rightPaddingDefined;
4573
4574        if (padding >= 0) {
4575            leftPadding = padding;
4576            topPadding = padding;
4577            rightPadding = padding;
4578            bottomPadding = padding;
4579            mUserPaddingLeftInitial = padding;
4580            mUserPaddingRightInitial = padding;
4581        }
4582
4583        if (isRtlCompatibilityMode()) {
4584            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4585            // left / right padding are used if defined (meaning here nothing to do). If they are not
4586            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4587            // start / end and resolve them as left / right (layout direction is not taken into account).
4588            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4589            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4590            // defined.
4591            if (!mLeftPaddingDefined && startPaddingDefined) {
4592                leftPadding = startPadding;
4593            }
4594            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4595            if (!mRightPaddingDefined && endPaddingDefined) {
4596                rightPadding = endPadding;
4597            }
4598            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4599        } else {
4600            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4601            // values defined. Otherwise, left /right values are used.
4602            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4603            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4604            // defined.
4605            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4606
4607            if (mLeftPaddingDefined && !hasRelativePadding) {
4608                mUserPaddingLeftInitial = leftPadding;
4609            }
4610            if (mRightPaddingDefined && !hasRelativePadding) {
4611                mUserPaddingRightInitial = rightPadding;
4612            }
4613        }
4614
4615        internalSetPadding(
4616                mUserPaddingLeftInitial,
4617                topPadding >= 0 ? topPadding : mPaddingTop,
4618                mUserPaddingRightInitial,
4619                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4620
4621        if (viewFlagMasks != 0) {
4622            setFlags(viewFlagValues, viewFlagMasks);
4623        }
4624
4625        if (initializeScrollbars) {
4626            initializeScrollbarsInternal(a);
4627        }
4628
4629        if (initializeScrollIndicators) {
4630            initializeScrollIndicatorsInternal();
4631        }
4632
4633        a.recycle();
4634
4635        // Needs to be called after mViewFlags is set
4636        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4637            recomputePadding();
4638        }
4639
4640        if (x != 0 || y != 0) {
4641            scrollTo(x, y);
4642        }
4643
4644        if (transformSet) {
4645            setTranslationX(tx);
4646            setTranslationY(ty);
4647            setTranslationZ(tz);
4648            setElevation(elevation);
4649            setRotation(rotation);
4650            setRotationX(rotationX);
4651            setRotationY(rotationY);
4652            setScaleX(sx);
4653            setScaleY(sy);
4654        }
4655
4656        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4657            setScrollContainer(true);
4658        }
4659
4660        computeOpaqueFlags();
4661    }
4662
4663    /**
4664     * An implementation of OnClickListener that attempts to lazily load a
4665     * named click handling method from a parent or ancestor context.
4666     */
4667    private static class DeclaredOnClickListener implements OnClickListener {
4668        private final View mHostView;
4669        private final String mMethodName;
4670
4671        private Method mResolvedMethod;
4672        private Context mResolvedContext;
4673
4674        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4675            mHostView = hostView;
4676            mMethodName = methodName;
4677        }
4678
4679        @Override
4680        public void onClick(@NonNull View v) {
4681            if (mResolvedMethod == null) {
4682                resolveMethod(mHostView.getContext(), mMethodName);
4683            }
4684
4685            try {
4686                mResolvedMethod.invoke(mResolvedContext, v);
4687            } catch (IllegalAccessException e) {
4688                throw new IllegalStateException(
4689                        "Could not execute non-public method for android:onClick", e);
4690            } catch (InvocationTargetException e) {
4691                throw new IllegalStateException(
4692                        "Could not execute method for android:onClick", e);
4693            }
4694        }
4695
4696        @NonNull
4697        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4698            while (context != null) {
4699                try {
4700                    if (!context.isRestricted()) {
4701                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4702                        if (method != null) {
4703                            mResolvedMethod = method;
4704                            mResolvedContext = context;
4705                            return;
4706                        }
4707                    }
4708                } catch (NoSuchMethodException e) {
4709                    // Failed to find method, keep searching up the hierarchy.
4710                }
4711
4712                if (context instanceof ContextWrapper) {
4713                    context = ((ContextWrapper) context).getBaseContext();
4714                } else {
4715                    // Can't search up the hierarchy, null out and fail.
4716                    context = null;
4717                }
4718            }
4719
4720            final int id = mHostView.getId();
4721            final String idText = id == NO_ID ? "" : " with id '"
4722                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4723            throw new IllegalStateException("Could not find method " + mMethodName
4724                    + "(View) in a parent or ancestor Context for android:onClick "
4725                    + "attribute defined on view " + mHostView.getClass() + idText);
4726        }
4727    }
4728
4729    /**
4730     * Non-public constructor for use in testing
4731     */
4732    View() {
4733        mResources = null;
4734        mRenderNode = RenderNode.create(getClass().getName(), this);
4735    }
4736
4737    private static SparseArray<String> getAttributeMap() {
4738        if (mAttributeMap == null) {
4739            mAttributeMap = new SparseArray<>();
4740        }
4741        return mAttributeMap;
4742    }
4743
4744    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4745        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4746        final int indexCount = t.getIndexCount();
4747        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4748
4749        int i = 0;
4750
4751        // Store raw XML attributes.
4752        for (int j = 0; j < attrsCount; ++j) {
4753            attributes[i] = attrs.getAttributeName(j);
4754            attributes[i + 1] = attrs.getAttributeValue(j);
4755            i += 2;
4756        }
4757
4758        // Store resolved styleable attributes.
4759        final Resources res = t.getResources();
4760        final SparseArray<String> attributeMap = getAttributeMap();
4761        for (int j = 0; j < indexCount; ++j) {
4762            final int index = t.getIndex(j);
4763            if (!t.hasValueOrEmpty(index)) {
4764                // Value is undefined. Skip it.
4765                continue;
4766            }
4767
4768            final int resourceId = t.getResourceId(index, 0);
4769            if (resourceId == 0) {
4770                // Value is not a reference. Skip it.
4771                continue;
4772            }
4773
4774            String resourceName = attributeMap.get(resourceId);
4775            if (resourceName == null) {
4776                try {
4777                    resourceName = res.getResourceName(resourceId);
4778                } catch (Resources.NotFoundException e) {
4779                    resourceName = "0x" + Integer.toHexString(resourceId);
4780                }
4781                attributeMap.put(resourceId, resourceName);
4782            }
4783
4784            attributes[i] = resourceName;
4785            attributes[i + 1] = t.getString(index);
4786            i += 2;
4787        }
4788
4789        // Trim to fit contents.
4790        final String[] trimmed = new String[i];
4791        System.arraycopy(attributes, 0, trimmed, 0, i);
4792        mAttributes = trimmed;
4793    }
4794
4795    public String toString() {
4796        StringBuilder out = new StringBuilder(128);
4797        out.append(getClass().getName());
4798        out.append('{');
4799        out.append(Integer.toHexString(System.identityHashCode(this)));
4800        out.append(' ');
4801        switch (mViewFlags&VISIBILITY_MASK) {
4802            case VISIBLE: out.append('V'); break;
4803            case INVISIBLE: out.append('I'); break;
4804            case GONE: out.append('G'); break;
4805            default: out.append('.'); break;
4806        }
4807        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4808        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4809        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4810        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4811        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4812        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4813        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4814        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4815        out.append(' ');
4816        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4817        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4818        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4819        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4820            out.append('p');
4821        } else {
4822            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4823        }
4824        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4825        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4826        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4827        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4828        out.append(' ');
4829        out.append(mLeft);
4830        out.append(',');
4831        out.append(mTop);
4832        out.append('-');
4833        out.append(mRight);
4834        out.append(',');
4835        out.append(mBottom);
4836        final int id = getId();
4837        if (id != NO_ID) {
4838            out.append(" #");
4839            out.append(Integer.toHexString(id));
4840            final Resources r = mResources;
4841            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
4842                try {
4843                    String pkgname;
4844                    switch (id&0xff000000) {
4845                        case 0x7f000000:
4846                            pkgname="app";
4847                            break;
4848                        case 0x01000000:
4849                            pkgname="android";
4850                            break;
4851                        default:
4852                            pkgname = r.getResourcePackageName(id);
4853                            break;
4854                    }
4855                    String typename = r.getResourceTypeName(id);
4856                    String entryname = r.getResourceEntryName(id);
4857                    out.append(" ");
4858                    out.append(pkgname);
4859                    out.append(":");
4860                    out.append(typename);
4861                    out.append("/");
4862                    out.append(entryname);
4863                } catch (Resources.NotFoundException e) {
4864                }
4865            }
4866        }
4867        out.append("}");
4868        return out.toString();
4869    }
4870
4871    /**
4872     * <p>
4873     * Initializes the fading edges from a given set of styled attributes. This
4874     * method should be called by subclasses that need fading edges and when an
4875     * instance of these subclasses is created programmatically rather than
4876     * being inflated from XML. This method is automatically called when the XML
4877     * is inflated.
4878     * </p>
4879     *
4880     * @param a the styled attributes set to initialize the fading edges from
4881     *
4882     * @removed
4883     */
4884    protected void initializeFadingEdge(TypedArray a) {
4885        // This method probably shouldn't have been included in the SDK to begin with.
4886        // It relies on 'a' having been initialized using an attribute filter array that is
4887        // not publicly available to the SDK. The old method has been renamed
4888        // to initializeFadingEdgeInternal and hidden for framework use only;
4889        // this one initializes using defaults to make it safe to call for apps.
4890
4891        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4892
4893        initializeFadingEdgeInternal(arr);
4894
4895        arr.recycle();
4896    }
4897
4898    /**
4899     * <p>
4900     * Initializes the fading edges from a given set of styled attributes. This
4901     * method should be called by subclasses that need fading edges and when an
4902     * instance of these subclasses is created programmatically rather than
4903     * being inflated from XML. This method is automatically called when the XML
4904     * is inflated.
4905     * </p>
4906     *
4907     * @param a the styled attributes set to initialize the fading edges from
4908     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4909     */
4910    protected void initializeFadingEdgeInternal(TypedArray a) {
4911        initScrollCache();
4912
4913        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4914                R.styleable.View_fadingEdgeLength,
4915                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4916    }
4917
4918    /**
4919     * Returns the size of the vertical faded edges used to indicate that more
4920     * content in this view is visible.
4921     *
4922     * @return The size in pixels of the vertical faded edge or 0 if vertical
4923     *         faded edges are not enabled for this view.
4924     * @attr ref android.R.styleable#View_fadingEdgeLength
4925     */
4926    public int getVerticalFadingEdgeLength() {
4927        if (isVerticalFadingEdgeEnabled()) {
4928            ScrollabilityCache cache = mScrollCache;
4929            if (cache != null) {
4930                return cache.fadingEdgeLength;
4931            }
4932        }
4933        return 0;
4934    }
4935
4936    /**
4937     * Set the size of the faded edge used to indicate that more content in this
4938     * view is available.  Will not change whether the fading edge is enabled; use
4939     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4940     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4941     * for the vertical or horizontal fading edges.
4942     *
4943     * @param length The size in pixels of the faded edge used to indicate that more
4944     *        content in this view is visible.
4945     */
4946    public void setFadingEdgeLength(int length) {
4947        initScrollCache();
4948        mScrollCache.fadingEdgeLength = length;
4949    }
4950
4951    /**
4952     * Returns the size of the horizontal faded edges used to indicate that more
4953     * content in this view is visible.
4954     *
4955     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4956     *         faded edges are not enabled for this view.
4957     * @attr ref android.R.styleable#View_fadingEdgeLength
4958     */
4959    public int getHorizontalFadingEdgeLength() {
4960        if (isHorizontalFadingEdgeEnabled()) {
4961            ScrollabilityCache cache = mScrollCache;
4962            if (cache != null) {
4963                return cache.fadingEdgeLength;
4964            }
4965        }
4966        return 0;
4967    }
4968
4969    /**
4970     * Returns the width of the vertical scrollbar.
4971     *
4972     * @return The width in pixels of the vertical scrollbar or 0 if there
4973     *         is no vertical scrollbar.
4974     */
4975    public int getVerticalScrollbarWidth() {
4976        ScrollabilityCache cache = mScrollCache;
4977        if (cache != null) {
4978            ScrollBarDrawable scrollBar = cache.scrollBar;
4979            if (scrollBar != null) {
4980                int size = scrollBar.getSize(true);
4981                if (size <= 0) {
4982                    size = cache.scrollBarSize;
4983                }
4984                return size;
4985            }
4986            return 0;
4987        }
4988        return 0;
4989    }
4990
4991    /**
4992     * Returns the height of the horizontal scrollbar.
4993     *
4994     * @return The height in pixels of the horizontal scrollbar or 0 if
4995     *         there is no horizontal scrollbar.
4996     */
4997    protected int getHorizontalScrollbarHeight() {
4998        ScrollabilityCache cache = mScrollCache;
4999        if (cache != null) {
5000            ScrollBarDrawable scrollBar = cache.scrollBar;
5001            if (scrollBar != null) {
5002                int size = scrollBar.getSize(false);
5003                if (size <= 0) {
5004                    size = cache.scrollBarSize;
5005                }
5006                return size;
5007            }
5008            return 0;
5009        }
5010        return 0;
5011    }
5012
5013    /**
5014     * <p>
5015     * Initializes the scrollbars from a given set of styled attributes. This
5016     * method should be called by subclasses that need scrollbars and when an
5017     * instance of these subclasses is created programmatically rather than
5018     * being inflated from XML. This method is automatically called when the XML
5019     * is inflated.
5020     * </p>
5021     *
5022     * @param a the styled attributes set to initialize the scrollbars from
5023     *
5024     * @removed
5025     */
5026    protected void initializeScrollbars(TypedArray a) {
5027        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5028        // using the View filter array which is not available to the SDK. As such, internal
5029        // framework usage now uses initializeScrollbarsInternal and we grab a default
5030        // TypedArray with the right filter instead here.
5031        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5032
5033        initializeScrollbarsInternal(arr);
5034
5035        // We ignored the method parameter. Recycle the one we actually did use.
5036        arr.recycle();
5037    }
5038
5039    /**
5040     * <p>
5041     * Initializes the scrollbars from a given set of styled attributes. This
5042     * method should be called by subclasses that need scrollbars and when an
5043     * instance of these subclasses is created programmatically rather than
5044     * being inflated from XML. This method is automatically called when the XML
5045     * is inflated.
5046     * </p>
5047     *
5048     * @param a the styled attributes set to initialize the scrollbars from
5049     * @hide
5050     */
5051    protected void initializeScrollbarsInternal(TypedArray a) {
5052        initScrollCache();
5053
5054        final ScrollabilityCache scrollabilityCache = mScrollCache;
5055
5056        if (scrollabilityCache.scrollBar == null) {
5057            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5058            scrollabilityCache.scrollBar.setState(getDrawableState());
5059            scrollabilityCache.scrollBar.setCallback(this);
5060        }
5061
5062        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5063
5064        if (!fadeScrollbars) {
5065            scrollabilityCache.state = ScrollabilityCache.ON;
5066        }
5067        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5068
5069
5070        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5071                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5072                        .getScrollBarFadeDuration());
5073        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5074                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5075                ViewConfiguration.getScrollDefaultDelay());
5076
5077
5078        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5079                com.android.internal.R.styleable.View_scrollbarSize,
5080                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5081
5082        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5083        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5084
5085        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5086        if (thumb != null) {
5087            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5088        }
5089
5090        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5091                false);
5092        if (alwaysDraw) {
5093            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5094        }
5095
5096        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5097        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5098
5099        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5100        if (thumb != null) {
5101            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5102        }
5103
5104        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5105                false);
5106        if (alwaysDraw) {
5107            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5108        }
5109
5110        // Apply layout direction to the new Drawables if needed
5111        final int layoutDirection = getLayoutDirection();
5112        if (track != null) {
5113            track.setLayoutDirection(layoutDirection);
5114        }
5115        if (thumb != null) {
5116            thumb.setLayoutDirection(layoutDirection);
5117        }
5118
5119        // Re-apply user/background padding so that scrollbar(s) get added
5120        resolvePadding();
5121    }
5122
5123    private void initializeScrollIndicatorsInternal() {
5124        // Some day maybe we'll break this into top/left/start/etc. and let the
5125        // client control it. Until then, you can have any scroll indicator you
5126        // want as long as it's a 1dp foreground-colored rectangle.
5127        if (mScrollIndicatorDrawable == null) {
5128            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5129        }
5130    }
5131
5132    /**
5133     * <p>
5134     * Initalizes the scrollability cache if necessary.
5135     * </p>
5136     */
5137    private void initScrollCache() {
5138        if (mScrollCache == null) {
5139            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5140        }
5141    }
5142
5143    private ScrollabilityCache getScrollCache() {
5144        initScrollCache();
5145        return mScrollCache;
5146    }
5147
5148    /**
5149     * Set the position of the vertical scroll bar. Should be one of
5150     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5151     * {@link #SCROLLBAR_POSITION_RIGHT}.
5152     *
5153     * @param position Where the vertical scroll bar should be positioned.
5154     */
5155    public void setVerticalScrollbarPosition(int position) {
5156        if (mVerticalScrollbarPosition != position) {
5157            mVerticalScrollbarPosition = position;
5158            computeOpaqueFlags();
5159            resolvePadding();
5160        }
5161    }
5162
5163    /**
5164     * @return The position where the vertical scroll bar will show, if applicable.
5165     * @see #setVerticalScrollbarPosition(int)
5166     */
5167    public int getVerticalScrollbarPosition() {
5168        return mVerticalScrollbarPosition;
5169    }
5170
5171    boolean isOnScrollbar(float x, float y) {
5172        if (mScrollCache == null) {
5173            return false;
5174        }
5175        x += getScrollX();
5176        y += getScrollY();
5177        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5178            final Rect bounds = mScrollCache.mScrollBarBounds;
5179            getVerticalScrollBarBounds(bounds);
5180            if (bounds.contains((int)x, (int)y)) {
5181                return true;
5182            }
5183        }
5184        if (isHorizontalScrollBarEnabled()) {
5185            final Rect bounds = mScrollCache.mScrollBarBounds;
5186            getHorizontalScrollBarBounds(bounds);
5187            if (bounds.contains((int)x, (int)y)) {
5188                return true;
5189            }
5190        }
5191        return false;
5192    }
5193
5194    boolean isOnScrollbarThumb(float x, float y) {
5195        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5196    }
5197
5198    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5199        if (mScrollCache == null) {
5200            return false;
5201        }
5202        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5203            x += getScrollX();
5204            y += getScrollY();
5205            final Rect bounds = mScrollCache.mScrollBarBounds;
5206            getVerticalScrollBarBounds(bounds);
5207            final int range = computeVerticalScrollRange();
5208            final int offset = computeVerticalScrollOffset();
5209            final int extent = computeVerticalScrollExtent();
5210            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5211                    extent, range);
5212            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5213                    extent, range, offset);
5214            final int thumbTop = bounds.top + thumbOffset;
5215            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5216                    && y <= thumbTop + thumbLength) {
5217                return true;
5218            }
5219        }
5220        return false;
5221    }
5222
5223    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5224        if (mScrollCache == null) {
5225            return false;
5226        }
5227        if (isHorizontalScrollBarEnabled()) {
5228            x += getScrollX();
5229            y += getScrollY();
5230            final Rect bounds = mScrollCache.mScrollBarBounds;
5231            getHorizontalScrollBarBounds(bounds);
5232            final int range = computeHorizontalScrollRange();
5233            final int offset = computeHorizontalScrollOffset();
5234            final int extent = computeHorizontalScrollExtent();
5235            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5236                    extent, range);
5237            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5238                    extent, range, offset);
5239            final int thumbLeft = bounds.left + thumbOffset;
5240            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5241                    && y <= bounds.bottom) {
5242                return true;
5243            }
5244        }
5245        return false;
5246    }
5247
5248    boolean isDraggingScrollBar() {
5249        return mScrollCache != null
5250                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5251    }
5252
5253    /**
5254     * Sets the state of all scroll indicators.
5255     * <p>
5256     * See {@link #setScrollIndicators(int, int)} for usage information.
5257     *
5258     * @param indicators a bitmask of indicators that should be enabled, or
5259     *                   {@code 0} to disable all indicators
5260     * @see #setScrollIndicators(int, int)
5261     * @see #getScrollIndicators()
5262     * @attr ref android.R.styleable#View_scrollIndicators
5263     */
5264    public void setScrollIndicators(@ScrollIndicators int indicators) {
5265        setScrollIndicators(indicators,
5266                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5267    }
5268
5269    /**
5270     * Sets the state of the scroll indicators specified by the mask. To change
5271     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5272     * <p>
5273     * When a scroll indicator is enabled, it will be displayed if the view
5274     * can scroll in the direction of the indicator.
5275     * <p>
5276     * Multiple indicator types may be enabled or disabled by passing the
5277     * logical OR of the desired types. If multiple types are specified, they
5278     * will all be set to the same enabled state.
5279     * <p>
5280     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5281     *
5282     * @param indicators the indicator direction, or the logical OR of multiple
5283     *             indicator directions. One or more of:
5284     *             <ul>
5285     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5286     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5287     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5288     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5289     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5290     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5291     *             </ul>
5292     * @see #setScrollIndicators(int)
5293     * @see #getScrollIndicators()
5294     * @attr ref android.R.styleable#View_scrollIndicators
5295     */
5296    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5297        // Shift and sanitize mask.
5298        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5299        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5300
5301        // Shift and mask indicators.
5302        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5303        indicators &= mask;
5304
5305        // Merge with non-masked flags.
5306        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5307
5308        if (mPrivateFlags3 != updatedFlags) {
5309            mPrivateFlags3 = updatedFlags;
5310
5311            if (indicators != 0) {
5312                initializeScrollIndicatorsInternal();
5313            }
5314            invalidate();
5315        }
5316    }
5317
5318    /**
5319     * Returns a bitmask representing the enabled scroll indicators.
5320     * <p>
5321     * For example, if the top and left scroll indicators are enabled and all
5322     * other indicators are disabled, the return value will be
5323     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5324     * <p>
5325     * To check whether the bottom scroll indicator is enabled, use the value
5326     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5327     *
5328     * @return a bitmask representing the enabled scroll indicators
5329     */
5330    @ScrollIndicators
5331    public int getScrollIndicators() {
5332        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5333                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5334    }
5335
5336    ListenerInfo getListenerInfo() {
5337        if (mListenerInfo != null) {
5338            return mListenerInfo;
5339        }
5340        mListenerInfo = new ListenerInfo();
5341        return mListenerInfo;
5342    }
5343
5344    /**
5345     * Register a callback to be invoked when the scroll X or Y positions of
5346     * this view change.
5347     * <p>
5348     * <b>Note:</b> Some views handle scrolling independently from View and may
5349     * have their own separate listeners for scroll-type events. For example,
5350     * {@link android.widget.ListView ListView} allows clients to register an
5351     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5352     * to listen for changes in list scroll position.
5353     *
5354     * @param l The listener to notify when the scroll X or Y position changes.
5355     * @see android.view.View#getScrollX()
5356     * @see android.view.View#getScrollY()
5357     */
5358    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5359        getListenerInfo().mOnScrollChangeListener = l;
5360    }
5361
5362    /**
5363     * Register a callback to be invoked when focus of this view changed.
5364     *
5365     * @param l The callback that will run.
5366     */
5367    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5368        getListenerInfo().mOnFocusChangeListener = l;
5369    }
5370
5371    /**
5372     * Add a listener that will be called when the bounds of the view change due to
5373     * layout processing.
5374     *
5375     * @param listener The listener that will be called when layout bounds change.
5376     */
5377    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5378        ListenerInfo li = getListenerInfo();
5379        if (li.mOnLayoutChangeListeners == null) {
5380            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5381        }
5382        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5383            li.mOnLayoutChangeListeners.add(listener);
5384        }
5385    }
5386
5387    /**
5388     * Remove a listener for layout changes.
5389     *
5390     * @param listener The listener for layout bounds change.
5391     */
5392    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5393        ListenerInfo li = mListenerInfo;
5394        if (li == null || li.mOnLayoutChangeListeners == null) {
5395            return;
5396        }
5397        li.mOnLayoutChangeListeners.remove(listener);
5398    }
5399
5400    /**
5401     * Add a listener for attach state changes.
5402     *
5403     * This listener will be called whenever this view is attached or detached
5404     * from a window. Remove the listener using
5405     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5406     *
5407     * @param listener Listener to attach
5408     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5409     */
5410    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5411        ListenerInfo li = getListenerInfo();
5412        if (li.mOnAttachStateChangeListeners == null) {
5413            li.mOnAttachStateChangeListeners
5414                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5415        }
5416        li.mOnAttachStateChangeListeners.add(listener);
5417    }
5418
5419    /**
5420     * Remove a listener for attach state changes. The listener will receive no further
5421     * notification of window attach/detach events.
5422     *
5423     * @param listener Listener to remove
5424     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5425     */
5426    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5427        ListenerInfo li = mListenerInfo;
5428        if (li == null || li.mOnAttachStateChangeListeners == null) {
5429            return;
5430        }
5431        li.mOnAttachStateChangeListeners.remove(listener);
5432    }
5433
5434    /**
5435     * Returns the focus-change callback registered for this view.
5436     *
5437     * @return The callback, or null if one is not registered.
5438     */
5439    public OnFocusChangeListener getOnFocusChangeListener() {
5440        ListenerInfo li = mListenerInfo;
5441        return li != null ? li.mOnFocusChangeListener : null;
5442    }
5443
5444    /**
5445     * Register a callback to be invoked when this view is clicked. If this view is not
5446     * clickable, it becomes clickable.
5447     *
5448     * @param l The callback that will run
5449     *
5450     * @see #setClickable(boolean)
5451     */
5452    public void setOnClickListener(@Nullable OnClickListener l) {
5453        if (!isClickable()) {
5454            setClickable(true);
5455        }
5456        getListenerInfo().mOnClickListener = l;
5457    }
5458
5459    /**
5460     * Return whether this view has an attached OnClickListener.  Returns
5461     * true if there is a listener, false if there is none.
5462     */
5463    public boolean hasOnClickListeners() {
5464        ListenerInfo li = mListenerInfo;
5465        return (li != null && li.mOnClickListener != null);
5466    }
5467
5468    /**
5469     * Register a callback to be invoked when this view is clicked and held. If this view is not
5470     * long clickable, it becomes long clickable.
5471     *
5472     * @param l The callback that will run
5473     *
5474     * @see #setLongClickable(boolean)
5475     */
5476    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5477        if (!isLongClickable()) {
5478            setLongClickable(true);
5479        }
5480        getListenerInfo().mOnLongClickListener = l;
5481    }
5482
5483    /**
5484     * Register a callback to be invoked when this view is context clicked. If the view is not
5485     * context clickable, it becomes context clickable.
5486     *
5487     * @param l The callback that will run
5488     * @see #setContextClickable(boolean)
5489     */
5490    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5491        if (!isContextClickable()) {
5492            setContextClickable(true);
5493        }
5494        getListenerInfo().mOnContextClickListener = l;
5495    }
5496
5497    /**
5498     * Register a callback to be invoked when the context menu for this view is
5499     * being built. If this view is not long clickable, it becomes long clickable.
5500     *
5501     * @param l The callback that will run
5502     *
5503     */
5504    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5505        if (!isLongClickable()) {
5506            setLongClickable(true);
5507        }
5508        getListenerInfo().mOnCreateContextMenuListener = l;
5509    }
5510
5511    /**
5512     * Set an observer to collect stats for each frame rendered for this view.
5513     *
5514     * @hide
5515     */
5516    public void addFrameMetricsListener(Window window, Window.FrameMetricsListener listener,
5517            Handler handler) {
5518        if (mAttachInfo != null) {
5519            if (mAttachInfo.mHardwareRenderer != null) {
5520                if (mFrameMetricsObservers == null) {
5521                    mFrameMetricsObservers = new ArrayList<>();
5522                }
5523
5524                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5525                        handler.getLooper(), listener);
5526                mFrameMetricsObservers.add(fmo);
5527                mAttachInfo.mHardwareRenderer.addFrameMetricsObserver(fmo);
5528            } else {
5529                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5530            }
5531        } else {
5532            if (mFrameMetricsObservers == null) {
5533                mFrameMetricsObservers = new ArrayList<>();
5534            }
5535
5536            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5537                    handler.getLooper(), listener);
5538            mFrameMetricsObservers.add(fmo);
5539        }
5540    }
5541
5542    /**
5543     * Remove observer configured to collect frame stats for this view.
5544     *
5545     * @hide
5546     */
5547    public void removeFrameMetricsListener(Window.FrameMetricsListener listener) {
5548        ThreadedRenderer renderer = getHardwareRenderer();
5549        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5550        if (fmo == null) {
5551            throw new IllegalArgumentException("attempt to remove FrameMetricsListener that was never added");
5552        }
5553
5554        if (mFrameMetricsObservers != null) {
5555            mFrameMetricsObservers.remove(fmo);
5556            if (renderer != null) {
5557                renderer.removeFrameMetricsObserver(fmo);
5558            }
5559        }
5560    }
5561
5562    private void registerPendingFrameMetricsObservers() {
5563        if (mFrameMetricsObservers != null) {
5564            ThreadedRenderer renderer = getHardwareRenderer();
5565            if (renderer != null) {
5566                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5567                    renderer.addFrameMetricsObserver(fmo);
5568                }
5569            } else {
5570                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5571            }
5572        }
5573    }
5574
5575    private FrameMetricsObserver findFrameMetricsObserver(Window.FrameMetricsListener listener) {
5576        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5577            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5578            if (observer.mListener == listener) {
5579                return observer;
5580            }
5581        }
5582
5583        return null;
5584    }
5585
5586    /**
5587     * Call this view's OnClickListener, if it is defined.  Performs all normal
5588     * actions associated with clicking: reporting accessibility event, playing
5589     * a sound, etc.
5590     *
5591     * @return True there was an assigned OnClickListener that was called, false
5592     *         otherwise is returned.
5593     */
5594    public boolean performClick() {
5595        final boolean result;
5596        final ListenerInfo li = mListenerInfo;
5597        if (li != null && li.mOnClickListener != null) {
5598            playSoundEffect(SoundEffectConstants.CLICK);
5599            li.mOnClickListener.onClick(this);
5600            result = true;
5601        } else {
5602            result = false;
5603        }
5604
5605        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5606        return result;
5607    }
5608
5609    /**
5610     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5611     * this only calls the listener, and does not do any associated clicking
5612     * actions like reporting an accessibility event.
5613     *
5614     * @return True there was an assigned OnClickListener that was called, false
5615     *         otherwise is returned.
5616     */
5617    public boolean callOnClick() {
5618        ListenerInfo li = mListenerInfo;
5619        if (li != null && li.mOnClickListener != null) {
5620            li.mOnClickListener.onClick(this);
5621            return true;
5622        }
5623        return false;
5624    }
5625
5626    /**
5627     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5628     * context menu if the OnLongClickListener did not consume the event.
5629     *
5630     * @return {@code true} if one of the above receivers consumed the event,
5631     *         {@code false} otherwise
5632     */
5633    public boolean performLongClick() {
5634        return performLongClickInternal(mLongClickX, mLongClickY);
5635    }
5636
5637    /**
5638     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5639     * context menu if the OnLongClickListener did not consume the event,
5640     * anchoring it to an (x,y) coordinate.
5641     *
5642     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5643     *          to disable anchoring
5644     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5645     *          to disable anchoring
5646     * @return {@code true} if one of the above receivers consumed the event,
5647     *         {@code false} otherwise
5648     */
5649    public boolean performLongClick(float x, float y) {
5650        mLongClickX = x;
5651        mLongClickY = y;
5652        final boolean handled = performLongClick();
5653        mLongClickX = Float.NaN;
5654        mLongClickY = Float.NaN;
5655        return handled;
5656    }
5657
5658    /**
5659     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5660     * context menu if the OnLongClickListener did not consume the event,
5661     * optionally anchoring it to an (x,y) coordinate.
5662     *
5663     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5664     *          to disable anchoring
5665     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5666     *          to disable anchoring
5667     * @return {@code true} if one of the above receivers consumed the event,
5668     *         {@code false} otherwise
5669     */
5670    private boolean performLongClickInternal(float x, float y) {
5671        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5672
5673        boolean handled = false;
5674        final ListenerInfo li = mListenerInfo;
5675        if (li != null && li.mOnLongClickListener != null) {
5676            handled = li.mOnLongClickListener.onLongClick(View.this);
5677        }
5678        if (!handled) {
5679            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5680            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5681        }
5682        if (handled) {
5683            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5684        }
5685        return handled;
5686    }
5687
5688    /**
5689     * Call this view's OnContextClickListener, if it is defined.
5690     *
5691     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5692     *         otherwise.
5693     */
5694    public boolean performContextClick() {
5695        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5696
5697        boolean handled = false;
5698        ListenerInfo li = mListenerInfo;
5699        if (li != null && li.mOnContextClickListener != null) {
5700            handled = li.mOnContextClickListener.onContextClick(View.this);
5701        }
5702        if (handled) {
5703            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5704        }
5705        return handled;
5706    }
5707
5708    /**
5709     * Performs button-related actions during a touch down event.
5710     *
5711     * @param event The event.
5712     * @return True if the down was consumed.
5713     *
5714     * @hide
5715     */
5716    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5717        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5718            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5719            showContextMenu(event.getX(), event.getY());
5720            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5721            return true;
5722        }
5723        return false;
5724    }
5725
5726    /**
5727     * Shows the context menu for this view.
5728     *
5729     * @return {@code true} if the context menu was shown, {@code false}
5730     *         otherwise
5731     * @see #showContextMenu(float, float)
5732     */
5733    public boolean showContextMenu() {
5734        return getParent().showContextMenuForChild(this);
5735    }
5736
5737    /**
5738     * Shows the context menu for this view anchored to the specified
5739     * view-relative coordinate.
5740     *
5741     * @param x the X coordinate in pixels relative to the view to which the
5742     *          menu should be anchored
5743     * @param y the Y coordinate in pixels relative to the view to which the
5744     *          menu should be anchored
5745     * @return {@code true} if the context menu was shown, {@code false}
5746     *         otherwise
5747     */
5748    public boolean showContextMenu(float x, float y) {
5749        return getParent().showContextMenuForChild(this, x, y);
5750    }
5751
5752    /**
5753     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5754     *
5755     * @param callback Callback that will control the lifecycle of the action mode
5756     * @return The new action mode if it is started, null otherwise
5757     *
5758     * @see ActionMode
5759     * @see #startActionMode(android.view.ActionMode.Callback, int)
5760     */
5761    public ActionMode startActionMode(ActionMode.Callback callback) {
5762        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5763    }
5764
5765    /**
5766     * Start an action mode with the given type.
5767     *
5768     * @param callback Callback that will control the lifecycle of the action mode
5769     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5770     * @return The new action mode if it is started, null otherwise
5771     *
5772     * @see ActionMode
5773     */
5774    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5775        ViewParent parent = getParent();
5776        if (parent == null) return null;
5777        try {
5778            return parent.startActionModeForChild(this, callback, type);
5779        } catch (AbstractMethodError ame) {
5780            // Older implementations of custom views might not implement this.
5781            return parent.startActionModeForChild(this, callback);
5782        }
5783    }
5784
5785    /**
5786     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5787     * Context, creating a unique View identifier to retrieve the result.
5788     *
5789     * @param intent The Intent to be started.
5790     * @param requestCode The request code to use.
5791     * @hide
5792     */
5793    public void startActivityForResult(Intent intent, int requestCode) {
5794        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5795        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5796    }
5797
5798    /**
5799     * If this View corresponds to the calling who, dispatches the activity result.
5800     * @param who The identifier for the targeted View to receive the result.
5801     * @param requestCode The integer request code originally supplied to
5802     *                    startActivityForResult(), allowing you to identify who this
5803     *                    result came from.
5804     * @param resultCode The integer result code returned by the child activity
5805     *                   through its setResult().
5806     * @param data An Intent, which can return result data to the caller
5807     *               (various data can be attached to Intent "extras").
5808     * @return {@code true} if the activity result was dispatched.
5809     * @hide
5810     */
5811    public boolean dispatchActivityResult(
5812            String who, int requestCode, int resultCode, Intent data) {
5813        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5814            onActivityResult(requestCode, resultCode, data);
5815            mStartActivityRequestWho = null;
5816            return true;
5817        }
5818        return false;
5819    }
5820
5821    /**
5822     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5823     *
5824     * @param requestCode The integer request code originally supplied to
5825     *                    startActivityForResult(), allowing you to identify who this
5826     *                    result came from.
5827     * @param resultCode The integer result code returned by the child activity
5828     *                   through its setResult().
5829     * @param data An Intent, which can return result data to the caller
5830     *               (various data can be attached to Intent "extras").
5831     * @hide
5832     */
5833    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5834        // Do nothing.
5835    }
5836
5837    /**
5838     * Register a callback to be invoked when a hardware key is pressed in this view.
5839     * Key presses in software input methods will generally not trigger the methods of
5840     * this listener.
5841     * @param l the key listener to attach to this view
5842     */
5843    public void setOnKeyListener(OnKeyListener l) {
5844        getListenerInfo().mOnKeyListener = l;
5845    }
5846
5847    /**
5848     * Register a callback to be invoked when a touch event is sent to this view.
5849     * @param l the touch listener to attach to this view
5850     */
5851    public void setOnTouchListener(OnTouchListener l) {
5852        getListenerInfo().mOnTouchListener = l;
5853    }
5854
5855    /**
5856     * Register a callback to be invoked when a generic motion event is sent to this view.
5857     * @param l the generic motion listener to attach to this view
5858     */
5859    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5860        getListenerInfo().mOnGenericMotionListener = l;
5861    }
5862
5863    /**
5864     * Register a callback to be invoked when a hover event is sent to this view.
5865     * @param l the hover listener to attach to this view
5866     */
5867    public void setOnHoverListener(OnHoverListener l) {
5868        getListenerInfo().mOnHoverListener = l;
5869    }
5870
5871    /**
5872     * Register a drag event listener callback object for this View. The parameter is
5873     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5874     * View, the system calls the
5875     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5876     * @param l An implementation of {@link android.view.View.OnDragListener}.
5877     */
5878    public void setOnDragListener(OnDragListener l) {
5879        getListenerInfo().mOnDragListener = l;
5880    }
5881
5882    /**
5883     * Give this view focus. This will cause
5884     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5885     *
5886     * Note: this does not check whether this {@link View} should get focus, it just
5887     * gives it focus no matter what.  It should only be called internally by framework
5888     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5889     *
5890     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5891     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5892     *        focus moved when requestFocus() is called. It may not always
5893     *        apply, in which case use the default View.FOCUS_DOWN.
5894     * @param previouslyFocusedRect The rectangle of the view that had focus
5895     *        prior in this View's coordinate system.
5896     */
5897    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5898        if (DBG) {
5899            System.out.println(this + " requestFocus()");
5900        }
5901
5902        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5903            mPrivateFlags |= PFLAG_FOCUSED;
5904
5905            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5906
5907            if (mParent != null) {
5908                mParent.requestChildFocus(this, this);
5909            }
5910
5911            if (mAttachInfo != null) {
5912                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5913            }
5914
5915            onFocusChanged(true, direction, previouslyFocusedRect);
5916            refreshDrawableState();
5917        }
5918    }
5919
5920    /**
5921     * Populates <code>outRect</code> with the hotspot bounds. By default,
5922     * the hotspot bounds are identical to the screen bounds.
5923     *
5924     * @param outRect rect to populate with hotspot bounds
5925     * @hide Only for internal use by views and widgets.
5926     */
5927    public void getHotspotBounds(Rect outRect) {
5928        final Drawable background = getBackground();
5929        if (background != null) {
5930            background.getHotspotBounds(outRect);
5931        } else {
5932            getBoundsOnScreen(outRect);
5933        }
5934    }
5935
5936    /**
5937     * Request that a rectangle of this view be visible on the screen,
5938     * scrolling if necessary just enough.
5939     *
5940     * <p>A View should call this if it maintains some notion of which part
5941     * of its content is interesting.  For example, a text editing view
5942     * should call this when its cursor moves.
5943     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5944     * It should not be affected by which part of the View is currently visible or its scroll
5945     * position.
5946     *
5947     * @param rectangle The rectangle in the View's content coordinate space
5948     * @return Whether any parent scrolled.
5949     */
5950    public boolean requestRectangleOnScreen(Rect rectangle) {
5951        return requestRectangleOnScreen(rectangle, false);
5952    }
5953
5954    /**
5955     * Request that a rectangle of this view be visible on the screen,
5956     * scrolling if necessary just enough.
5957     *
5958     * <p>A View should call this if it maintains some notion of which part
5959     * of its content is interesting.  For example, a text editing view
5960     * should call this when its cursor moves.
5961     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5962     * It should not be affected by which part of the View is currently visible or its scroll
5963     * position.
5964     * <p>When <code>immediate</code> is set to true, scrolling will not be
5965     * animated.
5966     *
5967     * @param rectangle The rectangle in the View's content coordinate space
5968     * @param immediate True to forbid animated scrolling, false otherwise
5969     * @return Whether any parent scrolled.
5970     */
5971    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5972        if (mParent == null) {
5973            return false;
5974        }
5975
5976        View child = this;
5977
5978        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5979        position.set(rectangle);
5980
5981        ViewParent parent = mParent;
5982        boolean scrolled = false;
5983        while (parent != null) {
5984            rectangle.set((int) position.left, (int) position.top,
5985                    (int) position.right, (int) position.bottom);
5986
5987            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
5988
5989            if (!(parent instanceof View)) {
5990                break;
5991            }
5992
5993            // move it from child's content coordinate space to parent's content coordinate space
5994            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
5995
5996            child = (View) parent;
5997            parent = child.getParent();
5998        }
5999
6000        return scrolled;
6001    }
6002
6003    /**
6004     * Called when this view wants to give up focus. If focus is cleared
6005     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6006     * <p>
6007     * <strong>Note:</strong> When a View clears focus the framework is trying
6008     * to give focus to the first focusable View from the top. Hence, if this
6009     * View is the first from the top that can take focus, then all callbacks
6010     * related to clearing focus will be invoked after which the framework will
6011     * give focus to this view.
6012     * </p>
6013     */
6014    public void clearFocus() {
6015        if (DBG) {
6016            System.out.println(this + " clearFocus()");
6017        }
6018
6019        clearFocusInternal(null, true, true);
6020    }
6021
6022    /**
6023     * Clears focus from the view, optionally propagating the change up through
6024     * the parent hierarchy and requesting that the root view place new focus.
6025     *
6026     * @param propagate whether to propagate the change up through the parent
6027     *            hierarchy
6028     * @param refocus when propagate is true, specifies whether to request the
6029     *            root view place new focus
6030     */
6031    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6032        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6033            mPrivateFlags &= ~PFLAG_FOCUSED;
6034
6035            if (propagate && mParent != null) {
6036                mParent.clearChildFocus(this);
6037            }
6038
6039            onFocusChanged(false, 0, null);
6040            refreshDrawableState();
6041
6042            if (propagate && (!refocus || !rootViewRequestFocus())) {
6043                notifyGlobalFocusCleared(this);
6044            }
6045        }
6046    }
6047
6048    void notifyGlobalFocusCleared(View oldFocus) {
6049        if (oldFocus != null && mAttachInfo != null) {
6050            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6051        }
6052    }
6053
6054    boolean rootViewRequestFocus() {
6055        final View root = getRootView();
6056        return root != null && root.requestFocus();
6057    }
6058
6059    /**
6060     * Called internally by the view system when a new view is getting focus.
6061     * This is what clears the old focus.
6062     * <p>
6063     * <b>NOTE:</b> The parent view's focused child must be updated manually
6064     * after calling this method. Otherwise, the view hierarchy may be left in
6065     * an inconstent state.
6066     */
6067    void unFocus(View focused) {
6068        if (DBG) {
6069            System.out.println(this + " unFocus()");
6070        }
6071
6072        clearFocusInternal(focused, false, false);
6073    }
6074
6075    /**
6076     * Returns true if this view has focus itself, or is the ancestor of the
6077     * view that has focus.
6078     *
6079     * @return True if this view has or contains focus, false otherwise.
6080     */
6081    @ViewDebug.ExportedProperty(category = "focus")
6082    public boolean hasFocus() {
6083        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6084    }
6085
6086    /**
6087     * Returns true if this view is focusable or if it contains a reachable View
6088     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6089     * is a View whose parents do not block descendants focus.
6090     *
6091     * Only {@link #VISIBLE} views are considered focusable.
6092     *
6093     * @return True if the view is focusable or if the view contains a focusable
6094     *         View, false otherwise.
6095     *
6096     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6097     * @see ViewGroup#getTouchscreenBlocksFocus()
6098     */
6099    public boolean hasFocusable() {
6100        if (!isFocusableInTouchMode()) {
6101            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6102                final ViewGroup g = (ViewGroup) p;
6103                if (g.shouldBlockFocusForTouchscreen()) {
6104                    return false;
6105                }
6106            }
6107        }
6108        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6109    }
6110
6111    /**
6112     * Called by the view system when the focus state of this view changes.
6113     * When the focus change event is caused by directional navigation, direction
6114     * and previouslyFocusedRect provide insight into where the focus is coming from.
6115     * When overriding, be sure to call up through to the super class so that
6116     * the standard focus handling will occur.
6117     *
6118     * @param gainFocus True if the View has focus; false otherwise.
6119     * @param direction The direction focus has moved when requestFocus()
6120     *                  is called to give this view focus. Values are
6121     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6122     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6123     *                  It may not always apply, in which case use the default.
6124     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6125     *        system, of the previously focused view.  If applicable, this will be
6126     *        passed in as finer grained information about where the focus is coming
6127     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6128     */
6129    @CallSuper
6130    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6131            @Nullable Rect previouslyFocusedRect) {
6132        if (gainFocus) {
6133            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6134        } else {
6135            notifyViewAccessibilityStateChangedIfNeeded(
6136                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6137        }
6138
6139        InputMethodManager imm = InputMethodManager.peekInstance();
6140        if (!gainFocus) {
6141            if (isPressed()) {
6142                setPressed(false);
6143            }
6144            if (imm != null && mAttachInfo != null
6145                    && mAttachInfo.mHasWindowFocus) {
6146                imm.focusOut(this);
6147            }
6148            onFocusLost();
6149        } else if (imm != null && mAttachInfo != null
6150                && mAttachInfo.mHasWindowFocus) {
6151            imm.focusIn(this);
6152        }
6153
6154        invalidate(true);
6155        ListenerInfo li = mListenerInfo;
6156        if (li != null && li.mOnFocusChangeListener != null) {
6157            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6158        }
6159
6160        if (mAttachInfo != null) {
6161            mAttachInfo.mKeyDispatchState.reset(this);
6162        }
6163    }
6164
6165    /**
6166     * Sends an accessibility event of the given type. If accessibility is
6167     * not enabled this method has no effect. The default implementation calls
6168     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6169     * to populate information about the event source (this View), then calls
6170     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6171     * populate the text content of the event source including its descendants,
6172     * and last calls
6173     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6174     * on its parent to request sending of the event to interested parties.
6175     * <p>
6176     * If an {@link AccessibilityDelegate} has been specified via calling
6177     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6178     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6179     * responsible for handling this call.
6180     * </p>
6181     *
6182     * @param eventType The type of the event to send, as defined by several types from
6183     * {@link android.view.accessibility.AccessibilityEvent}, such as
6184     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6185     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6186     *
6187     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6188     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6189     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6190     * @see AccessibilityDelegate
6191     */
6192    public void sendAccessibilityEvent(int eventType) {
6193        if (mAccessibilityDelegate != null) {
6194            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6195        } else {
6196            sendAccessibilityEventInternal(eventType);
6197        }
6198    }
6199
6200    /**
6201     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6202     * {@link AccessibilityEvent} to make an announcement which is related to some
6203     * sort of a context change for which none of the events representing UI transitions
6204     * is a good fit. For example, announcing a new page in a book. If accessibility
6205     * is not enabled this method does nothing.
6206     *
6207     * @param text The announcement text.
6208     */
6209    public void announceForAccessibility(CharSequence text) {
6210        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6211            AccessibilityEvent event = AccessibilityEvent.obtain(
6212                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6213            onInitializeAccessibilityEvent(event);
6214            event.getText().add(text);
6215            event.setContentDescription(null);
6216            mParent.requestSendAccessibilityEvent(this, event);
6217        }
6218    }
6219
6220    /**
6221     * @see #sendAccessibilityEvent(int)
6222     *
6223     * Note: Called from the default {@link AccessibilityDelegate}.
6224     *
6225     * @hide
6226     */
6227    public void sendAccessibilityEventInternal(int eventType) {
6228        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6229            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6230        }
6231    }
6232
6233    /**
6234     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6235     * takes as an argument an empty {@link AccessibilityEvent} and does not
6236     * perform a check whether accessibility is enabled.
6237     * <p>
6238     * If an {@link AccessibilityDelegate} has been specified via calling
6239     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6240     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6241     * is responsible for handling this call.
6242     * </p>
6243     *
6244     * @param event The event to send.
6245     *
6246     * @see #sendAccessibilityEvent(int)
6247     */
6248    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6249        if (mAccessibilityDelegate != null) {
6250            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6251        } else {
6252            sendAccessibilityEventUncheckedInternal(event);
6253        }
6254    }
6255
6256    /**
6257     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6258     *
6259     * Note: Called from the default {@link AccessibilityDelegate}.
6260     *
6261     * @hide
6262     */
6263    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6264        if (!isShown()) {
6265            return;
6266        }
6267        onInitializeAccessibilityEvent(event);
6268        // Only a subset of accessibility events populates text content.
6269        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6270            dispatchPopulateAccessibilityEvent(event);
6271        }
6272        // In the beginning we called #isShown(), so we know that getParent() is not null.
6273        getParent().requestSendAccessibilityEvent(this, event);
6274    }
6275
6276    /**
6277     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6278     * to its children for adding their text content to the event. Note that the
6279     * event text is populated in a separate dispatch path since we add to the
6280     * event not only the text of the source but also the text of all its descendants.
6281     * A typical implementation will call
6282     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6283     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6284     * on each child. Override this method if custom population of the event text
6285     * content is required.
6286     * <p>
6287     * If an {@link AccessibilityDelegate} has been specified via calling
6288     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6289     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6290     * is responsible for handling this call.
6291     * </p>
6292     * <p>
6293     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6294     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6295     * </p>
6296     *
6297     * @param event The event.
6298     *
6299     * @return True if the event population was completed.
6300     */
6301    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6302        if (mAccessibilityDelegate != null) {
6303            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6304        } else {
6305            return dispatchPopulateAccessibilityEventInternal(event);
6306        }
6307    }
6308
6309    /**
6310     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6311     *
6312     * Note: Called from the default {@link AccessibilityDelegate}.
6313     *
6314     * @hide
6315     */
6316    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6317        onPopulateAccessibilityEvent(event);
6318        return false;
6319    }
6320
6321    /**
6322     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6323     * giving a chance to this View to populate the accessibility event with its
6324     * text content. While this method is free to modify event
6325     * attributes other than text content, doing so should normally be performed in
6326     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6327     * <p>
6328     * Example: Adding formatted date string to an accessibility event in addition
6329     *          to the text added by the super implementation:
6330     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6331     *     super.onPopulateAccessibilityEvent(event);
6332     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6333     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6334     *         mCurrentDate.getTimeInMillis(), flags);
6335     *     event.getText().add(selectedDateUtterance);
6336     * }</pre>
6337     * <p>
6338     * If an {@link AccessibilityDelegate} has been specified via calling
6339     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6340     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6341     * is responsible for handling this call.
6342     * </p>
6343     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6344     * information to the event, in case the default implementation has basic information to add.
6345     * </p>
6346     *
6347     * @param event The accessibility event which to populate.
6348     *
6349     * @see #sendAccessibilityEvent(int)
6350     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6351     */
6352    @CallSuper
6353    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6354        if (mAccessibilityDelegate != null) {
6355            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6356        } else {
6357            onPopulateAccessibilityEventInternal(event);
6358        }
6359    }
6360
6361    /**
6362     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6363     *
6364     * Note: Called from the default {@link AccessibilityDelegate}.
6365     *
6366     * @hide
6367     */
6368    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6369    }
6370
6371    /**
6372     * Initializes an {@link AccessibilityEvent} with information about
6373     * this View which is the event source. In other words, the source of
6374     * an accessibility event is the view whose state change triggered firing
6375     * the event.
6376     * <p>
6377     * Example: Setting the password property of an event in addition
6378     *          to properties set by the super implementation:
6379     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6380     *     super.onInitializeAccessibilityEvent(event);
6381     *     event.setPassword(true);
6382     * }</pre>
6383     * <p>
6384     * If an {@link AccessibilityDelegate} has been specified via calling
6385     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6386     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6387     * is responsible for handling this call.
6388     * </p>
6389     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6390     * information to the event, in case the default implementation has basic information to add.
6391     * </p>
6392     * @param event The event to initialize.
6393     *
6394     * @see #sendAccessibilityEvent(int)
6395     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6396     */
6397    @CallSuper
6398    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6399        if (mAccessibilityDelegate != null) {
6400            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6401        } else {
6402            onInitializeAccessibilityEventInternal(event);
6403        }
6404    }
6405
6406    /**
6407     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6408     *
6409     * Note: Called from the default {@link AccessibilityDelegate}.
6410     *
6411     * @hide
6412     */
6413    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6414        event.setSource(this);
6415        event.setClassName(getAccessibilityClassName());
6416        event.setPackageName(getContext().getPackageName());
6417        event.setEnabled(isEnabled());
6418        event.setContentDescription(mContentDescription);
6419
6420        switch (event.getEventType()) {
6421            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6422                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6423                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6424                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6425                event.setItemCount(focusablesTempList.size());
6426                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6427                if (mAttachInfo != null) {
6428                    focusablesTempList.clear();
6429                }
6430            } break;
6431            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6432                CharSequence text = getIterableTextForAccessibility();
6433                if (text != null && text.length() > 0) {
6434                    event.setFromIndex(getAccessibilitySelectionStart());
6435                    event.setToIndex(getAccessibilitySelectionEnd());
6436                    event.setItemCount(text.length());
6437                }
6438            } break;
6439        }
6440    }
6441
6442    /**
6443     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6444     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6445     * This method is responsible for obtaining an accessibility node info from a
6446     * pool of reusable instances and calling
6447     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6448     * initialize the former.
6449     * <p>
6450     * Note: The client is responsible for recycling the obtained instance by calling
6451     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6452     * </p>
6453     *
6454     * @return A populated {@link AccessibilityNodeInfo}.
6455     *
6456     * @see AccessibilityNodeInfo
6457     */
6458    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6459        if (mAccessibilityDelegate != null) {
6460            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6461        } else {
6462            return createAccessibilityNodeInfoInternal();
6463        }
6464    }
6465
6466    /**
6467     * @see #createAccessibilityNodeInfo()
6468     *
6469     * @hide
6470     */
6471    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6472        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6473        if (provider != null) {
6474            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6475        } else {
6476            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6477            onInitializeAccessibilityNodeInfo(info);
6478            return info;
6479        }
6480    }
6481
6482    /**
6483     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6484     * The base implementation sets:
6485     * <ul>
6486     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6487     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6488     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6489     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6490     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6491     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6492     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6493     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6494     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6495     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6496     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6497     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6498     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6499     * </ul>
6500     * <p>
6501     * Subclasses should override this method, call the super implementation,
6502     * and set additional attributes.
6503     * </p>
6504     * <p>
6505     * If an {@link AccessibilityDelegate} has been specified via calling
6506     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6507     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6508     * is responsible for handling this call.
6509     * </p>
6510     *
6511     * @param info The instance to initialize.
6512     */
6513    @CallSuper
6514    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6515        if (mAccessibilityDelegate != null) {
6516            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6517        } else {
6518            onInitializeAccessibilityNodeInfoInternal(info);
6519        }
6520    }
6521
6522    /**
6523     * Gets the location of this view in screen coordinates.
6524     *
6525     * @param outRect The output location
6526     * @hide
6527     */
6528    public void getBoundsOnScreen(Rect outRect) {
6529        getBoundsOnScreen(outRect, false);
6530    }
6531
6532    /**
6533     * Gets the location of this view in screen coordinates.
6534     *
6535     * @param outRect The output location
6536     * @param clipToParent Whether to clip child bounds to the parent ones.
6537     * @hide
6538     */
6539    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6540        if (mAttachInfo == null) {
6541            return;
6542        }
6543
6544        RectF position = mAttachInfo.mTmpTransformRect;
6545        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6546
6547        if (!hasIdentityMatrix()) {
6548            getMatrix().mapRect(position);
6549        }
6550
6551        position.offset(mLeft, mTop);
6552
6553        ViewParent parent = mParent;
6554        while (parent instanceof View) {
6555            View parentView = (View) parent;
6556
6557            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6558
6559            if (clipToParent) {
6560                position.left = Math.max(position.left, 0);
6561                position.top = Math.max(position.top, 0);
6562                position.right = Math.min(position.right, parentView.getWidth());
6563                position.bottom = Math.min(position.bottom, parentView.getHeight());
6564            }
6565
6566            if (!parentView.hasIdentityMatrix()) {
6567                parentView.getMatrix().mapRect(position);
6568            }
6569
6570            position.offset(parentView.mLeft, parentView.mTop);
6571
6572            parent = parentView.mParent;
6573        }
6574
6575        if (parent instanceof ViewRootImpl) {
6576            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6577            position.offset(0, -viewRootImpl.mCurScrollY);
6578        }
6579
6580        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6581
6582        outRect.set(Math.round(position.left), Math.round(position.top),
6583                Math.round(position.right), Math.round(position.bottom));
6584    }
6585
6586    /**
6587     * Return the class name of this object to be used for accessibility purposes.
6588     * Subclasses should only override this if they are implementing something that
6589     * should be seen as a completely new class of view when used by accessibility,
6590     * unrelated to the class it is deriving from.  This is used to fill in
6591     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6592     */
6593    public CharSequence getAccessibilityClassName() {
6594        return View.class.getName();
6595    }
6596
6597    /**
6598     * Called when assist structure is being retrieved from a view as part of
6599     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6600     * @param structure Fill in with structured view data.  The default implementation
6601     * fills in all data that can be inferred from the view itself.
6602     */
6603    public void onProvideStructure(ViewStructure structure) {
6604        final int id = mID;
6605        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6606                && (id&0x0000ffff) != 0) {
6607            String pkg, type, entry;
6608            try {
6609                final Resources res = getResources();
6610                entry = res.getResourceEntryName(id);
6611                type = res.getResourceTypeName(id);
6612                pkg = res.getResourcePackageName(id);
6613            } catch (Resources.NotFoundException e) {
6614                entry = type = pkg = null;
6615            }
6616            structure.setId(id, pkg, type, entry);
6617        } else {
6618            structure.setId(id, null, null, null);
6619        }
6620        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6621        if (!hasIdentityMatrix()) {
6622            structure.setTransformation(getMatrix());
6623        }
6624        structure.setElevation(getZ());
6625        structure.setVisibility(getVisibility());
6626        structure.setEnabled(isEnabled());
6627        if (isClickable()) {
6628            structure.setClickable(true);
6629        }
6630        if (isFocusable()) {
6631            structure.setFocusable(true);
6632        }
6633        if (isFocused()) {
6634            structure.setFocused(true);
6635        }
6636        if (isAccessibilityFocused()) {
6637            structure.setAccessibilityFocused(true);
6638        }
6639        if (isSelected()) {
6640            structure.setSelected(true);
6641        }
6642        if (isActivated()) {
6643            structure.setActivated(true);
6644        }
6645        if (isLongClickable()) {
6646            structure.setLongClickable(true);
6647        }
6648        if (this instanceof Checkable) {
6649            structure.setCheckable(true);
6650            if (((Checkable)this).isChecked()) {
6651                structure.setChecked(true);
6652            }
6653        }
6654        if (isContextClickable()) {
6655            structure.setContextClickable(true);
6656        }
6657        structure.setClassName(getAccessibilityClassName().toString());
6658        structure.setContentDescription(getContentDescription());
6659    }
6660
6661    /**
6662     * Called when assist structure is being retrieved from a view as part of
6663     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6664     * generate additional virtual structure under this view.  The defaullt implementation
6665     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6666     * view's virtual accessibility nodes, if any.  You can override this for a more
6667     * optimal implementation providing this data.
6668     */
6669    public void onProvideVirtualStructure(ViewStructure structure) {
6670        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6671        if (provider != null) {
6672            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6673            structure.setChildCount(1);
6674            ViewStructure root = structure.newChild(0);
6675            populateVirtualStructure(root, provider, info);
6676            info.recycle();
6677        }
6678    }
6679
6680    private void populateVirtualStructure(ViewStructure structure,
6681            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
6682        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6683                null, null, null);
6684        Rect rect = structure.getTempRect();
6685        info.getBoundsInParent(rect);
6686        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6687        structure.setVisibility(VISIBLE);
6688        structure.setEnabled(info.isEnabled());
6689        if (info.isClickable()) {
6690            structure.setClickable(true);
6691        }
6692        if (info.isFocusable()) {
6693            structure.setFocusable(true);
6694        }
6695        if (info.isFocused()) {
6696            structure.setFocused(true);
6697        }
6698        if (info.isAccessibilityFocused()) {
6699            structure.setAccessibilityFocused(true);
6700        }
6701        if (info.isSelected()) {
6702            structure.setSelected(true);
6703        }
6704        if (info.isLongClickable()) {
6705            structure.setLongClickable(true);
6706        }
6707        if (info.isCheckable()) {
6708            structure.setCheckable(true);
6709            if (info.isChecked()) {
6710                structure.setChecked(true);
6711            }
6712        }
6713        if (info.isContextClickable()) {
6714            structure.setContextClickable(true);
6715        }
6716        CharSequence cname = info.getClassName();
6717        structure.setClassName(cname != null ? cname.toString() : null);
6718        structure.setContentDescription(info.getContentDescription());
6719        if (info.getText() != null || info.getError() != null) {
6720            structure.setText(info.getText(), info.getTextSelectionStart(),
6721                    info.getTextSelectionEnd());
6722        }
6723        final int NCHILDREN = info.getChildCount();
6724        if (NCHILDREN > 0) {
6725            structure.setChildCount(NCHILDREN);
6726            for (int i=0; i<NCHILDREN; i++) {
6727                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6728                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6729                ViewStructure child = structure.newChild(i);
6730                populateVirtualStructure(child, provider, cinfo);
6731                cinfo.recycle();
6732            }
6733        }
6734    }
6735
6736    /**
6737     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6738     * implementation calls {@link #onProvideStructure} and
6739     * {@link #onProvideVirtualStructure}.
6740     */
6741    public void dispatchProvideStructure(ViewStructure structure) {
6742        if (!isAssistBlocked()) {
6743            onProvideStructure(structure);
6744            onProvideVirtualStructure(structure);
6745        } else {
6746            structure.setClassName(getAccessibilityClassName().toString());
6747            structure.setAssistBlocked(true);
6748        }
6749    }
6750
6751    /**
6752     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6753     *
6754     * Note: Called from the default {@link AccessibilityDelegate}.
6755     *
6756     * @hide
6757     */
6758    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6759        if (mAttachInfo == null) {
6760            return;
6761        }
6762
6763        Rect bounds = mAttachInfo.mTmpInvalRect;
6764
6765        getDrawingRect(bounds);
6766        info.setBoundsInParent(bounds);
6767
6768        getBoundsOnScreen(bounds, true);
6769        info.setBoundsInScreen(bounds);
6770
6771        ViewParent parent = getParentForAccessibility();
6772        if (parent instanceof View) {
6773            info.setParent((View) parent);
6774        }
6775
6776        if (mID != View.NO_ID) {
6777            View rootView = getRootView();
6778            if (rootView == null) {
6779                rootView = this;
6780            }
6781
6782            View label = rootView.findLabelForView(this, mID);
6783            if (label != null) {
6784                info.setLabeledBy(label);
6785            }
6786
6787            if ((mAttachInfo.mAccessibilityFetchFlags
6788                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6789                    && Resources.resourceHasPackage(mID)) {
6790                try {
6791                    String viewId = getResources().getResourceName(mID);
6792                    info.setViewIdResourceName(viewId);
6793                } catch (Resources.NotFoundException nfe) {
6794                    /* ignore */
6795                }
6796            }
6797        }
6798
6799        if (mLabelForId != View.NO_ID) {
6800            View rootView = getRootView();
6801            if (rootView == null) {
6802                rootView = this;
6803            }
6804            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6805            if (labeled != null) {
6806                info.setLabelFor(labeled);
6807            }
6808        }
6809
6810        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6811            View rootView = getRootView();
6812            if (rootView == null) {
6813                rootView = this;
6814            }
6815            View next = rootView.findViewInsideOutShouldExist(this,
6816                    mAccessibilityTraversalBeforeId);
6817            if (next != null && next.includeForAccessibility()) {
6818                info.setTraversalBefore(next);
6819            }
6820        }
6821
6822        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6823            View rootView = getRootView();
6824            if (rootView == null) {
6825                rootView = this;
6826            }
6827            View next = rootView.findViewInsideOutShouldExist(this,
6828                    mAccessibilityTraversalAfterId);
6829            if (next != null && next.includeForAccessibility()) {
6830                info.setTraversalAfter(next);
6831            }
6832        }
6833
6834        info.setVisibleToUser(isVisibleToUser());
6835
6836        if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags
6837                & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) {
6838            info.setImportantForAccessibility(isImportantForAccessibility());
6839        } else {
6840            info.setImportantForAccessibility(true);
6841        }
6842
6843        info.setPackageName(mContext.getPackageName());
6844        info.setClassName(getAccessibilityClassName());
6845        info.setContentDescription(getContentDescription());
6846
6847        info.setEnabled(isEnabled());
6848        info.setClickable(isClickable());
6849        info.setFocusable(isFocusable());
6850        info.setFocused(isFocused());
6851        info.setAccessibilityFocused(isAccessibilityFocused());
6852        info.setSelected(isSelected());
6853        info.setLongClickable(isLongClickable());
6854        info.setContextClickable(isContextClickable());
6855        info.setLiveRegion(getAccessibilityLiveRegion());
6856
6857        // TODO: These make sense only if we are in an AdapterView but all
6858        // views can be selected. Maybe from accessibility perspective
6859        // we should report as selectable view in an AdapterView.
6860        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6861        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6862
6863        if (isFocusable()) {
6864            if (isFocused()) {
6865                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6866            } else {
6867                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6868            }
6869        }
6870
6871        if (!isAccessibilityFocused()) {
6872            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6873        } else {
6874            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6875        }
6876
6877        if (isClickable() && isEnabled()) {
6878            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6879        }
6880
6881        if (isLongClickable() && isEnabled()) {
6882            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6883        }
6884
6885        if (isContextClickable() && isEnabled()) {
6886            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6887        }
6888
6889        CharSequence text = getIterableTextForAccessibility();
6890        if (text != null && text.length() > 0) {
6891            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6892
6893            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6894            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6895            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6896            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6897                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6898                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6899        }
6900
6901        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6902        populateAccessibilityNodeInfoDrawingOrderInParent(info);
6903    }
6904
6905    /**
6906     * Determine the order in which this view will be drawn relative to its siblings for a11y
6907     *
6908     * @param info The info whose drawing order should be populated
6909     */
6910    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
6911        /*
6912         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
6913         * drawing order may not be well-defined, and some Views with custom drawing order may
6914         * not be initialized sufficiently to respond properly getChildDrawingOrder.
6915         */
6916        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
6917            info.setDrawingOrder(0);
6918            return;
6919        }
6920        int drawingOrderInParent = 1;
6921        // Iterate up the hierarchy if parents are not important for a11y
6922        View viewAtDrawingLevel = this;
6923        final ViewParent parent = getParentForAccessibility();
6924        while (viewAtDrawingLevel != parent) {
6925            final ViewParent currentParent = viewAtDrawingLevel.getParent();
6926            if (!(currentParent instanceof ViewGroup)) {
6927                // Should only happen for the Decor
6928                drawingOrderInParent = 0;
6929                break;
6930            } else {
6931                final ViewGroup parentGroup = (ViewGroup) currentParent;
6932                final int childCount = parentGroup.getChildCount();
6933                if (childCount > 1) {
6934                    List<View> preorderedList = parentGroup.buildOrderedChildList();
6935                    if (preorderedList != null) {
6936                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
6937                        for (int i = 0; i < childDrawIndex; i++) {
6938                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
6939                        }
6940                    } else {
6941                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
6942                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
6943                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
6944                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
6945                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
6946                        if (childDrawIndex != 0) {
6947                            for (int i = 0; i < numChildrenToIterate; i++) {
6948                                final int otherDrawIndex = (customOrder ?
6949                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
6950                                if (otherDrawIndex < childDrawIndex) {
6951                                    drawingOrderInParent +=
6952                                            numViewsForAccessibility(parentGroup.getChildAt(i));
6953                                }
6954                            }
6955                        }
6956                    }
6957                }
6958            }
6959            viewAtDrawingLevel = (View) currentParent;
6960        }
6961        info.setDrawingOrder(drawingOrderInParent);
6962    }
6963
6964    private static int numViewsForAccessibility(View view) {
6965        if (view != null) {
6966            if (view.includeForAccessibility()) {
6967                return 1;
6968            } else if (view instanceof ViewGroup) {
6969                return ((ViewGroup) view).getNumChildrenForAccessibility();
6970            }
6971        }
6972        return 0;
6973    }
6974
6975    private View findLabelForView(View view, int labeledId) {
6976        if (mMatchLabelForPredicate == null) {
6977            mMatchLabelForPredicate = new MatchLabelForPredicate();
6978        }
6979        mMatchLabelForPredicate.mLabeledId = labeledId;
6980        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
6981    }
6982
6983    /**
6984     * Computes whether this view is visible to the user. Such a view is
6985     * attached, visible, all its predecessors are visible, it is not clipped
6986     * entirely by its predecessors, and has an alpha greater than zero.
6987     *
6988     * @return Whether the view is visible on the screen.
6989     *
6990     * @hide
6991     */
6992    protected boolean isVisibleToUser() {
6993        return isVisibleToUser(null);
6994    }
6995
6996    /**
6997     * Computes whether the given portion of this view is visible to the user.
6998     * Such a view is attached, visible, all its predecessors are visible,
6999     * has an alpha greater than zero, and the specified portion is not
7000     * clipped entirely by its predecessors.
7001     *
7002     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7003     *                    <code>null</code>, and the entire view will be tested in this case.
7004     *                    When <code>true</code> is returned by the function, the actual visible
7005     *                    region will be stored in this parameter; that is, if boundInView is fully
7006     *                    contained within the view, no modification will be made, otherwise regions
7007     *                    outside of the visible area of the view will be clipped.
7008     *
7009     * @return Whether the specified portion of the view is visible on the screen.
7010     *
7011     * @hide
7012     */
7013    protected boolean isVisibleToUser(Rect boundInView) {
7014        if (mAttachInfo != null) {
7015            // Attached to invisible window means this view is not visible.
7016            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7017                return false;
7018            }
7019            // An invisible predecessor or one with alpha zero means
7020            // that this view is not visible to the user.
7021            Object current = this;
7022            while (current instanceof View) {
7023                View view = (View) current;
7024                // We have attach info so this view is attached and there is no
7025                // need to check whether we reach to ViewRootImpl on the way up.
7026                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7027                        view.getVisibility() != VISIBLE) {
7028                    return false;
7029                }
7030                current = view.mParent;
7031            }
7032            // Check if the view is entirely covered by its predecessors.
7033            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7034            Point offset = mAttachInfo.mPoint;
7035            if (!getGlobalVisibleRect(visibleRect, offset)) {
7036                return false;
7037            }
7038            // Check if the visible portion intersects the rectangle of interest.
7039            if (boundInView != null) {
7040                visibleRect.offset(-offset.x, -offset.y);
7041                return boundInView.intersect(visibleRect);
7042            }
7043            return true;
7044        }
7045        return false;
7046    }
7047
7048    /**
7049     * Returns the delegate for implementing accessibility support via
7050     * composition. For more details see {@link AccessibilityDelegate}.
7051     *
7052     * @return The delegate, or null if none set.
7053     *
7054     * @hide
7055     */
7056    public AccessibilityDelegate getAccessibilityDelegate() {
7057        return mAccessibilityDelegate;
7058    }
7059
7060    /**
7061     * Sets a delegate for implementing accessibility support via composition
7062     * (as opposed to inheritance). For more details, see
7063     * {@link AccessibilityDelegate}.
7064     * <p>
7065     * <strong>Note:</strong> On platform versions prior to
7066     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7067     * views in the {@code android.widget.*} package are called <i>before</i>
7068     * host methods. This prevents certain properties such as class name from
7069     * being modified by overriding
7070     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7071     * as any changes will be overwritten by the host class.
7072     * <p>
7073     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7074     * methods are called <i>after</i> host methods, which all properties to be
7075     * modified without being overwritten by the host class.
7076     *
7077     * @param delegate the object to which accessibility method calls should be
7078     *                 delegated
7079     * @see AccessibilityDelegate
7080     */
7081    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7082        mAccessibilityDelegate = delegate;
7083    }
7084
7085    /**
7086     * Gets the provider for managing a virtual view hierarchy rooted at this View
7087     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7088     * that explore the window content.
7089     * <p>
7090     * If this method returns an instance, this instance is responsible for managing
7091     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7092     * View including the one representing the View itself. Similarly the returned
7093     * instance is responsible for performing accessibility actions on any virtual
7094     * view or the root view itself.
7095     * </p>
7096     * <p>
7097     * If an {@link AccessibilityDelegate} has been specified via calling
7098     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7099     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7100     * is responsible for handling this call.
7101     * </p>
7102     *
7103     * @return The provider.
7104     *
7105     * @see AccessibilityNodeProvider
7106     */
7107    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7108        if (mAccessibilityDelegate != null) {
7109            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7110        } else {
7111            return null;
7112        }
7113    }
7114
7115    /**
7116     * Gets the unique identifier of this view on the screen for accessibility purposes.
7117     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
7118     *
7119     * @return The view accessibility id.
7120     *
7121     * @hide
7122     */
7123    public int getAccessibilityViewId() {
7124        if (mAccessibilityViewId == NO_ID) {
7125            mAccessibilityViewId = sNextAccessibilityViewId++;
7126        }
7127        return mAccessibilityViewId;
7128    }
7129
7130    /**
7131     * Gets the unique identifier of the window in which this View reseides.
7132     *
7133     * @return The window accessibility id.
7134     *
7135     * @hide
7136     */
7137    public int getAccessibilityWindowId() {
7138        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7139                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7140    }
7141
7142    /**
7143     * Returns the {@link View}'s content description.
7144     * <p>
7145     * <strong>Note:</strong> Do not override this method, as it will have no
7146     * effect on the content description presented to accessibility services.
7147     * You must call {@link #setContentDescription(CharSequence)} to modify the
7148     * content description.
7149     *
7150     * @return the content description
7151     * @see #setContentDescription(CharSequence)
7152     * @attr ref android.R.styleable#View_contentDescription
7153     */
7154    @ViewDebug.ExportedProperty(category = "accessibility")
7155    public CharSequence getContentDescription() {
7156        return mContentDescription;
7157    }
7158
7159    /**
7160     * Sets the {@link View}'s content description.
7161     * <p>
7162     * A content description briefly describes the view and is primarily used
7163     * for accessibility support to determine how a view should be presented to
7164     * the user. In the case of a view with no textual representation, such as
7165     * {@link android.widget.ImageButton}, a useful content description
7166     * explains what the view does. For example, an image button with a phone
7167     * icon that is used to place a call may use "Call" as its content
7168     * description. An image of a floppy disk that is used to save a file may
7169     * use "Save".
7170     *
7171     * @param contentDescription The content description.
7172     * @see #getContentDescription()
7173     * @attr ref android.R.styleable#View_contentDescription
7174     */
7175    @RemotableViewMethod
7176    public void setContentDescription(CharSequence contentDescription) {
7177        if (mContentDescription == null) {
7178            if (contentDescription == null) {
7179                return;
7180            }
7181        } else if (mContentDescription.equals(contentDescription)) {
7182            return;
7183        }
7184        mContentDescription = contentDescription;
7185        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7186        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7187            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7188            notifySubtreeAccessibilityStateChangedIfNeeded();
7189        } else {
7190            notifyViewAccessibilityStateChangedIfNeeded(
7191                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7192        }
7193    }
7194
7195    /**
7196     * Sets the id of a view before which this one is visited in accessibility traversal.
7197     * A screen-reader must visit the content of this view before the content of the one
7198     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7199     * will traverse the entire content of B before traversing the entire content of A,
7200     * regardles of what traversal strategy it is using.
7201     * <p>
7202     * Views that do not have specified before/after relationships are traversed in order
7203     * determined by the screen-reader.
7204     * </p>
7205     * <p>
7206     * Setting that this view is before a view that is not important for accessibility
7207     * or if this view is not important for accessibility will have no effect as the
7208     * screen-reader is not aware of unimportant views.
7209     * </p>
7210     *
7211     * @param beforeId The id of a view this one precedes in accessibility traversal.
7212     *
7213     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7214     *
7215     * @see #setImportantForAccessibility(int)
7216     */
7217    @RemotableViewMethod
7218    public void setAccessibilityTraversalBefore(int beforeId) {
7219        if (mAccessibilityTraversalBeforeId == beforeId) {
7220            return;
7221        }
7222        mAccessibilityTraversalBeforeId = beforeId;
7223        notifyViewAccessibilityStateChangedIfNeeded(
7224                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7225    }
7226
7227    /**
7228     * Gets the id of a view before which this one is visited in accessibility traversal.
7229     *
7230     * @return The id of a view this one precedes in accessibility traversal if
7231     *         specified, otherwise {@link #NO_ID}.
7232     *
7233     * @see #setAccessibilityTraversalBefore(int)
7234     */
7235    public int getAccessibilityTraversalBefore() {
7236        return mAccessibilityTraversalBeforeId;
7237    }
7238
7239    /**
7240     * Sets the id of a view after which this one is visited in accessibility traversal.
7241     * A screen-reader must visit the content of the other view before the content of this
7242     * one. For example, if view B is set to be after view A, then a screen-reader
7243     * will traverse the entire content of A before traversing the entire content of B,
7244     * regardles of what traversal strategy it is using.
7245     * <p>
7246     * Views that do not have specified before/after relationships are traversed in order
7247     * determined by the screen-reader.
7248     * </p>
7249     * <p>
7250     * Setting that this view is after a view that is not important for accessibility
7251     * or if this view is not important for accessibility will have no effect as the
7252     * screen-reader is not aware of unimportant views.
7253     * </p>
7254     *
7255     * @param afterId The id of a view this one succedees in accessibility traversal.
7256     *
7257     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7258     *
7259     * @see #setImportantForAccessibility(int)
7260     */
7261    @RemotableViewMethod
7262    public void setAccessibilityTraversalAfter(int afterId) {
7263        if (mAccessibilityTraversalAfterId == afterId) {
7264            return;
7265        }
7266        mAccessibilityTraversalAfterId = afterId;
7267        notifyViewAccessibilityStateChangedIfNeeded(
7268                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7269    }
7270
7271    /**
7272     * Gets the id of a view after which this one is visited in accessibility traversal.
7273     *
7274     * @return The id of a view this one succeedes in accessibility traversal if
7275     *         specified, otherwise {@link #NO_ID}.
7276     *
7277     * @see #setAccessibilityTraversalAfter(int)
7278     */
7279    public int getAccessibilityTraversalAfter() {
7280        return mAccessibilityTraversalAfterId;
7281    }
7282
7283    /**
7284     * Gets the id of a view for which this view serves as a label for
7285     * accessibility purposes.
7286     *
7287     * @return The labeled view id.
7288     */
7289    @ViewDebug.ExportedProperty(category = "accessibility")
7290    public int getLabelFor() {
7291        return mLabelForId;
7292    }
7293
7294    /**
7295     * Sets the id of a view for which this view serves as a label for
7296     * accessibility purposes.
7297     *
7298     * @param id The labeled view id.
7299     */
7300    @RemotableViewMethod
7301    public void setLabelFor(@IdRes int id) {
7302        if (mLabelForId == id) {
7303            return;
7304        }
7305        mLabelForId = id;
7306        if (mLabelForId != View.NO_ID
7307                && mID == View.NO_ID) {
7308            mID = generateViewId();
7309        }
7310        notifyViewAccessibilityStateChangedIfNeeded(
7311                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7312    }
7313
7314    /**
7315     * Invoked whenever this view loses focus, either by losing window focus or by losing
7316     * focus within its window. This method can be used to clear any state tied to the
7317     * focus. For instance, if a button is held pressed with the trackball and the window
7318     * loses focus, this method can be used to cancel the press.
7319     *
7320     * Subclasses of View overriding this method should always call super.onFocusLost().
7321     *
7322     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7323     * @see #onWindowFocusChanged(boolean)
7324     *
7325     * @hide pending API council approval
7326     */
7327    @CallSuper
7328    protected void onFocusLost() {
7329        resetPressedState();
7330    }
7331
7332    private void resetPressedState() {
7333        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7334            return;
7335        }
7336
7337        if (isPressed()) {
7338            setPressed(false);
7339
7340            if (!mHasPerformedLongPress) {
7341                removeLongPressCallback();
7342            }
7343        }
7344    }
7345
7346    /**
7347     * Returns true if this view has focus
7348     *
7349     * @return True if this view has focus, false otherwise.
7350     */
7351    @ViewDebug.ExportedProperty(category = "focus")
7352    public boolean isFocused() {
7353        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7354    }
7355
7356    /**
7357     * Find the view in the hierarchy rooted at this view that currently has
7358     * focus.
7359     *
7360     * @return The view that currently has focus, or null if no focused view can
7361     *         be found.
7362     */
7363    public View findFocus() {
7364        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7365    }
7366
7367    /**
7368     * Indicates whether this view is one of the set of scrollable containers in
7369     * its window.
7370     *
7371     * @return whether this view is one of the set of scrollable containers in
7372     * its window
7373     *
7374     * @attr ref android.R.styleable#View_isScrollContainer
7375     */
7376    public boolean isScrollContainer() {
7377        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7378    }
7379
7380    /**
7381     * Change whether this view is one of the set of scrollable containers in
7382     * its window.  This will be used to determine whether the window can
7383     * resize or must pan when a soft input area is open -- scrollable
7384     * containers allow the window to use resize mode since the container
7385     * will appropriately shrink.
7386     *
7387     * @attr ref android.R.styleable#View_isScrollContainer
7388     */
7389    public void setScrollContainer(boolean isScrollContainer) {
7390        if (isScrollContainer) {
7391            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7392                mAttachInfo.mScrollContainers.add(this);
7393                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7394            }
7395            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7396        } else {
7397            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7398                mAttachInfo.mScrollContainers.remove(this);
7399            }
7400            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7401        }
7402    }
7403
7404    /**
7405     * Returns the quality of the drawing cache.
7406     *
7407     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7408     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7409     *
7410     * @see #setDrawingCacheQuality(int)
7411     * @see #setDrawingCacheEnabled(boolean)
7412     * @see #isDrawingCacheEnabled()
7413     *
7414     * @attr ref android.R.styleable#View_drawingCacheQuality
7415     */
7416    @DrawingCacheQuality
7417    public int getDrawingCacheQuality() {
7418        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7419    }
7420
7421    /**
7422     * Set the drawing cache quality of this view. This value is used only when the
7423     * drawing cache is enabled
7424     *
7425     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7426     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7427     *
7428     * @see #getDrawingCacheQuality()
7429     * @see #setDrawingCacheEnabled(boolean)
7430     * @see #isDrawingCacheEnabled()
7431     *
7432     * @attr ref android.R.styleable#View_drawingCacheQuality
7433     */
7434    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7435        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7436    }
7437
7438    /**
7439     * Returns whether the screen should remain on, corresponding to the current
7440     * value of {@link #KEEP_SCREEN_ON}.
7441     *
7442     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7443     *
7444     * @see #setKeepScreenOn(boolean)
7445     *
7446     * @attr ref android.R.styleable#View_keepScreenOn
7447     */
7448    public boolean getKeepScreenOn() {
7449        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7450    }
7451
7452    /**
7453     * Controls whether the screen should remain on, modifying the
7454     * value of {@link #KEEP_SCREEN_ON}.
7455     *
7456     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7457     *
7458     * @see #getKeepScreenOn()
7459     *
7460     * @attr ref android.R.styleable#View_keepScreenOn
7461     */
7462    public void setKeepScreenOn(boolean keepScreenOn) {
7463        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7464    }
7465
7466    /**
7467     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7468     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7469     *
7470     * @attr ref android.R.styleable#View_nextFocusLeft
7471     */
7472    public int getNextFocusLeftId() {
7473        return mNextFocusLeftId;
7474    }
7475
7476    /**
7477     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7478     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7479     * decide automatically.
7480     *
7481     * @attr ref android.R.styleable#View_nextFocusLeft
7482     */
7483    public void setNextFocusLeftId(int nextFocusLeftId) {
7484        mNextFocusLeftId = nextFocusLeftId;
7485    }
7486
7487    /**
7488     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7489     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7490     *
7491     * @attr ref android.R.styleable#View_nextFocusRight
7492     */
7493    public int getNextFocusRightId() {
7494        return mNextFocusRightId;
7495    }
7496
7497    /**
7498     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7499     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7500     * decide automatically.
7501     *
7502     * @attr ref android.R.styleable#View_nextFocusRight
7503     */
7504    public void setNextFocusRightId(int nextFocusRightId) {
7505        mNextFocusRightId = nextFocusRightId;
7506    }
7507
7508    /**
7509     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7510     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7511     *
7512     * @attr ref android.R.styleable#View_nextFocusUp
7513     */
7514    public int getNextFocusUpId() {
7515        return mNextFocusUpId;
7516    }
7517
7518    /**
7519     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7520     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7521     * decide automatically.
7522     *
7523     * @attr ref android.R.styleable#View_nextFocusUp
7524     */
7525    public void setNextFocusUpId(int nextFocusUpId) {
7526        mNextFocusUpId = nextFocusUpId;
7527    }
7528
7529    /**
7530     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7531     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7532     *
7533     * @attr ref android.R.styleable#View_nextFocusDown
7534     */
7535    public int getNextFocusDownId() {
7536        return mNextFocusDownId;
7537    }
7538
7539    /**
7540     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7541     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7542     * decide automatically.
7543     *
7544     * @attr ref android.R.styleable#View_nextFocusDown
7545     */
7546    public void setNextFocusDownId(int nextFocusDownId) {
7547        mNextFocusDownId = nextFocusDownId;
7548    }
7549
7550    /**
7551     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7552     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7553     *
7554     * @attr ref android.R.styleable#View_nextFocusForward
7555     */
7556    public int getNextFocusForwardId() {
7557        return mNextFocusForwardId;
7558    }
7559
7560    /**
7561     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7562     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7563     * decide automatically.
7564     *
7565     * @attr ref android.R.styleable#View_nextFocusForward
7566     */
7567    public void setNextFocusForwardId(int nextFocusForwardId) {
7568        mNextFocusForwardId = nextFocusForwardId;
7569    }
7570
7571    /**
7572     * Returns the visibility of this view and all of its ancestors
7573     *
7574     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7575     */
7576    public boolean isShown() {
7577        View current = this;
7578        //noinspection ConstantConditions
7579        do {
7580            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7581                return false;
7582            }
7583            ViewParent parent = current.mParent;
7584            if (parent == null) {
7585                return false; // We are not attached to the view root
7586            }
7587            if (!(parent instanceof View)) {
7588                return true;
7589            }
7590            current = (View) parent;
7591        } while (current != null);
7592
7593        return false;
7594    }
7595
7596    /**
7597     * Called by the view hierarchy when the content insets for a window have
7598     * changed, to allow it to adjust its content to fit within those windows.
7599     * The content insets tell you the space that the status bar, input method,
7600     * and other system windows infringe on the application's window.
7601     *
7602     * <p>You do not normally need to deal with this function, since the default
7603     * window decoration given to applications takes care of applying it to the
7604     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7605     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7606     * and your content can be placed under those system elements.  You can then
7607     * use this method within your view hierarchy if you have parts of your UI
7608     * which you would like to ensure are not being covered.
7609     *
7610     * <p>The default implementation of this method simply applies the content
7611     * insets to the view's padding, consuming that content (modifying the
7612     * insets to be 0), and returning true.  This behavior is off by default, but can
7613     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7614     *
7615     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7616     * insets object is propagated down the hierarchy, so any changes made to it will
7617     * be seen by all following views (including potentially ones above in
7618     * the hierarchy since this is a depth-first traversal).  The first view
7619     * that returns true will abort the entire traversal.
7620     *
7621     * <p>The default implementation works well for a situation where it is
7622     * used with a container that covers the entire window, allowing it to
7623     * apply the appropriate insets to its content on all edges.  If you need
7624     * a more complicated layout (such as two different views fitting system
7625     * windows, one on the top of the window, and one on the bottom),
7626     * you can override the method and handle the insets however you would like.
7627     * Note that the insets provided by the framework are always relative to the
7628     * far edges of the window, not accounting for the location of the called view
7629     * within that window.  (In fact when this method is called you do not yet know
7630     * where the layout will place the view, as it is done before layout happens.)
7631     *
7632     * <p>Note: unlike many View methods, there is no dispatch phase to this
7633     * call.  If you are overriding it in a ViewGroup and want to allow the
7634     * call to continue to your children, you must be sure to call the super
7635     * implementation.
7636     *
7637     * <p>Here is a sample layout that makes use of fitting system windows
7638     * to have controls for a video view placed inside of the window decorations
7639     * that it hides and shows.  This can be used with code like the second
7640     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7641     *
7642     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7643     *
7644     * @param insets Current content insets of the window.  Prior to
7645     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7646     * the insets or else you and Android will be unhappy.
7647     *
7648     * @return {@code true} if this view applied the insets and it should not
7649     * continue propagating further down the hierarchy, {@code false} otherwise.
7650     * @see #getFitsSystemWindows()
7651     * @see #setFitsSystemWindows(boolean)
7652     * @see #setSystemUiVisibility(int)
7653     *
7654     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7655     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7656     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7657     * to implement handling their own insets.
7658     */
7659    protected boolean fitSystemWindows(Rect insets) {
7660        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7661            if (insets == null) {
7662                // Null insets by definition have already been consumed.
7663                // This call cannot apply insets since there are none to apply,
7664                // so return false.
7665                return false;
7666            }
7667            // If we're not in the process of dispatching the newer apply insets call,
7668            // that means we're not in the compatibility path. Dispatch into the newer
7669            // apply insets path and take things from there.
7670            try {
7671                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7672                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7673            } finally {
7674                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7675            }
7676        } else {
7677            // We're being called from the newer apply insets path.
7678            // Perform the standard fallback behavior.
7679            return fitSystemWindowsInt(insets);
7680        }
7681    }
7682
7683    private boolean fitSystemWindowsInt(Rect insets) {
7684        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7685            mUserPaddingStart = UNDEFINED_PADDING;
7686            mUserPaddingEnd = UNDEFINED_PADDING;
7687            Rect localInsets = sThreadLocal.get();
7688            if (localInsets == null) {
7689                localInsets = new Rect();
7690                sThreadLocal.set(localInsets);
7691            }
7692            boolean res = computeFitSystemWindows(insets, localInsets);
7693            mUserPaddingLeftInitial = localInsets.left;
7694            mUserPaddingRightInitial = localInsets.right;
7695            internalSetPadding(localInsets.left, localInsets.top,
7696                    localInsets.right, localInsets.bottom);
7697            return res;
7698        }
7699        return false;
7700    }
7701
7702    /**
7703     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7704     *
7705     * <p>This method should be overridden by views that wish to apply a policy different from or
7706     * in addition to the default behavior. Clients that wish to force a view subtree
7707     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7708     *
7709     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7710     * it will be called during dispatch instead of this method. The listener may optionally
7711     * call this method from its own implementation if it wishes to apply the view's default
7712     * insets policy in addition to its own.</p>
7713     *
7714     * <p>Implementations of this method should either return the insets parameter unchanged
7715     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7716     * that this view applied itself. This allows new inset types added in future platform
7717     * versions to pass through existing implementations unchanged without being erroneously
7718     * consumed.</p>
7719     *
7720     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7721     * property is set then the view will consume the system window insets and apply them
7722     * as padding for the view.</p>
7723     *
7724     * @param insets Insets to apply
7725     * @return The supplied insets with any applied insets consumed
7726     */
7727    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7728        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7729            // We weren't called from within a direct call to fitSystemWindows,
7730            // call into it as a fallback in case we're in a class that overrides it
7731            // and has logic to perform.
7732            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7733                return insets.consumeSystemWindowInsets();
7734            }
7735        } else {
7736            // We were called from within a direct call to fitSystemWindows.
7737            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7738                return insets.consumeSystemWindowInsets();
7739            }
7740        }
7741        return insets;
7742    }
7743
7744    /**
7745     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7746     * window insets to this view. The listener's
7747     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7748     * method will be called instead of the view's
7749     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7750     *
7751     * @param listener Listener to set
7752     *
7753     * @see #onApplyWindowInsets(WindowInsets)
7754     */
7755    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7756        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7757    }
7758
7759    /**
7760     * Request to apply the given window insets to this view or another view in its subtree.
7761     *
7762     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7763     * obscured by window decorations or overlays. This can include the status and navigation bars,
7764     * action bars, input methods and more. New inset categories may be added in the future.
7765     * The method returns the insets provided minus any that were applied by this view or its
7766     * children.</p>
7767     *
7768     * <p>Clients wishing to provide custom behavior should override the
7769     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7770     * {@link OnApplyWindowInsetsListener} via the
7771     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7772     * method.</p>
7773     *
7774     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7775     * </p>
7776     *
7777     * @param insets Insets to apply
7778     * @return The provided insets minus the insets that were consumed
7779     */
7780    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7781        try {
7782            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7783            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7784                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7785            } else {
7786                return onApplyWindowInsets(insets);
7787            }
7788        } finally {
7789            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7790        }
7791    }
7792
7793    /**
7794     * Compute the view's coordinate within the surface.
7795     *
7796     * <p>Computes the coordinates of this view in its surface. The argument
7797     * must be an array of two integers. After the method returns, the array
7798     * contains the x and y location in that order.</p>
7799     * @hide
7800     * @param location an array of two integers in which to hold the coordinates
7801     */
7802    public void getLocationInSurface(@Size(2) int[] location) {
7803        getLocationInWindow(location);
7804        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
7805            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
7806            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
7807        }
7808    }
7809
7810    /**
7811     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7812     * only available if the view is attached.
7813     *
7814     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7815     */
7816    public WindowInsets getRootWindowInsets() {
7817        if (mAttachInfo != null) {
7818            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7819        }
7820        return null;
7821    }
7822
7823    /**
7824     * @hide Compute the insets that should be consumed by this view and the ones
7825     * that should propagate to those under it.
7826     */
7827    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7828        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7829                || mAttachInfo == null
7830                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7831                        && !mAttachInfo.mOverscanRequested)) {
7832            outLocalInsets.set(inoutInsets);
7833            inoutInsets.set(0, 0, 0, 0);
7834            return true;
7835        } else {
7836            // The application wants to take care of fitting system window for
7837            // the content...  however we still need to take care of any overscan here.
7838            final Rect overscan = mAttachInfo.mOverscanInsets;
7839            outLocalInsets.set(overscan);
7840            inoutInsets.left -= overscan.left;
7841            inoutInsets.top -= overscan.top;
7842            inoutInsets.right -= overscan.right;
7843            inoutInsets.bottom -= overscan.bottom;
7844            return false;
7845        }
7846    }
7847
7848    /**
7849     * Compute insets that should be consumed by this view and the ones that should propagate
7850     * to those under it.
7851     *
7852     * @param in Insets currently being processed by this View, likely received as a parameter
7853     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7854     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7855     *                       by this view
7856     * @return Insets that should be passed along to views under this one
7857     */
7858    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7859        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7860                || mAttachInfo == null
7861                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7862            outLocalInsets.set(in.getSystemWindowInsets());
7863            return in.consumeSystemWindowInsets();
7864        } else {
7865            outLocalInsets.set(0, 0, 0, 0);
7866            return in;
7867        }
7868    }
7869
7870    /**
7871     * Sets whether or not this view should account for system screen decorations
7872     * such as the status bar and inset its content; that is, controlling whether
7873     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7874     * executed.  See that method for more details.
7875     *
7876     * <p>Note that if you are providing your own implementation of
7877     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7878     * flag to true -- your implementation will be overriding the default
7879     * implementation that checks this flag.
7880     *
7881     * @param fitSystemWindows If true, then the default implementation of
7882     * {@link #fitSystemWindows(Rect)} will be executed.
7883     *
7884     * @attr ref android.R.styleable#View_fitsSystemWindows
7885     * @see #getFitsSystemWindows()
7886     * @see #fitSystemWindows(Rect)
7887     * @see #setSystemUiVisibility(int)
7888     */
7889    public void setFitsSystemWindows(boolean fitSystemWindows) {
7890        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7891    }
7892
7893    /**
7894     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7895     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7896     * will be executed.
7897     *
7898     * @return {@code true} if the default implementation of
7899     * {@link #fitSystemWindows(Rect)} will be executed.
7900     *
7901     * @attr ref android.R.styleable#View_fitsSystemWindows
7902     * @see #setFitsSystemWindows(boolean)
7903     * @see #fitSystemWindows(Rect)
7904     * @see #setSystemUiVisibility(int)
7905     */
7906    @ViewDebug.ExportedProperty
7907    public boolean getFitsSystemWindows() {
7908        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
7909    }
7910
7911    /** @hide */
7912    public boolean fitsSystemWindows() {
7913        return getFitsSystemWindows();
7914    }
7915
7916    /**
7917     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
7918     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
7919     */
7920    public void requestFitSystemWindows() {
7921        if (mParent != null) {
7922            mParent.requestFitSystemWindows();
7923        }
7924    }
7925
7926    /**
7927     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
7928     */
7929    public void requestApplyInsets() {
7930        requestFitSystemWindows();
7931    }
7932
7933    /**
7934     * For use by PhoneWindow to make its own system window fitting optional.
7935     * @hide
7936     */
7937    public void makeOptionalFitsSystemWindows() {
7938        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
7939    }
7940
7941    /**
7942     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
7943     * treat them as such.
7944     * @hide
7945     */
7946    public void getOutsets(Rect outOutsetRect) {
7947        if (mAttachInfo != null) {
7948            outOutsetRect.set(mAttachInfo.mOutsets);
7949        } else {
7950            outOutsetRect.setEmpty();
7951        }
7952    }
7953
7954    /**
7955     * Returns the visibility status for this view.
7956     *
7957     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7958     * @attr ref android.R.styleable#View_visibility
7959     */
7960    @ViewDebug.ExportedProperty(mapping = {
7961        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
7962        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
7963        @ViewDebug.IntToString(from = GONE,      to = "GONE")
7964    })
7965    @Visibility
7966    public int getVisibility() {
7967        return mViewFlags & VISIBILITY_MASK;
7968    }
7969
7970    /**
7971     * Set the enabled state of this view.
7972     *
7973     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7974     * @attr ref android.R.styleable#View_visibility
7975     */
7976    @RemotableViewMethod
7977    public void setVisibility(@Visibility int visibility) {
7978        setFlags(visibility, VISIBILITY_MASK);
7979    }
7980
7981    /**
7982     * Returns the enabled status for this view. The interpretation of the
7983     * enabled state varies by subclass.
7984     *
7985     * @return True if this view is enabled, false otherwise.
7986     */
7987    @ViewDebug.ExportedProperty
7988    public boolean isEnabled() {
7989        return (mViewFlags & ENABLED_MASK) == ENABLED;
7990    }
7991
7992    /**
7993     * Set the enabled state of this view. The interpretation of the enabled
7994     * state varies by subclass.
7995     *
7996     * @param enabled True if this view is enabled, false otherwise.
7997     */
7998    @RemotableViewMethod
7999    public void setEnabled(boolean enabled) {
8000        if (enabled == isEnabled()) return;
8001
8002        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8003
8004        /*
8005         * The View most likely has to change its appearance, so refresh
8006         * the drawable state.
8007         */
8008        refreshDrawableState();
8009
8010        // Invalidate too, since the default behavior for views is to be
8011        // be drawn at 50% alpha rather than to change the drawable.
8012        invalidate(true);
8013
8014        if (!enabled) {
8015            cancelPendingInputEvents();
8016        }
8017    }
8018
8019    /**
8020     * Set whether this view can receive the focus.
8021     *
8022     * Setting this to false will also ensure that this view is not focusable
8023     * in touch mode.
8024     *
8025     * @param focusable If true, this view can receive the focus.
8026     *
8027     * @see #setFocusableInTouchMode(boolean)
8028     * @attr ref android.R.styleable#View_focusable
8029     */
8030    public void setFocusable(boolean focusable) {
8031        if (!focusable) {
8032            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8033        }
8034        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8035    }
8036
8037    /**
8038     * Set whether this view can receive focus while in touch mode.
8039     *
8040     * Setting this to true will also ensure that this view is focusable.
8041     *
8042     * @param focusableInTouchMode If true, this view can receive the focus while
8043     *   in touch mode.
8044     *
8045     * @see #setFocusable(boolean)
8046     * @attr ref android.R.styleable#View_focusableInTouchMode
8047     */
8048    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8049        // Focusable in touch mode should always be set before the focusable flag
8050        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8051        // which, in touch mode, will not successfully request focus on this view
8052        // because the focusable in touch mode flag is not set
8053        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8054        if (focusableInTouchMode) {
8055            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8056        }
8057    }
8058
8059    /**
8060     * Set whether this view should have sound effects enabled for events such as
8061     * clicking and touching.
8062     *
8063     * <p>You may wish to disable sound effects for a view if you already play sounds,
8064     * for instance, a dial key that plays dtmf tones.
8065     *
8066     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8067     * @see #isSoundEffectsEnabled()
8068     * @see #playSoundEffect(int)
8069     * @attr ref android.R.styleable#View_soundEffectsEnabled
8070     */
8071    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8072        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8073    }
8074
8075    /**
8076     * @return whether this view should have sound effects enabled for events such as
8077     *     clicking and touching.
8078     *
8079     * @see #setSoundEffectsEnabled(boolean)
8080     * @see #playSoundEffect(int)
8081     * @attr ref android.R.styleable#View_soundEffectsEnabled
8082     */
8083    @ViewDebug.ExportedProperty
8084    public boolean isSoundEffectsEnabled() {
8085        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8086    }
8087
8088    /**
8089     * Set whether this view should have haptic feedback for events such as
8090     * long presses.
8091     *
8092     * <p>You may wish to disable haptic feedback if your view already controls
8093     * its own haptic feedback.
8094     *
8095     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8096     * @see #isHapticFeedbackEnabled()
8097     * @see #performHapticFeedback(int)
8098     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8099     */
8100    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8101        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8102    }
8103
8104    /**
8105     * @return whether this view should have haptic feedback enabled for events
8106     * long presses.
8107     *
8108     * @see #setHapticFeedbackEnabled(boolean)
8109     * @see #performHapticFeedback(int)
8110     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8111     */
8112    @ViewDebug.ExportedProperty
8113    public boolean isHapticFeedbackEnabled() {
8114        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8115    }
8116
8117    /**
8118     * Returns the layout direction for this view.
8119     *
8120     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8121     *   {@link #LAYOUT_DIRECTION_RTL},
8122     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8123     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8124     *
8125     * @attr ref android.R.styleable#View_layoutDirection
8126     *
8127     * @hide
8128     */
8129    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8130        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8131        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8132        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8133        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8134    })
8135    @LayoutDir
8136    public int getRawLayoutDirection() {
8137        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8138    }
8139
8140    /**
8141     * Set the layout direction for this view. This will propagate a reset of layout direction
8142     * resolution to the view's children and resolve layout direction for this view.
8143     *
8144     * @param layoutDirection the layout direction to set. Should be one of:
8145     *
8146     * {@link #LAYOUT_DIRECTION_LTR},
8147     * {@link #LAYOUT_DIRECTION_RTL},
8148     * {@link #LAYOUT_DIRECTION_INHERIT},
8149     * {@link #LAYOUT_DIRECTION_LOCALE}.
8150     *
8151     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8152     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8153     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8154     *
8155     * @attr ref android.R.styleable#View_layoutDirection
8156     */
8157    @RemotableViewMethod
8158    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8159        if (getRawLayoutDirection() != layoutDirection) {
8160            // Reset the current layout direction and the resolved one
8161            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8162            resetRtlProperties();
8163            // Set the new layout direction (filtered)
8164            mPrivateFlags2 |=
8165                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8166            // We need to resolve all RTL properties as they all depend on layout direction
8167            resolveRtlPropertiesIfNeeded();
8168            requestLayout();
8169            invalidate(true);
8170        }
8171    }
8172
8173    /**
8174     * Returns the resolved layout direction for this view.
8175     *
8176     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8177     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8178     *
8179     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8180     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8181     *
8182     * @attr ref android.R.styleable#View_layoutDirection
8183     */
8184    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8185        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8186        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8187    })
8188    @ResolvedLayoutDir
8189    public int getLayoutDirection() {
8190        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8191        if (targetSdkVersion < JELLY_BEAN_MR1) {
8192            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8193            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8194        }
8195        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8196                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8197    }
8198
8199    /**
8200     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8201     * layout attribute and/or the inherited value from the parent
8202     *
8203     * @return true if the layout is right-to-left.
8204     *
8205     * @hide
8206     */
8207    @ViewDebug.ExportedProperty(category = "layout")
8208    public boolean isLayoutRtl() {
8209        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8210    }
8211
8212    /**
8213     * Indicates whether the view is currently tracking transient state that the
8214     * app should not need to concern itself with saving and restoring, but that
8215     * the framework should take special note to preserve when possible.
8216     *
8217     * <p>A view with transient state cannot be trivially rebound from an external
8218     * data source, such as an adapter binding item views in a list. This may be
8219     * because the view is performing an animation, tracking user selection
8220     * of content, or similar.</p>
8221     *
8222     * @return true if the view has transient state
8223     */
8224    @ViewDebug.ExportedProperty(category = "layout")
8225    public boolean hasTransientState() {
8226        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8227    }
8228
8229    /**
8230     * Set whether this view is currently tracking transient state that the
8231     * framework should attempt to preserve when possible. This flag is reference counted,
8232     * so every call to setHasTransientState(true) should be paired with a later call
8233     * to setHasTransientState(false).
8234     *
8235     * <p>A view with transient state cannot be trivially rebound from an external
8236     * data source, such as an adapter binding item views in a list. This may be
8237     * because the view is performing an animation, tracking user selection
8238     * of content, or similar.</p>
8239     *
8240     * @param hasTransientState true if this view has transient state
8241     */
8242    public void setHasTransientState(boolean hasTransientState) {
8243        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8244                mTransientStateCount - 1;
8245        if (mTransientStateCount < 0) {
8246            mTransientStateCount = 0;
8247            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8248                    "unmatched pair of setHasTransientState calls");
8249        } else if ((hasTransientState && mTransientStateCount == 1) ||
8250                (!hasTransientState && mTransientStateCount == 0)) {
8251            // update flag if we've just incremented up from 0 or decremented down to 0
8252            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8253                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8254            if (mParent != null) {
8255                try {
8256                    mParent.childHasTransientStateChanged(this, hasTransientState);
8257                } catch (AbstractMethodError e) {
8258                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8259                            " does not fully implement ViewParent", e);
8260                }
8261            }
8262        }
8263    }
8264
8265    /**
8266     * Returns true if this view is currently attached to a window.
8267     */
8268    public boolean isAttachedToWindow() {
8269        return mAttachInfo != null;
8270    }
8271
8272    /**
8273     * Returns true if this view has been through at least one layout since it
8274     * was last attached to or detached from a window.
8275     */
8276    public boolean isLaidOut() {
8277        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8278    }
8279
8280    /**
8281     * If this view doesn't do any drawing on its own, set this flag to
8282     * allow further optimizations. By default, this flag is not set on
8283     * View, but could be set on some View subclasses such as ViewGroup.
8284     *
8285     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8286     * you should clear this flag.
8287     *
8288     * @param willNotDraw whether or not this View draw on its own
8289     */
8290    public void setWillNotDraw(boolean willNotDraw) {
8291        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8292    }
8293
8294    /**
8295     * Returns whether or not this View draws on its own.
8296     *
8297     * @return true if this view has nothing to draw, false otherwise
8298     */
8299    @ViewDebug.ExportedProperty(category = "drawing")
8300    public boolean willNotDraw() {
8301        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8302    }
8303
8304    /**
8305     * When a View's drawing cache is enabled, drawing is redirected to an
8306     * offscreen bitmap. Some views, like an ImageView, must be able to
8307     * bypass this mechanism if they already draw a single bitmap, to avoid
8308     * unnecessary usage of the memory.
8309     *
8310     * @param willNotCacheDrawing true if this view does not cache its
8311     *        drawing, false otherwise
8312     */
8313    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8314        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8315    }
8316
8317    /**
8318     * Returns whether or not this View can cache its drawing or not.
8319     *
8320     * @return true if this view does not cache its drawing, false otherwise
8321     */
8322    @ViewDebug.ExportedProperty(category = "drawing")
8323    public boolean willNotCacheDrawing() {
8324        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8325    }
8326
8327    /**
8328     * Indicates whether this view reacts to click events or not.
8329     *
8330     * @return true if the view is clickable, false otherwise
8331     *
8332     * @see #setClickable(boolean)
8333     * @attr ref android.R.styleable#View_clickable
8334     */
8335    @ViewDebug.ExportedProperty
8336    public boolean isClickable() {
8337        return (mViewFlags & CLICKABLE) == CLICKABLE;
8338    }
8339
8340    /**
8341     * Enables or disables click events for this view. When a view
8342     * is clickable it will change its state to "pressed" on every click.
8343     * Subclasses should set the view clickable to visually react to
8344     * user's clicks.
8345     *
8346     * @param clickable true to make the view clickable, false otherwise
8347     *
8348     * @see #isClickable()
8349     * @attr ref android.R.styleable#View_clickable
8350     */
8351    public void setClickable(boolean clickable) {
8352        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8353    }
8354
8355    /**
8356     * Indicates whether this view reacts to long click events or not.
8357     *
8358     * @return true if the view is long clickable, false otherwise
8359     *
8360     * @see #setLongClickable(boolean)
8361     * @attr ref android.R.styleable#View_longClickable
8362     */
8363    public boolean isLongClickable() {
8364        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8365    }
8366
8367    /**
8368     * Enables or disables long click events for this view. When a view is long
8369     * clickable it reacts to the user holding down the button for a longer
8370     * duration than a tap. This event can either launch the listener or a
8371     * context menu.
8372     *
8373     * @param longClickable true to make the view long clickable, false otherwise
8374     * @see #isLongClickable()
8375     * @attr ref android.R.styleable#View_longClickable
8376     */
8377    public void setLongClickable(boolean longClickable) {
8378        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8379    }
8380
8381    /**
8382     * Indicates whether this view reacts to context clicks or not.
8383     *
8384     * @return true if the view is context clickable, false otherwise
8385     * @see #setContextClickable(boolean)
8386     * @attr ref android.R.styleable#View_contextClickable
8387     */
8388    public boolean isContextClickable() {
8389        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8390    }
8391
8392    /**
8393     * Enables or disables context clicking for this view. This event can launch the listener.
8394     *
8395     * @param contextClickable true to make the view react to a context click, false otherwise
8396     * @see #isContextClickable()
8397     * @attr ref android.R.styleable#View_contextClickable
8398     */
8399    public void setContextClickable(boolean contextClickable) {
8400        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8401    }
8402
8403    /**
8404     * Sets the pressed state for this view and provides a touch coordinate for
8405     * animation hinting.
8406     *
8407     * @param pressed Pass true to set the View's internal state to "pressed",
8408     *            or false to reverts the View's internal state from a
8409     *            previously set "pressed" state.
8410     * @param x The x coordinate of the touch that caused the press
8411     * @param y The y coordinate of the touch that caused the press
8412     */
8413    private void setPressed(boolean pressed, float x, float y) {
8414        if (pressed) {
8415            drawableHotspotChanged(x, y);
8416        }
8417
8418        setPressed(pressed);
8419    }
8420
8421    /**
8422     * Sets the pressed state for this view.
8423     *
8424     * @see #isClickable()
8425     * @see #setClickable(boolean)
8426     *
8427     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8428     *        the View's internal state from a previously set "pressed" state.
8429     */
8430    public void setPressed(boolean pressed) {
8431        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8432
8433        if (pressed) {
8434            mPrivateFlags |= PFLAG_PRESSED;
8435        } else {
8436            mPrivateFlags &= ~PFLAG_PRESSED;
8437        }
8438
8439        if (needsRefresh) {
8440            refreshDrawableState();
8441        }
8442        dispatchSetPressed(pressed);
8443    }
8444
8445    /**
8446     * Dispatch setPressed to all of this View's children.
8447     *
8448     * @see #setPressed(boolean)
8449     *
8450     * @param pressed The new pressed state
8451     */
8452    protected void dispatchSetPressed(boolean pressed) {
8453    }
8454
8455    /**
8456     * Indicates whether the view is currently in pressed state. Unless
8457     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8458     * the pressed state.
8459     *
8460     * @see #setPressed(boolean)
8461     * @see #isClickable()
8462     * @see #setClickable(boolean)
8463     *
8464     * @return true if the view is currently pressed, false otherwise
8465     */
8466    @ViewDebug.ExportedProperty
8467    public boolean isPressed() {
8468        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8469    }
8470
8471    /**
8472     * @hide
8473     * Indicates whether this view will participate in data collection through
8474     * {@link ViewStructure}.  If true, it will not provide any data
8475     * for itself or its children.  If false, the normal data collection will be allowed.
8476     *
8477     * @return Returns false if assist data collection is not blocked, else true.
8478     *
8479     * @see #setAssistBlocked(boolean)
8480     * @attr ref android.R.styleable#View_assistBlocked
8481     */
8482    public boolean isAssistBlocked() {
8483        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8484    }
8485
8486    /**
8487     * @hide
8488     * Controls whether assist data collection from this view and its children is enabled
8489     * (that is, whether {@link #onProvideStructure} and
8490     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8491     * allowing normal assist collection.  Setting this to false will disable assist collection.
8492     *
8493     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8494     * (the default) to allow it.
8495     *
8496     * @see #isAssistBlocked()
8497     * @see #onProvideStructure
8498     * @see #onProvideVirtualStructure
8499     * @attr ref android.R.styleable#View_assistBlocked
8500     */
8501    public void setAssistBlocked(boolean enabled) {
8502        if (enabled) {
8503            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8504        } else {
8505            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
8506        }
8507    }
8508
8509    /**
8510     * Indicates whether this view will save its state (that is,
8511     * whether its {@link #onSaveInstanceState} method will be called).
8512     *
8513     * @return Returns true if the view state saving is enabled, else false.
8514     *
8515     * @see #setSaveEnabled(boolean)
8516     * @attr ref android.R.styleable#View_saveEnabled
8517     */
8518    public boolean isSaveEnabled() {
8519        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
8520    }
8521
8522    /**
8523     * Controls whether the saving of this view's state is
8524     * enabled (that is, whether its {@link #onSaveInstanceState} method
8525     * will be called).  Note that even if freezing is enabled, the
8526     * view still must have an id assigned to it (via {@link #setId(int)})
8527     * for its state to be saved.  This flag can only disable the
8528     * saving of this view; any child views may still have their state saved.
8529     *
8530     * @param enabled Set to false to <em>disable</em> state saving, or true
8531     * (the default) to allow it.
8532     *
8533     * @see #isSaveEnabled()
8534     * @see #setId(int)
8535     * @see #onSaveInstanceState()
8536     * @attr ref android.R.styleable#View_saveEnabled
8537     */
8538    public void setSaveEnabled(boolean enabled) {
8539        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
8540    }
8541
8542    /**
8543     * Gets whether the framework should discard touches when the view's
8544     * window is obscured by another visible window.
8545     * Refer to the {@link View} security documentation for more details.
8546     *
8547     * @return True if touch filtering is enabled.
8548     *
8549     * @see #setFilterTouchesWhenObscured(boolean)
8550     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8551     */
8552    @ViewDebug.ExportedProperty
8553    public boolean getFilterTouchesWhenObscured() {
8554        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8555    }
8556
8557    /**
8558     * Sets whether the framework should discard touches when the view's
8559     * window is obscured by another visible window.
8560     * Refer to the {@link View} security documentation for more details.
8561     *
8562     * @param enabled True if touch filtering should be enabled.
8563     *
8564     * @see #getFilterTouchesWhenObscured
8565     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8566     */
8567    public void setFilterTouchesWhenObscured(boolean enabled) {
8568        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8569                FILTER_TOUCHES_WHEN_OBSCURED);
8570    }
8571
8572    /**
8573     * Indicates whether the entire hierarchy under this view will save its
8574     * state when a state saving traversal occurs from its parent.  The default
8575     * is true; if false, these views will not be saved unless
8576     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8577     *
8578     * @return Returns true if the view state saving from parent is enabled, else false.
8579     *
8580     * @see #setSaveFromParentEnabled(boolean)
8581     */
8582    public boolean isSaveFromParentEnabled() {
8583        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8584    }
8585
8586    /**
8587     * Controls whether the entire hierarchy under this view will save its
8588     * state when a state saving traversal occurs from its parent.  The default
8589     * is true; if false, these views will not be saved unless
8590     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8591     *
8592     * @param enabled Set to false to <em>disable</em> state saving, or true
8593     * (the default) to allow it.
8594     *
8595     * @see #isSaveFromParentEnabled()
8596     * @see #setId(int)
8597     * @see #onSaveInstanceState()
8598     */
8599    public void setSaveFromParentEnabled(boolean enabled) {
8600        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8601    }
8602
8603
8604    /**
8605     * Returns whether this View is able to take focus.
8606     *
8607     * @return True if this view can take focus, or false otherwise.
8608     * @attr ref android.R.styleable#View_focusable
8609     */
8610    @ViewDebug.ExportedProperty(category = "focus")
8611    public final boolean isFocusable() {
8612        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8613    }
8614
8615    /**
8616     * When a view is focusable, it may not want to take focus when in touch mode.
8617     * For example, a button would like focus when the user is navigating via a D-pad
8618     * so that the user can click on it, but once the user starts touching the screen,
8619     * the button shouldn't take focus
8620     * @return Whether the view is focusable in touch mode.
8621     * @attr ref android.R.styleable#View_focusableInTouchMode
8622     */
8623    @ViewDebug.ExportedProperty
8624    public final boolean isFocusableInTouchMode() {
8625        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8626    }
8627
8628    /**
8629     * Find the nearest view in the specified direction that can take focus.
8630     * This does not actually give focus to that view.
8631     *
8632     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8633     *
8634     * @return The nearest focusable in the specified direction, or null if none
8635     *         can be found.
8636     */
8637    public View focusSearch(@FocusRealDirection int direction) {
8638        if (mParent != null) {
8639            return mParent.focusSearch(this, direction);
8640        } else {
8641            return null;
8642        }
8643    }
8644
8645    /**
8646     * This method is the last chance for the focused view and its ancestors to
8647     * respond to an arrow key. This is called when the focused view did not
8648     * consume the key internally, nor could the view system find a new view in
8649     * the requested direction to give focus to.
8650     *
8651     * @param focused The currently focused view.
8652     * @param direction The direction focus wants to move. One of FOCUS_UP,
8653     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8654     * @return True if the this view consumed this unhandled move.
8655     */
8656    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8657        return false;
8658    }
8659
8660    /**
8661     * If a user manually specified the next view id for a particular direction,
8662     * use the root to look up the view.
8663     * @param root The root view of the hierarchy containing this view.
8664     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8665     * or FOCUS_BACKWARD.
8666     * @return The user specified next view, or null if there is none.
8667     */
8668    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8669        switch (direction) {
8670            case FOCUS_LEFT:
8671                if (mNextFocusLeftId == View.NO_ID) return null;
8672                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8673            case FOCUS_RIGHT:
8674                if (mNextFocusRightId == View.NO_ID) return null;
8675                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8676            case FOCUS_UP:
8677                if (mNextFocusUpId == View.NO_ID) return null;
8678                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8679            case FOCUS_DOWN:
8680                if (mNextFocusDownId == View.NO_ID) return null;
8681                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8682            case FOCUS_FORWARD:
8683                if (mNextFocusForwardId == View.NO_ID) return null;
8684                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8685            case FOCUS_BACKWARD: {
8686                if (mID == View.NO_ID) return null;
8687                final int id = mID;
8688                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8689                    @Override
8690                    public boolean apply(View t) {
8691                        return t.mNextFocusForwardId == id;
8692                    }
8693                });
8694            }
8695        }
8696        return null;
8697    }
8698
8699    private View findViewInsideOutShouldExist(View root, int id) {
8700        if (mMatchIdPredicate == null) {
8701            mMatchIdPredicate = new MatchIdPredicate();
8702        }
8703        mMatchIdPredicate.mId = id;
8704        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8705        if (result == null) {
8706            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8707        }
8708        return result;
8709    }
8710
8711    /**
8712     * Find and return all focusable views that are descendants of this view,
8713     * possibly including this view if it is focusable itself.
8714     *
8715     * @param direction The direction of the focus
8716     * @return A list of focusable views
8717     */
8718    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8719        ArrayList<View> result = new ArrayList<View>(24);
8720        addFocusables(result, direction);
8721        return result;
8722    }
8723
8724    /**
8725     * Add any focusable views that are descendants of this view (possibly
8726     * including this view if it is focusable itself) to views.  If we are in touch mode,
8727     * only add views that are also focusable in touch mode.
8728     *
8729     * @param views Focusable views found so far
8730     * @param direction The direction of the focus
8731     */
8732    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8733        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
8734    }
8735
8736    /**
8737     * Adds any focusable views that are descendants of this view (possibly
8738     * including this view if it is focusable itself) to views. This method
8739     * adds all focusable views regardless if we are in touch mode or
8740     * only views focusable in touch mode if we are in touch mode or
8741     * only views that can take accessibility focus if accessibility is enabled
8742     * depending on the focusable mode parameter.
8743     *
8744     * @param views Focusable views found so far or null if all we are interested is
8745     *        the number of focusables.
8746     * @param direction The direction of the focus.
8747     * @param focusableMode The type of focusables to be added.
8748     *
8749     * @see #FOCUSABLES_ALL
8750     * @see #FOCUSABLES_TOUCH_MODE
8751     */
8752    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8753            @FocusableMode int focusableMode) {
8754        if (views == null) {
8755            return;
8756        }
8757        if (!isFocusable()) {
8758            return;
8759        }
8760        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8761                && isInTouchMode() && !isFocusableInTouchMode()) {
8762            return;
8763        }
8764        views.add(this);
8765    }
8766
8767    /**
8768     * Finds the Views that contain given text. The containment is case insensitive.
8769     * The search is performed by either the text that the View renders or the content
8770     * description that describes the view for accessibility purposes and the view does
8771     * not render or both. Clients can specify how the search is to be performed via
8772     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8773     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8774     *
8775     * @param outViews The output list of matching Views.
8776     * @param searched The text to match against.
8777     *
8778     * @see #FIND_VIEWS_WITH_TEXT
8779     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8780     * @see #setContentDescription(CharSequence)
8781     */
8782    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8783            @FindViewFlags int flags) {
8784        if (getAccessibilityNodeProvider() != null) {
8785            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8786                outViews.add(this);
8787            }
8788        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8789                && (searched != null && searched.length() > 0)
8790                && (mContentDescription != null && mContentDescription.length() > 0)) {
8791            String searchedLowerCase = searched.toString().toLowerCase();
8792            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8793            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8794                outViews.add(this);
8795            }
8796        }
8797    }
8798
8799    /**
8800     * Find and return all touchable views that are descendants of this view,
8801     * possibly including this view if it is touchable itself.
8802     *
8803     * @return A list of touchable views
8804     */
8805    public ArrayList<View> getTouchables() {
8806        ArrayList<View> result = new ArrayList<View>();
8807        addTouchables(result);
8808        return result;
8809    }
8810
8811    /**
8812     * Add any touchable views that are descendants of this view (possibly
8813     * including this view if it is touchable itself) to views.
8814     *
8815     * @param views Touchable views found so far
8816     */
8817    public void addTouchables(ArrayList<View> views) {
8818        final int viewFlags = mViewFlags;
8819
8820        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8821                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8822                && (viewFlags & ENABLED_MASK) == ENABLED) {
8823            views.add(this);
8824        }
8825    }
8826
8827    /**
8828     * Returns whether this View is accessibility focused.
8829     *
8830     * @return True if this View is accessibility focused.
8831     */
8832    public boolean isAccessibilityFocused() {
8833        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8834    }
8835
8836    /**
8837     * Call this to try to give accessibility focus to this view.
8838     *
8839     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8840     * returns false or the view is no visible or the view already has accessibility
8841     * focus.
8842     *
8843     * See also {@link #focusSearch(int)}, which is what you call to say that you
8844     * have focus, and you want your parent to look for the next one.
8845     *
8846     * @return Whether this view actually took accessibility focus.
8847     *
8848     * @hide
8849     */
8850    public boolean requestAccessibilityFocus() {
8851        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8852        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8853            return false;
8854        }
8855        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8856            return false;
8857        }
8858        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8859            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8860            ViewRootImpl viewRootImpl = getViewRootImpl();
8861            if (viewRootImpl != null) {
8862                viewRootImpl.setAccessibilityFocus(this, null);
8863            }
8864            invalidate();
8865            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8866            return true;
8867        }
8868        return false;
8869    }
8870
8871    /**
8872     * Call this to try to clear accessibility focus of this view.
8873     *
8874     * See also {@link #focusSearch(int)}, which is what you call to say that you
8875     * have focus, and you want your parent to look for the next one.
8876     *
8877     * @hide
8878     */
8879    public void clearAccessibilityFocus() {
8880        clearAccessibilityFocusNoCallbacks(0);
8881
8882        // Clear the global reference of accessibility focus if this view or
8883        // any of its descendants had accessibility focus. This will NOT send
8884        // an event or update internal state if focus is cleared from a
8885        // descendant view, which may leave views in inconsistent states.
8886        final ViewRootImpl viewRootImpl = getViewRootImpl();
8887        if (viewRootImpl != null) {
8888            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8889            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8890                viewRootImpl.setAccessibilityFocus(null, null);
8891            }
8892        }
8893    }
8894
8895    private void sendAccessibilityHoverEvent(int eventType) {
8896        // Since we are not delivering to a client accessibility events from not
8897        // important views (unless the clinet request that) we need to fire the
8898        // event from the deepest view exposed to the client. As a consequence if
8899        // the user crosses a not exposed view the client will see enter and exit
8900        // of the exposed predecessor followed by and enter and exit of that same
8901        // predecessor when entering and exiting the not exposed descendant. This
8902        // is fine since the client has a clear idea which view is hovered at the
8903        // price of a couple more events being sent. This is a simple and
8904        // working solution.
8905        View source = this;
8906        while (true) {
8907            if (source.includeForAccessibility()) {
8908                source.sendAccessibilityEvent(eventType);
8909                return;
8910            }
8911            ViewParent parent = source.getParent();
8912            if (parent instanceof View) {
8913                source = (View) parent;
8914            } else {
8915                return;
8916            }
8917        }
8918    }
8919
8920    /**
8921     * Clears accessibility focus without calling any callback methods
8922     * normally invoked in {@link #clearAccessibilityFocus()}. This method
8923     * is used separately from that one for clearing accessibility focus when
8924     * giving this focus to another view.
8925     *
8926     * @param action The action, if any, that led to focus being cleared. Set to
8927     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
8928     * the window.
8929     */
8930    void clearAccessibilityFocusNoCallbacks(int action) {
8931        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
8932            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
8933            invalidate();
8934            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8935                AccessibilityEvent event = AccessibilityEvent.obtain(
8936                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
8937                event.setAction(action);
8938                if (mAccessibilityDelegate != null) {
8939                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
8940                } else {
8941                    sendAccessibilityEventUnchecked(event);
8942                }
8943            }
8944        }
8945    }
8946
8947    /**
8948     * Call this to try to give focus to a specific view or to one of its
8949     * descendants.
8950     *
8951     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8952     * false), or if it is focusable and it is not focusable in touch mode
8953     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8954     *
8955     * See also {@link #focusSearch(int)}, which is what you call to say that you
8956     * have focus, and you want your parent to look for the next one.
8957     *
8958     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
8959     * {@link #FOCUS_DOWN} and <code>null</code>.
8960     *
8961     * @return Whether this view or one of its descendants actually took focus.
8962     */
8963    public final boolean requestFocus() {
8964        return requestFocus(View.FOCUS_DOWN);
8965    }
8966
8967    /**
8968     * Call this to try to give focus to a specific view or to one of its
8969     * descendants and give it a hint about what direction focus is heading.
8970     *
8971     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8972     * false), or if it is focusable and it is not focusable in touch mode
8973     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8974     *
8975     * See also {@link #focusSearch(int)}, which is what you call to say that you
8976     * have focus, and you want your parent to look for the next one.
8977     *
8978     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
8979     * <code>null</code> set for the previously focused rectangle.
8980     *
8981     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8982     * @return Whether this view or one of its descendants actually took focus.
8983     */
8984    public final boolean requestFocus(int direction) {
8985        return requestFocus(direction, null);
8986    }
8987
8988    /**
8989     * Call this to try to give focus to a specific view or to one of its descendants
8990     * and give it hints about the direction and a specific rectangle that the focus
8991     * is coming from.  The rectangle can help give larger views a finer grained hint
8992     * about where focus is coming from, and therefore, where to show selection, or
8993     * forward focus change internally.
8994     *
8995     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8996     * false), or if it is focusable and it is not focusable in touch mode
8997     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8998     *
8999     * A View will not take focus if it is not visible.
9000     *
9001     * A View will not take focus if one of its parents has
9002     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9003     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9004     *
9005     * See also {@link #focusSearch(int)}, which is what you call to say that you
9006     * have focus, and you want your parent to look for the next one.
9007     *
9008     * You may wish to override this method if your custom {@link View} has an internal
9009     * {@link View} that it wishes to forward the request to.
9010     *
9011     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9012     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9013     *        to give a finer grained hint about where focus is coming from.  May be null
9014     *        if there is no hint.
9015     * @return Whether this view or one of its descendants actually took focus.
9016     */
9017    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9018        return requestFocusNoSearch(direction, previouslyFocusedRect);
9019    }
9020
9021    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9022        // need to be focusable
9023        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9024                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9025            return false;
9026        }
9027
9028        // need to be focusable in touch mode if in touch mode
9029        if (isInTouchMode() &&
9030            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9031               return false;
9032        }
9033
9034        // need to not have any parents blocking us
9035        if (hasAncestorThatBlocksDescendantFocus()) {
9036            return false;
9037        }
9038
9039        handleFocusGainInternal(direction, previouslyFocusedRect);
9040        return true;
9041    }
9042
9043    /**
9044     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9045     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9046     * touch mode to request focus when they are touched.
9047     *
9048     * @return Whether this view or one of its descendants actually took focus.
9049     *
9050     * @see #isInTouchMode()
9051     *
9052     */
9053    public final boolean requestFocusFromTouch() {
9054        // Leave touch mode if we need to
9055        if (isInTouchMode()) {
9056            ViewRootImpl viewRoot = getViewRootImpl();
9057            if (viewRoot != null) {
9058                viewRoot.ensureTouchMode(false);
9059            }
9060        }
9061        return requestFocus(View.FOCUS_DOWN);
9062    }
9063
9064    /**
9065     * @return Whether any ancestor of this view blocks descendant focus.
9066     */
9067    private boolean hasAncestorThatBlocksDescendantFocus() {
9068        final boolean focusableInTouchMode = isFocusableInTouchMode();
9069        ViewParent ancestor = mParent;
9070        while (ancestor instanceof ViewGroup) {
9071            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9072            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9073                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9074                return true;
9075            } else {
9076                ancestor = vgAncestor.getParent();
9077            }
9078        }
9079        return false;
9080    }
9081
9082    /**
9083     * Gets the mode for determining whether this View is important for accessibility
9084     * which is if it fires accessibility events and if it is reported to
9085     * accessibility services that query the screen.
9086     *
9087     * @return The mode for determining whether a View is important for accessibility.
9088     *
9089     * @attr ref android.R.styleable#View_importantForAccessibility
9090     *
9091     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9092     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9093     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9094     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9095     */
9096    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9097            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9098            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9099            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9100            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9101                    to = "noHideDescendants")
9102        })
9103    public int getImportantForAccessibility() {
9104        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9105                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9106    }
9107
9108    /**
9109     * Sets the live region mode for this view. This indicates to accessibility
9110     * services whether they should automatically notify the user about changes
9111     * to the view's content description or text, or to the content descriptions
9112     * or text of the view's children (where applicable).
9113     * <p>
9114     * For example, in a login screen with a TextView that displays an "incorrect
9115     * password" notification, that view should be marked as a live region with
9116     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9117     * <p>
9118     * To disable change notifications for this view, use
9119     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9120     * mode for most views.
9121     * <p>
9122     * To indicate that the user should be notified of changes, use
9123     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9124     * <p>
9125     * If the view's changes should interrupt ongoing speech and notify the user
9126     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9127     *
9128     * @param mode The live region mode for this view, one of:
9129     *        <ul>
9130     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9131     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9132     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9133     *        </ul>
9134     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9135     */
9136    public void setAccessibilityLiveRegion(int mode) {
9137        if (mode != getAccessibilityLiveRegion()) {
9138            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9139            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9140                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9141            notifyViewAccessibilityStateChangedIfNeeded(
9142                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9143        }
9144    }
9145
9146    /**
9147     * Gets the live region mode for this View.
9148     *
9149     * @return The live region mode for the view.
9150     *
9151     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9152     *
9153     * @see #setAccessibilityLiveRegion(int)
9154     */
9155    public int getAccessibilityLiveRegion() {
9156        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9157                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9158    }
9159
9160    /**
9161     * Sets how to determine whether this view is important for accessibility
9162     * which is if it fires accessibility events and if it is reported to
9163     * accessibility services that query the screen.
9164     *
9165     * @param mode How to determine whether this view is important for accessibility.
9166     *
9167     * @attr ref android.R.styleable#View_importantForAccessibility
9168     *
9169     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9170     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9171     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9172     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9173     */
9174    public void setImportantForAccessibility(int mode) {
9175        final int oldMode = getImportantForAccessibility();
9176        if (mode != oldMode) {
9177            final boolean hideDescendants =
9178                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9179
9180            // If this node or its descendants are no longer important, try to
9181            // clear accessibility focus.
9182            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9183                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9184                if (focusHost != null) {
9185                    focusHost.clearAccessibilityFocus();
9186                }
9187            }
9188
9189            // If we're moving between AUTO and another state, we might not need
9190            // to send a subtree changed notification. We'll store the computed
9191            // importance, since we'll need to check it later to make sure.
9192            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9193                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9194            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9195            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9196            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9197                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9198            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9199                notifySubtreeAccessibilityStateChangedIfNeeded();
9200            } else {
9201                notifyViewAccessibilityStateChangedIfNeeded(
9202                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9203            }
9204        }
9205    }
9206
9207    /**
9208     * Returns the view within this view's hierarchy that is hosting
9209     * accessibility focus.
9210     *
9211     * @param searchDescendants whether to search for focus in descendant views
9212     * @return the view hosting accessibility focus, or {@code null}
9213     */
9214    private View findAccessibilityFocusHost(boolean searchDescendants) {
9215        if (isAccessibilityFocusedViewOrHost()) {
9216            return this;
9217        }
9218
9219        if (searchDescendants) {
9220            final ViewRootImpl viewRoot = getViewRootImpl();
9221            if (viewRoot != null) {
9222                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9223                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9224                    return focusHost;
9225                }
9226            }
9227        }
9228
9229        return null;
9230    }
9231
9232    /**
9233     * Computes whether this view should be exposed for accessibility. In
9234     * general, views that are interactive or provide information are exposed
9235     * while views that serve only as containers are hidden.
9236     * <p>
9237     * If an ancestor of this view has importance
9238     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9239     * returns <code>false</code>.
9240     * <p>
9241     * Otherwise, the value is computed according to the view's
9242     * {@link #getImportantForAccessibility()} value:
9243     * <ol>
9244     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9245     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9246     * </code>
9247     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9248     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9249     * view satisfies any of the following:
9250     * <ul>
9251     * <li>Is actionable, e.g. {@link #isClickable()},
9252     * {@link #isLongClickable()}, or {@link #isFocusable()}
9253     * <li>Has an {@link AccessibilityDelegate}
9254     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9255     * {@link OnKeyListener}, etc.
9256     * <li>Is an accessibility live region, e.g.
9257     * {@link #getAccessibilityLiveRegion()} is not
9258     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9259     * </ul>
9260     * </ol>
9261     *
9262     * @return Whether the view is exposed for accessibility.
9263     * @see #setImportantForAccessibility(int)
9264     * @see #getImportantForAccessibility()
9265     */
9266    public boolean isImportantForAccessibility() {
9267        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9268                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9269        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9270                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9271            return false;
9272        }
9273
9274        // Check parent mode to ensure we're not hidden.
9275        ViewParent parent = mParent;
9276        while (parent instanceof View) {
9277            if (((View) parent).getImportantForAccessibility()
9278                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9279                return false;
9280            }
9281            parent = parent.getParent();
9282        }
9283
9284        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9285                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9286                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9287    }
9288
9289    /**
9290     * Gets the parent for accessibility purposes. Note that the parent for
9291     * accessibility is not necessary the immediate parent. It is the first
9292     * predecessor that is important for accessibility.
9293     *
9294     * @return The parent for accessibility purposes.
9295     */
9296    public ViewParent getParentForAccessibility() {
9297        if (mParent instanceof View) {
9298            View parentView = (View) mParent;
9299            if (parentView.includeForAccessibility()) {
9300                return mParent;
9301            } else {
9302                return mParent.getParentForAccessibility();
9303            }
9304        }
9305        return null;
9306    }
9307
9308    /**
9309     * Adds the children of this View relevant for accessibility to the given list
9310     * as output. Since some Views are not important for accessibility the added
9311     * child views are not necessarily direct children of this view, rather they are
9312     * the first level of descendants important for accessibility.
9313     *
9314     * @param outChildren The output list that will receive children for accessibility.
9315     */
9316    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9317
9318    }
9319
9320    /**
9321     * Whether to regard this view for accessibility. A view is regarded for
9322     * accessibility if it is important for accessibility or the querying
9323     * accessibility service has explicitly requested that view not
9324     * important for accessibility are regarded.
9325     *
9326     * @return Whether to regard the view for accessibility.
9327     *
9328     * @hide
9329     */
9330    public boolean includeForAccessibility() {
9331        if (mAttachInfo != null) {
9332            return (mAttachInfo.mAccessibilityFetchFlags
9333                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9334                    || isImportantForAccessibility();
9335        }
9336        return false;
9337    }
9338
9339    /**
9340     * Returns whether the View is considered actionable from
9341     * accessibility perspective. Such view are important for
9342     * accessibility.
9343     *
9344     * @return True if the view is actionable for accessibility.
9345     *
9346     * @hide
9347     */
9348    public boolean isActionableForAccessibility() {
9349        return (isClickable() || isLongClickable() || isFocusable());
9350    }
9351
9352    /**
9353     * Returns whether the View has registered callbacks which makes it
9354     * important for accessibility.
9355     *
9356     * @return True if the view is actionable for accessibility.
9357     */
9358    private boolean hasListenersForAccessibility() {
9359        ListenerInfo info = getListenerInfo();
9360        return mTouchDelegate != null || info.mOnKeyListener != null
9361                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
9362                || info.mOnHoverListener != null || info.mOnDragListener != null;
9363    }
9364
9365    /**
9366     * Notifies that the accessibility state of this view changed. The change
9367     * is local to this view and does not represent structural changes such
9368     * as children and parent. For example, the view became focusable. The
9369     * notification is at at most once every
9370     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9371     * to avoid unnecessary load to the system. Also once a view has a pending
9372     * notification this method is a NOP until the notification has been sent.
9373     *
9374     * @hide
9375     */
9376    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
9377        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9378            return;
9379        }
9380        if (mSendViewStateChangedAccessibilityEvent == null) {
9381            mSendViewStateChangedAccessibilityEvent =
9382                    new SendViewStateChangedAccessibilityEvent();
9383        }
9384        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
9385    }
9386
9387    /**
9388     * Notifies that the accessibility state of this view changed. The change
9389     * is *not* local to this view and does represent structural changes such
9390     * as children and parent. For example, the view size changed. The
9391     * notification is at at most once every
9392     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9393     * to avoid unnecessary load to the system. Also once a view has a pending
9394     * notification this method is a NOP until the notification has been sent.
9395     *
9396     * @hide
9397     */
9398    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
9399        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9400            return;
9401        }
9402        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
9403            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9404            if (mParent != null) {
9405                try {
9406                    mParent.notifySubtreeAccessibilityStateChanged(
9407                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
9408                } catch (AbstractMethodError e) {
9409                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9410                            " does not fully implement ViewParent", e);
9411                }
9412            }
9413        }
9414    }
9415
9416    /**
9417     * Change the visibility of the View without triggering any other changes. This is
9418     * important for transitions, where visibility changes should not adjust focus or
9419     * trigger a new layout. This is only used when the visibility has already been changed
9420     * and we need a transient value during an animation. When the animation completes,
9421     * the original visibility value is always restored.
9422     *
9423     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9424     * @hide
9425     */
9426    public void setTransitionVisibility(@Visibility int visibility) {
9427        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
9428    }
9429
9430    /**
9431     * Reset the flag indicating the accessibility state of the subtree rooted
9432     * at this view changed.
9433     */
9434    void resetSubtreeAccessibilityStateChanged() {
9435        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9436    }
9437
9438    /**
9439     * Report an accessibility action to this view's parents for delegated processing.
9440     *
9441     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
9442     * call this method to delegate an accessibility action to a supporting parent. If the parent
9443     * returns true from its
9444     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
9445     * method this method will return true to signify that the action was consumed.</p>
9446     *
9447     * <p>This method is useful for implementing nested scrolling child views. If
9448     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
9449     * a custom view implementation may invoke this method to allow a parent to consume the
9450     * scroll first. If this method returns true the custom view should skip its own scrolling
9451     * behavior.</p>
9452     *
9453     * @param action Accessibility action to delegate
9454     * @param arguments Optional action arguments
9455     * @return true if the action was consumed by a parent
9456     */
9457    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
9458        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
9459            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
9460                return true;
9461            }
9462        }
9463        return false;
9464    }
9465
9466    /**
9467     * Performs the specified accessibility action on the view. For
9468     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
9469     * <p>
9470     * If an {@link AccessibilityDelegate} has been specified via calling
9471     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9472     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
9473     * is responsible for handling this call.
9474     * </p>
9475     *
9476     * <p>The default implementation will delegate
9477     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
9478     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
9479     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
9480     *
9481     * @param action The action to perform.
9482     * @param arguments Optional action arguments.
9483     * @return Whether the action was performed.
9484     */
9485    public boolean performAccessibilityAction(int action, Bundle arguments) {
9486      if (mAccessibilityDelegate != null) {
9487          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
9488      } else {
9489          return performAccessibilityActionInternal(action, arguments);
9490      }
9491    }
9492
9493   /**
9494    * @see #performAccessibilityAction(int, Bundle)
9495    *
9496    * Note: Called from the default {@link AccessibilityDelegate}.
9497    *
9498    * @hide
9499    */
9500    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9501        if (isNestedScrollingEnabled()
9502                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
9503                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
9504                || action == R.id.accessibilityActionScrollUp
9505                || action == R.id.accessibilityActionScrollLeft
9506                || action == R.id.accessibilityActionScrollDown
9507                || action == R.id.accessibilityActionScrollRight)) {
9508            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
9509                return true;
9510            }
9511        }
9512
9513        switch (action) {
9514            case AccessibilityNodeInfo.ACTION_CLICK: {
9515                if (isClickable()) {
9516                    performClick();
9517                    return true;
9518                }
9519            } break;
9520            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
9521                if (isLongClickable()) {
9522                    performLongClick();
9523                    return true;
9524                }
9525            } break;
9526            case AccessibilityNodeInfo.ACTION_FOCUS: {
9527                if (!hasFocus()) {
9528                    // Get out of touch mode since accessibility
9529                    // wants to move focus around.
9530                    getViewRootImpl().ensureTouchMode(false);
9531                    return requestFocus();
9532                }
9533            } break;
9534            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
9535                if (hasFocus()) {
9536                    clearFocus();
9537                    return !isFocused();
9538                }
9539            } break;
9540            case AccessibilityNodeInfo.ACTION_SELECT: {
9541                if (!isSelected()) {
9542                    setSelected(true);
9543                    return isSelected();
9544                }
9545            } break;
9546            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
9547                if (isSelected()) {
9548                    setSelected(false);
9549                    return !isSelected();
9550                }
9551            } break;
9552            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
9553                if (!isAccessibilityFocused()) {
9554                    return requestAccessibilityFocus();
9555                }
9556            } break;
9557            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
9558                if (isAccessibilityFocused()) {
9559                    clearAccessibilityFocus();
9560                    return true;
9561                }
9562            } break;
9563            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
9564                if (arguments != null) {
9565                    final int granularity = arguments.getInt(
9566                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9567                    final boolean extendSelection = arguments.getBoolean(
9568                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9569                    return traverseAtGranularity(granularity, true, extendSelection);
9570                }
9571            } break;
9572            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
9573                if (arguments != null) {
9574                    final int granularity = arguments.getInt(
9575                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9576                    final boolean extendSelection = arguments.getBoolean(
9577                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9578                    return traverseAtGranularity(granularity, false, extendSelection);
9579                }
9580            } break;
9581            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
9582                CharSequence text = getIterableTextForAccessibility();
9583                if (text == null) {
9584                    return false;
9585                }
9586                final int start = (arguments != null) ? arguments.getInt(
9587                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
9588                final int end = (arguments != null) ? arguments.getInt(
9589                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
9590                // Only cursor position can be specified (selection length == 0)
9591                if ((getAccessibilitySelectionStart() != start
9592                        || getAccessibilitySelectionEnd() != end)
9593                        && (start == end)) {
9594                    setAccessibilitySelection(start, end);
9595                    notifyViewAccessibilityStateChangedIfNeeded(
9596                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9597                    return true;
9598                }
9599            } break;
9600            case R.id.accessibilityActionShowOnScreen: {
9601                if (mAttachInfo != null) {
9602                    final Rect r = mAttachInfo.mTmpInvalRect;
9603                    getDrawingRect(r);
9604                    return requestRectangleOnScreen(r, true);
9605                }
9606            } break;
9607            case R.id.accessibilityActionContextClick: {
9608                if (isContextClickable()) {
9609                    performContextClick();
9610                    return true;
9611                }
9612            } break;
9613        }
9614        return false;
9615    }
9616
9617    private boolean traverseAtGranularity(int granularity, boolean forward,
9618            boolean extendSelection) {
9619        CharSequence text = getIterableTextForAccessibility();
9620        if (text == null || text.length() == 0) {
9621            return false;
9622        }
9623        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9624        if (iterator == null) {
9625            return false;
9626        }
9627        int current = getAccessibilitySelectionEnd();
9628        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9629            current = forward ? 0 : text.length();
9630        }
9631        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9632        if (range == null) {
9633            return false;
9634        }
9635        final int segmentStart = range[0];
9636        final int segmentEnd = range[1];
9637        int selectionStart;
9638        int selectionEnd;
9639        if (extendSelection && isAccessibilitySelectionExtendable()) {
9640            selectionStart = getAccessibilitySelectionStart();
9641            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9642                selectionStart = forward ? segmentStart : segmentEnd;
9643            }
9644            selectionEnd = forward ? segmentEnd : segmentStart;
9645        } else {
9646            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9647        }
9648        setAccessibilitySelection(selectionStart, selectionEnd);
9649        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9650                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9651        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9652        return true;
9653    }
9654
9655    /**
9656     * Gets the text reported for accessibility purposes.
9657     *
9658     * @return The accessibility text.
9659     *
9660     * @hide
9661     */
9662    public CharSequence getIterableTextForAccessibility() {
9663        return getContentDescription();
9664    }
9665
9666    /**
9667     * Gets whether accessibility selection can be extended.
9668     *
9669     * @return If selection is extensible.
9670     *
9671     * @hide
9672     */
9673    public boolean isAccessibilitySelectionExtendable() {
9674        return false;
9675    }
9676
9677    /**
9678     * @hide
9679     */
9680    public int getAccessibilitySelectionStart() {
9681        return mAccessibilityCursorPosition;
9682    }
9683
9684    /**
9685     * @hide
9686     */
9687    public int getAccessibilitySelectionEnd() {
9688        return getAccessibilitySelectionStart();
9689    }
9690
9691    /**
9692     * @hide
9693     */
9694    public void setAccessibilitySelection(int start, int end) {
9695        if (start ==  end && end == mAccessibilityCursorPosition) {
9696            return;
9697        }
9698        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9699            mAccessibilityCursorPosition = start;
9700        } else {
9701            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9702        }
9703        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9704    }
9705
9706    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9707            int fromIndex, int toIndex) {
9708        if (mParent == null) {
9709            return;
9710        }
9711        AccessibilityEvent event = AccessibilityEvent.obtain(
9712                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9713        onInitializeAccessibilityEvent(event);
9714        onPopulateAccessibilityEvent(event);
9715        event.setFromIndex(fromIndex);
9716        event.setToIndex(toIndex);
9717        event.setAction(action);
9718        event.setMovementGranularity(granularity);
9719        mParent.requestSendAccessibilityEvent(this, event);
9720    }
9721
9722    /**
9723     * @hide
9724     */
9725    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9726        switch (granularity) {
9727            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9728                CharSequence text = getIterableTextForAccessibility();
9729                if (text != null && text.length() > 0) {
9730                    CharacterTextSegmentIterator iterator =
9731                        CharacterTextSegmentIterator.getInstance(
9732                                mContext.getResources().getConfiguration().locale);
9733                    iterator.initialize(text.toString());
9734                    return iterator;
9735                }
9736            } break;
9737            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9738                CharSequence text = getIterableTextForAccessibility();
9739                if (text != null && text.length() > 0) {
9740                    WordTextSegmentIterator iterator =
9741                        WordTextSegmentIterator.getInstance(
9742                                mContext.getResources().getConfiguration().locale);
9743                    iterator.initialize(text.toString());
9744                    return iterator;
9745                }
9746            } break;
9747            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9748                CharSequence text = getIterableTextForAccessibility();
9749                if (text != null && text.length() > 0) {
9750                    ParagraphTextSegmentIterator iterator =
9751                        ParagraphTextSegmentIterator.getInstance();
9752                    iterator.initialize(text.toString());
9753                    return iterator;
9754                }
9755            } break;
9756        }
9757        return null;
9758    }
9759
9760    /**
9761     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
9762     * and {@link #onFinishTemporaryDetach()}.
9763     */
9764    public final boolean isTemporarilyDetached() {
9765        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
9766    }
9767
9768    /**
9769     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
9770     * a container View.
9771     */
9772    @CallSuper
9773    public void dispatchStartTemporaryDetach() {
9774        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
9775        onStartTemporaryDetach();
9776    }
9777
9778    /**
9779     * This is called when a container is going to temporarily detach a child, with
9780     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9781     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9782     * {@link #onDetachedFromWindow()} when the container is done.
9783     */
9784    public void onStartTemporaryDetach() {
9785        removeUnsetPressCallback();
9786        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9787    }
9788
9789    /**
9790     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
9791     * a container View.
9792     */
9793    @CallSuper
9794    public void dispatchFinishTemporaryDetach() {
9795        onFinishTemporaryDetach();
9796        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
9797    }
9798
9799    /**
9800     * Called after {@link #onStartTemporaryDetach} when the container is done
9801     * changing the view.
9802     */
9803    public void onFinishTemporaryDetach() {
9804    }
9805
9806    /**
9807     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9808     * for this view's window.  Returns null if the view is not currently attached
9809     * to the window.  Normally you will not need to use this directly, but
9810     * just use the standard high-level event callbacks like
9811     * {@link #onKeyDown(int, KeyEvent)}.
9812     */
9813    public KeyEvent.DispatcherState getKeyDispatcherState() {
9814        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9815    }
9816
9817    /**
9818     * Dispatch a key event before it is processed by any input method
9819     * associated with the view hierarchy.  This can be used to intercept
9820     * key events in special situations before the IME consumes them; a
9821     * typical example would be handling the BACK key to update the application's
9822     * UI instead of allowing the IME to see it and close itself.
9823     *
9824     * @param event The key event to be dispatched.
9825     * @return True if the event was handled, false otherwise.
9826     */
9827    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9828        return onKeyPreIme(event.getKeyCode(), event);
9829    }
9830
9831    /**
9832     * Dispatch a key event to the next view on the focus path. This path runs
9833     * from the top of the view tree down to the currently focused view. If this
9834     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9835     * the next node down the focus path. This method also fires any key
9836     * listeners.
9837     *
9838     * @param event The key event to be dispatched.
9839     * @return True if the event was handled, false otherwise.
9840     */
9841    public boolean dispatchKeyEvent(KeyEvent event) {
9842        if (mInputEventConsistencyVerifier != null) {
9843            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9844        }
9845
9846        // Give any attached key listener a first crack at the event.
9847        //noinspection SimplifiableIfStatement
9848        ListenerInfo li = mListenerInfo;
9849        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9850                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9851            return true;
9852        }
9853
9854        if (event.dispatch(this, mAttachInfo != null
9855                ? mAttachInfo.mKeyDispatchState : null, this)) {
9856            return true;
9857        }
9858
9859        if (mInputEventConsistencyVerifier != null) {
9860            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9861        }
9862        return false;
9863    }
9864
9865    /**
9866     * Dispatches a key shortcut event.
9867     *
9868     * @param event The key event to be dispatched.
9869     * @return True if the event was handled by the view, false otherwise.
9870     */
9871    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9872        return onKeyShortcut(event.getKeyCode(), event);
9873    }
9874
9875    /**
9876     * Pass the touch screen motion event down to the target view, or this
9877     * view if it is the target.
9878     *
9879     * @param event The motion event to be dispatched.
9880     * @return True if the event was handled by the view, false otherwise.
9881     */
9882    public boolean dispatchTouchEvent(MotionEvent event) {
9883        // If the event should be handled by accessibility focus first.
9884        if (event.isTargetAccessibilityFocus()) {
9885            // We don't have focus or no virtual descendant has it, do not handle the event.
9886            if (!isAccessibilityFocusedViewOrHost()) {
9887                return false;
9888            }
9889            // We have focus and got the event, then use normal event dispatch.
9890            event.setTargetAccessibilityFocus(false);
9891        }
9892
9893        boolean result = false;
9894
9895        if (mInputEventConsistencyVerifier != null) {
9896            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
9897        }
9898
9899        final int actionMasked = event.getActionMasked();
9900        if (actionMasked == MotionEvent.ACTION_DOWN) {
9901            // Defensive cleanup for new gesture
9902            stopNestedScroll();
9903        }
9904
9905        if (onFilterTouchEventForSecurity(event)) {
9906            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
9907                result = true;
9908            }
9909            //noinspection SimplifiableIfStatement
9910            ListenerInfo li = mListenerInfo;
9911            if (li != null && li.mOnTouchListener != null
9912                    && (mViewFlags & ENABLED_MASK) == ENABLED
9913                    && li.mOnTouchListener.onTouch(this, event)) {
9914                result = true;
9915            }
9916
9917            if (!result && onTouchEvent(event)) {
9918                result = true;
9919            }
9920        }
9921
9922        if (!result && mInputEventConsistencyVerifier != null) {
9923            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9924        }
9925
9926        // Clean up after nested scrolls if this is the end of a gesture;
9927        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
9928        // of the gesture.
9929        if (actionMasked == MotionEvent.ACTION_UP ||
9930                actionMasked == MotionEvent.ACTION_CANCEL ||
9931                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
9932            stopNestedScroll();
9933        }
9934
9935        return result;
9936    }
9937
9938    boolean isAccessibilityFocusedViewOrHost() {
9939        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
9940                .getAccessibilityFocusedHost() == this);
9941    }
9942
9943    /**
9944     * Filter the touch event to apply security policies.
9945     *
9946     * @param event The motion event to be filtered.
9947     * @return True if the event should be dispatched, false if the event should be dropped.
9948     *
9949     * @see #getFilterTouchesWhenObscured
9950     */
9951    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
9952        //noinspection RedundantIfStatement
9953        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
9954                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
9955            // Window is obscured, drop this touch.
9956            return false;
9957        }
9958        return true;
9959    }
9960
9961    /**
9962     * Pass a trackball motion event down to the focused view.
9963     *
9964     * @param event The motion event to be dispatched.
9965     * @return True if the event was handled by the view, false otherwise.
9966     */
9967    public boolean dispatchTrackballEvent(MotionEvent event) {
9968        if (mInputEventConsistencyVerifier != null) {
9969            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
9970        }
9971
9972        return onTrackballEvent(event);
9973    }
9974
9975    /**
9976     * Dispatch a generic motion event.
9977     * <p>
9978     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9979     * are delivered to the view under the pointer.  All other generic motion events are
9980     * delivered to the focused view.  Hover events are handled specially and are delivered
9981     * to {@link #onHoverEvent(MotionEvent)}.
9982     * </p>
9983     *
9984     * @param event The motion event to be dispatched.
9985     * @return True if the event was handled by the view, false otherwise.
9986     */
9987    public boolean dispatchGenericMotionEvent(MotionEvent event) {
9988        if (mInputEventConsistencyVerifier != null) {
9989            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
9990        }
9991
9992        final int source = event.getSource();
9993        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
9994            final int action = event.getAction();
9995            if (action == MotionEvent.ACTION_HOVER_ENTER
9996                    || action == MotionEvent.ACTION_HOVER_MOVE
9997                    || action == MotionEvent.ACTION_HOVER_EXIT) {
9998                if (dispatchHoverEvent(event)) {
9999                    return true;
10000                }
10001            } else if (dispatchGenericPointerEvent(event)) {
10002                return true;
10003            }
10004        } else if (dispatchGenericFocusedEvent(event)) {
10005            return true;
10006        }
10007
10008        if (dispatchGenericMotionEventInternal(event)) {
10009            return true;
10010        }
10011
10012        if (mInputEventConsistencyVerifier != null) {
10013            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10014        }
10015        return false;
10016    }
10017
10018    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10019        //noinspection SimplifiableIfStatement
10020        ListenerInfo li = mListenerInfo;
10021        if (li != null && li.mOnGenericMotionListener != null
10022                && (mViewFlags & ENABLED_MASK) == ENABLED
10023                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10024            return true;
10025        }
10026
10027        if (onGenericMotionEvent(event)) {
10028            return true;
10029        }
10030
10031        final int actionButton = event.getActionButton();
10032        switch (event.getActionMasked()) {
10033            case MotionEvent.ACTION_BUTTON_PRESS:
10034                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10035                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10036                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10037                    if (performContextClick()) {
10038                        mInContextButtonPress = true;
10039                        setPressed(true, event.getX(), event.getY());
10040                        removeTapCallback();
10041                        removeLongPressCallback();
10042                        return true;
10043                    }
10044                }
10045                break;
10046
10047            case MotionEvent.ACTION_BUTTON_RELEASE:
10048                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10049                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10050                    mInContextButtonPress = false;
10051                    mIgnoreNextUpEvent = true;
10052                }
10053                break;
10054        }
10055
10056        if (mInputEventConsistencyVerifier != null) {
10057            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10058        }
10059        return false;
10060    }
10061
10062    /**
10063     * Dispatch a hover event.
10064     * <p>
10065     * Do not call this method directly.
10066     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10067     * </p>
10068     *
10069     * @param event The motion event to be dispatched.
10070     * @return True if the event was handled by the view, false otherwise.
10071     */
10072    protected boolean dispatchHoverEvent(MotionEvent event) {
10073        ListenerInfo li = mListenerInfo;
10074        //noinspection SimplifiableIfStatement
10075        if (li != null && li.mOnHoverListener != null
10076                && (mViewFlags & ENABLED_MASK) == ENABLED
10077                && li.mOnHoverListener.onHover(this, event)) {
10078            return true;
10079        }
10080
10081        return onHoverEvent(event);
10082    }
10083
10084    /**
10085     * Returns true if the view has a child to which it has recently sent
10086     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10087     * it does not have a hovered child, then it must be the innermost hovered view.
10088     * @hide
10089     */
10090    protected boolean hasHoveredChild() {
10091        return false;
10092    }
10093
10094    /**
10095     * Dispatch a generic motion event to the view under the first pointer.
10096     * <p>
10097     * Do not call this method directly.
10098     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10099     * </p>
10100     *
10101     * @param event The motion event to be dispatched.
10102     * @return True if the event was handled by the view, false otherwise.
10103     */
10104    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10105        return false;
10106    }
10107
10108    /**
10109     * Dispatch a generic motion event to the currently focused view.
10110     * <p>
10111     * Do not call this method directly.
10112     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10113     * </p>
10114     *
10115     * @param event The motion event to be dispatched.
10116     * @return True if the event was handled by the view, false otherwise.
10117     */
10118    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10119        return false;
10120    }
10121
10122    /**
10123     * Dispatch a pointer event.
10124     * <p>
10125     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10126     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10127     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10128     * and should not be expected to handle other pointing device features.
10129     * </p>
10130     *
10131     * @param event The motion event to be dispatched.
10132     * @return True if the event was handled by the view, false otherwise.
10133     * @hide
10134     */
10135    public final boolean dispatchPointerEvent(MotionEvent event) {
10136        if (event.isTouchEvent()) {
10137            return dispatchTouchEvent(event);
10138        } else {
10139            return dispatchGenericMotionEvent(event);
10140        }
10141    }
10142
10143    /**
10144     * Called when the window containing this view gains or loses window focus.
10145     * ViewGroups should override to route to their children.
10146     *
10147     * @param hasFocus True if the window containing this view now has focus,
10148     *        false otherwise.
10149     */
10150    public void dispatchWindowFocusChanged(boolean hasFocus) {
10151        onWindowFocusChanged(hasFocus);
10152    }
10153
10154    /**
10155     * Called when the window containing this view gains or loses focus.  Note
10156     * that this is separate from view focus: to receive key events, both
10157     * your view and its window must have focus.  If a window is displayed
10158     * on top of yours that takes input focus, then your own window will lose
10159     * focus but the view focus will remain unchanged.
10160     *
10161     * @param hasWindowFocus True if the window containing this view now has
10162     *        focus, false otherwise.
10163     */
10164    public void onWindowFocusChanged(boolean hasWindowFocus) {
10165        InputMethodManager imm = InputMethodManager.peekInstance();
10166        if (!hasWindowFocus) {
10167            if (isPressed()) {
10168                setPressed(false);
10169            }
10170            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10171                imm.focusOut(this);
10172            }
10173            removeLongPressCallback();
10174            removeTapCallback();
10175            onFocusLost();
10176        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10177            imm.focusIn(this);
10178        }
10179        refreshDrawableState();
10180    }
10181
10182    /**
10183     * Returns true if this view is in a window that currently has window focus.
10184     * Note that this is not the same as the view itself having focus.
10185     *
10186     * @return True if this view is in a window that currently has window focus.
10187     */
10188    public boolean hasWindowFocus() {
10189        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10190    }
10191
10192    /**
10193     * Dispatch a view visibility change down the view hierarchy.
10194     * ViewGroups should override to route to their children.
10195     * @param changedView The view whose visibility changed. Could be 'this' or
10196     * an ancestor view.
10197     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10198     * {@link #INVISIBLE} or {@link #GONE}.
10199     */
10200    protected void dispatchVisibilityChanged(@NonNull View changedView,
10201            @Visibility int visibility) {
10202        onVisibilityChanged(changedView, visibility);
10203    }
10204
10205    /**
10206     * Called when the visibility of the view or an ancestor of the view has
10207     * changed.
10208     *
10209     * @param changedView The view whose visibility changed. May be
10210     *                    {@code this} or an ancestor view.
10211     * @param visibility The new visibility, one of {@link #VISIBLE},
10212     *                   {@link #INVISIBLE} or {@link #GONE}.
10213     */
10214    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10215    }
10216
10217    /**
10218     * Dispatch a hint about whether this view is displayed. For instance, when
10219     * a View moves out of the screen, it might receives a display hint indicating
10220     * the view is not displayed. Applications should not <em>rely</em> on this hint
10221     * as there is no guarantee that they will receive one.
10222     *
10223     * @param hint A hint about whether or not this view is displayed:
10224     * {@link #VISIBLE} or {@link #INVISIBLE}.
10225     */
10226    public void dispatchDisplayHint(@Visibility int hint) {
10227        onDisplayHint(hint);
10228    }
10229
10230    /**
10231     * Gives this view a hint about whether is displayed or not. For instance, when
10232     * a View moves out of the screen, it might receives a display hint indicating
10233     * the view is not displayed. Applications should not <em>rely</em> on this hint
10234     * as there is no guarantee that they will receive one.
10235     *
10236     * @param hint A hint about whether or not this view is displayed:
10237     * {@link #VISIBLE} or {@link #INVISIBLE}.
10238     */
10239    protected void onDisplayHint(@Visibility int hint) {
10240    }
10241
10242    /**
10243     * Dispatch a window visibility change down the view hierarchy.
10244     * ViewGroups should override to route to their children.
10245     *
10246     * @param visibility The new visibility of the window.
10247     *
10248     * @see #onWindowVisibilityChanged(int)
10249     */
10250    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10251        onWindowVisibilityChanged(visibility);
10252    }
10253
10254    /**
10255     * Called when the window containing has change its visibility
10256     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10257     * that this tells you whether or not your window is being made visible
10258     * to the window manager; this does <em>not</em> tell you whether or not
10259     * your window is obscured by other windows on the screen, even if it
10260     * is itself visible.
10261     *
10262     * @param visibility The new visibility of the window.
10263     */
10264    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10265        if (visibility == VISIBLE) {
10266            initialAwakenScrollBars();
10267        }
10268    }
10269
10270    /**
10271     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10272     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10273     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10274     *
10275     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10276     *                  ancestors or by window visibility
10277     * @return true if this view is visible to the user, not counting clipping or overlapping
10278     */
10279    @Visibility boolean dispatchVisibilityAggregated(boolean isVisible) {
10280        final boolean thisVisible = getVisibility() == VISIBLE;
10281        // If we're not visible but something is telling us we are, ignore it.
10282        if (thisVisible || !isVisible) {
10283            onVisibilityAggregated(isVisible);
10284        }
10285        return thisVisible && isVisible;
10286    }
10287
10288    /**
10289     * Called when the user-visibility of this View is potentially affected by a change
10290     * to this view itself, an ancestor view or the window this view is attached to.
10291     *
10292     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10293     *                  and this view's window is also visible
10294     */
10295    @CallSuper
10296    public void onVisibilityAggregated(boolean isVisible) {
10297        if (isVisible && mAttachInfo != null) {
10298            initialAwakenScrollBars();
10299        }
10300
10301        final Drawable dr = mBackground;
10302        if (dr != null && isVisible != dr.isVisible()) {
10303            dr.setVisible(isVisible, false);
10304        }
10305        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10306        if (fg != null && isVisible != fg.isVisible()) {
10307            fg.setVisible(isVisible, false);
10308        }
10309    }
10310
10311    /**
10312     * Returns the current visibility of the window this view is attached to
10313     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10314     *
10315     * @return Returns the current visibility of the view's window.
10316     */
10317    @Visibility
10318    public int getWindowVisibility() {
10319        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10320    }
10321
10322    /**
10323     * Retrieve the overall visible display size in which the window this view is
10324     * attached to has been positioned in.  This takes into account screen
10325     * decorations above the window, for both cases where the window itself
10326     * is being position inside of them or the window is being placed under
10327     * then and covered insets are used for the window to position its content
10328     * inside.  In effect, this tells you the available area where content can
10329     * be placed and remain visible to users.
10330     *
10331     * <p>This function requires an IPC back to the window manager to retrieve
10332     * the requested information, so should not be used in performance critical
10333     * code like drawing.
10334     *
10335     * @param outRect Filled in with the visible display frame.  If the view
10336     * is not attached to a window, this is simply the raw display size.
10337     */
10338    public void getWindowVisibleDisplayFrame(Rect outRect) {
10339        if (mAttachInfo != null) {
10340            try {
10341                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10342            } catch (RemoteException e) {
10343                return;
10344            }
10345            // XXX This is really broken, and probably all needs to be done
10346            // in the window manager, and we need to know more about whether
10347            // we want the area behind or in front of the IME.
10348            final Rect insets = mAttachInfo.mVisibleInsets;
10349            outRect.left += insets.left;
10350            outRect.top += insets.top;
10351            outRect.right -= insets.right;
10352            outRect.bottom -= insets.bottom;
10353            return;
10354        }
10355        // The view is not attached to a display so we don't have a context.
10356        // Make a best guess about the display size.
10357        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10358        d.getRectSize(outRect);
10359    }
10360
10361    /**
10362     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
10363     * is currently in without any insets.
10364     *
10365     * @hide
10366     */
10367    public void getWindowDisplayFrame(Rect outRect) {
10368        if (mAttachInfo != null) {
10369            try {
10370                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10371            } catch (RemoteException e) {
10372                return;
10373            }
10374            return;
10375        }
10376        // The view is not attached to a display so we don't have a context.
10377        // Make a best guess about the display size.
10378        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10379        d.getRectSize(outRect);
10380    }
10381
10382    /**
10383     * Dispatch a notification about a resource configuration change down
10384     * the view hierarchy.
10385     * ViewGroups should override to route to their children.
10386     *
10387     * @param newConfig The new resource configuration.
10388     *
10389     * @see #onConfigurationChanged(android.content.res.Configuration)
10390     */
10391    public void dispatchConfigurationChanged(Configuration newConfig) {
10392        onConfigurationChanged(newConfig);
10393    }
10394
10395    /**
10396     * Called when the current configuration of the resources being used
10397     * by the application have changed.  You can use this to decide when
10398     * to reload resources that can changed based on orientation and other
10399     * configuration characteristics.  You only need to use this if you are
10400     * not relying on the normal {@link android.app.Activity} mechanism of
10401     * recreating the activity instance upon a configuration change.
10402     *
10403     * @param newConfig The new resource configuration.
10404     */
10405    protected void onConfigurationChanged(Configuration newConfig) {
10406    }
10407
10408    /**
10409     * Private function to aggregate all per-view attributes in to the view
10410     * root.
10411     */
10412    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10413        performCollectViewAttributes(attachInfo, visibility);
10414    }
10415
10416    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10417        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
10418            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
10419                attachInfo.mKeepScreenOn = true;
10420            }
10421            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
10422            ListenerInfo li = mListenerInfo;
10423            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
10424                attachInfo.mHasSystemUiListeners = true;
10425            }
10426        }
10427    }
10428
10429    void needGlobalAttributesUpdate(boolean force) {
10430        final AttachInfo ai = mAttachInfo;
10431        if (ai != null && !ai.mRecomputeGlobalAttributes) {
10432            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
10433                    || ai.mHasSystemUiListeners) {
10434                ai.mRecomputeGlobalAttributes = true;
10435            }
10436        }
10437    }
10438
10439    /**
10440     * Returns whether the device is currently in touch mode.  Touch mode is entered
10441     * once the user begins interacting with the device by touch, and affects various
10442     * things like whether focus is always visible to the user.
10443     *
10444     * @return Whether the device is in touch mode.
10445     */
10446    @ViewDebug.ExportedProperty
10447    public boolean isInTouchMode() {
10448        if (mAttachInfo != null) {
10449            return mAttachInfo.mInTouchMode;
10450        } else {
10451            return ViewRootImpl.isInTouchMode();
10452        }
10453    }
10454
10455    /**
10456     * Returns the context the view is running in, through which it can
10457     * access the current theme, resources, etc.
10458     *
10459     * @return The view's Context.
10460     */
10461    @ViewDebug.CapturedViewProperty
10462    public final Context getContext() {
10463        return mContext;
10464    }
10465
10466    /**
10467     * Handle a key event before it is processed by any input method
10468     * associated with the view hierarchy.  This can be used to intercept
10469     * key events in special situations before the IME consumes them; a
10470     * typical example would be handling the BACK key to update the application's
10471     * UI instead of allowing the IME to see it and close itself.
10472     *
10473     * @param keyCode The value in event.getKeyCode().
10474     * @param event Description of the key event.
10475     * @return If you handled the event, return true. If you want to allow the
10476     *         event to be handled by the next receiver, return false.
10477     */
10478    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
10479        return false;
10480    }
10481
10482    /**
10483     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
10484     * KeyEvent.Callback.onKeyDown()}: perform press of the view
10485     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
10486     * is released, if the view is enabled and clickable.
10487     * <p>
10488     * Key presses in software keyboards will generally NOT trigger this
10489     * listener, although some may elect to do so in some situations. Do not
10490     * rely on this to catch software key presses.
10491     *
10492     * @param keyCode a key code that represents the button pressed, from
10493     *                {@link android.view.KeyEvent}
10494     * @param event the KeyEvent object that defines the button action
10495     */
10496    public boolean onKeyDown(int keyCode, KeyEvent event) {
10497        if (KeyEvent.isConfirmKey(keyCode)) {
10498            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10499                return true;
10500            }
10501
10502            // Long clickable items don't necessarily have to be clickable.
10503            if (((mViewFlags & CLICKABLE) == CLICKABLE
10504                    || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10505                    && (event.getRepeatCount() == 0)) {
10506                // For the purposes of menu anchoring and drawable hotspots,
10507                // key events are considered to be at the center of the view.
10508                final float x = getWidth() / 2f;
10509                final float y = getHeight() / 2f;
10510                setPressed(true, x, y);
10511                checkForLongClick(0, x, y);
10512                return true;
10513            }
10514        }
10515
10516        return false;
10517    }
10518
10519    /**
10520     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
10521     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
10522     * the event).
10523     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10524     * although some may elect to do so in some situations. Do not rely on this to
10525     * catch software key presses.
10526     */
10527    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
10528        return false;
10529    }
10530
10531    /**
10532     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
10533     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
10534     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
10535     * or {@link KeyEvent#KEYCODE_SPACE} is released.
10536     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10537     * although some may elect to do so in some situations. Do not rely on this to
10538     * catch software key presses.
10539     *
10540     * @param keyCode A key code that represents the button pressed, from
10541     *                {@link android.view.KeyEvent}.
10542     * @param event   The KeyEvent object that defines the button action.
10543     */
10544    public boolean onKeyUp(int keyCode, KeyEvent event) {
10545        if (KeyEvent.isConfirmKey(keyCode)) {
10546            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10547                return true;
10548            }
10549            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
10550                setPressed(false);
10551
10552                if (!mHasPerformedLongPress) {
10553                    // This is a tap, so remove the longpress check
10554                    removeLongPressCallback();
10555                    return performClick();
10556                }
10557            }
10558        }
10559        return false;
10560    }
10561
10562    /**
10563     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
10564     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
10565     * the event).
10566     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10567     * although some may elect to do so in some situations. Do not rely on this to
10568     * catch software key presses.
10569     *
10570     * @param keyCode     A key code that represents the button pressed, from
10571     *                    {@link android.view.KeyEvent}.
10572     * @param repeatCount The number of times the action was made.
10573     * @param event       The KeyEvent object that defines the button action.
10574     */
10575    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
10576        return false;
10577    }
10578
10579    /**
10580     * Called on the focused view when a key shortcut event is not handled.
10581     * Override this method to implement local key shortcuts for the View.
10582     * Key shortcuts can also be implemented by setting the
10583     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
10584     *
10585     * @param keyCode The value in event.getKeyCode().
10586     * @param event Description of the key event.
10587     * @return If you handled the event, return true. If you want to allow the
10588     *         event to be handled by the next receiver, return false.
10589     */
10590    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
10591        return false;
10592    }
10593
10594    /**
10595     * Check whether the called view is a text editor, in which case it
10596     * would make sense to automatically display a soft input window for
10597     * it.  Subclasses should override this if they implement
10598     * {@link #onCreateInputConnection(EditorInfo)} to return true if
10599     * a call on that method would return a non-null InputConnection, and
10600     * they are really a first-class editor that the user would normally
10601     * start typing on when the go into a window containing your view.
10602     *
10603     * <p>The default implementation always returns false.  This does
10604     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
10605     * will not be called or the user can not otherwise perform edits on your
10606     * view; it is just a hint to the system that this is not the primary
10607     * purpose of this view.
10608     *
10609     * @return Returns true if this view is a text editor, else false.
10610     */
10611    public boolean onCheckIsTextEditor() {
10612        return false;
10613    }
10614
10615    /**
10616     * Create a new InputConnection for an InputMethod to interact
10617     * with the view.  The default implementation returns null, since it doesn't
10618     * support input methods.  You can override this to implement such support.
10619     * This is only needed for views that take focus and text input.
10620     *
10621     * <p>When implementing this, you probably also want to implement
10622     * {@link #onCheckIsTextEditor()} to indicate you will return a
10623     * non-null InputConnection.</p>
10624     *
10625     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
10626     * object correctly and in its entirety, so that the connected IME can rely
10627     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
10628     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
10629     * must be filled in with the correct cursor position for IMEs to work correctly
10630     * with your application.</p>
10631     *
10632     * @param outAttrs Fill in with attribute information about the connection.
10633     */
10634    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
10635        return null;
10636    }
10637
10638    /**
10639     * Called by the {@link android.view.inputmethod.InputMethodManager}
10640     * when a view who is not the current
10641     * input connection target is trying to make a call on the manager.  The
10642     * default implementation returns false; you can override this to return
10643     * true for certain views if you are performing InputConnection proxying
10644     * to them.
10645     * @param view The View that is making the InputMethodManager call.
10646     * @return Return true to allow the call, false to reject.
10647     */
10648    public boolean checkInputConnectionProxy(View view) {
10649        return false;
10650    }
10651
10652    /**
10653     * Show the context menu for this view. It is not safe to hold on to the
10654     * menu after returning from this method.
10655     *
10656     * You should normally not overload this method. Overload
10657     * {@link #onCreateContextMenu(ContextMenu)} or define an
10658     * {@link OnCreateContextMenuListener} to add items to the context menu.
10659     *
10660     * @param menu The context menu to populate
10661     */
10662    public void createContextMenu(ContextMenu menu) {
10663        ContextMenuInfo menuInfo = getContextMenuInfo();
10664
10665        // Sets the current menu info so all items added to menu will have
10666        // my extra info set.
10667        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10668
10669        onCreateContextMenu(menu);
10670        ListenerInfo li = mListenerInfo;
10671        if (li != null && li.mOnCreateContextMenuListener != null) {
10672            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10673        }
10674
10675        // Clear the extra information so subsequent items that aren't mine don't
10676        // have my extra info.
10677        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10678
10679        if (mParent != null) {
10680            mParent.createContextMenu(menu);
10681        }
10682    }
10683
10684    /**
10685     * Views should implement this if they have extra information to associate
10686     * with the context menu. The return result is supplied as a parameter to
10687     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10688     * callback.
10689     *
10690     * @return Extra information about the item for which the context menu
10691     *         should be shown. This information will vary across different
10692     *         subclasses of View.
10693     */
10694    protected ContextMenuInfo getContextMenuInfo() {
10695        return null;
10696    }
10697
10698    /**
10699     * Views should implement this if the view itself is going to add items to
10700     * the context menu.
10701     *
10702     * @param menu the context menu to populate
10703     */
10704    protected void onCreateContextMenu(ContextMenu menu) {
10705    }
10706
10707    /**
10708     * Implement this method to handle trackball motion events.  The
10709     * <em>relative</em> movement of the trackball since the last event
10710     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10711     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10712     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10713     * they will often be fractional values, representing the more fine-grained
10714     * movement information available from a trackball).
10715     *
10716     * @param event The motion event.
10717     * @return True if the event was handled, false otherwise.
10718     */
10719    public boolean onTrackballEvent(MotionEvent event) {
10720        return false;
10721    }
10722
10723    /**
10724     * Implement this method to handle generic motion events.
10725     * <p>
10726     * Generic motion events describe joystick movements, mouse hovers, track pad
10727     * touches, scroll wheel movements and other input events.  The
10728     * {@link MotionEvent#getSource() source} of the motion event specifies
10729     * the class of input that was received.  Implementations of this method
10730     * must examine the bits in the source before processing the event.
10731     * The following code example shows how this is done.
10732     * </p><p>
10733     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10734     * are delivered to the view under the pointer.  All other generic motion events are
10735     * delivered to the focused view.
10736     * </p>
10737     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10738     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10739     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10740     *             // process the joystick movement...
10741     *             return true;
10742     *         }
10743     *     }
10744     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10745     *         switch (event.getAction()) {
10746     *             case MotionEvent.ACTION_HOVER_MOVE:
10747     *                 // process the mouse hover movement...
10748     *                 return true;
10749     *             case MotionEvent.ACTION_SCROLL:
10750     *                 // process the scroll wheel movement...
10751     *                 return true;
10752     *         }
10753     *     }
10754     *     return super.onGenericMotionEvent(event);
10755     * }</pre>
10756     *
10757     * @param event The generic motion event being processed.
10758     * @return True if the event was handled, false otherwise.
10759     */
10760    public boolean onGenericMotionEvent(MotionEvent event) {
10761        return false;
10762    }
10763
10764    /**
10765     * Implement this method to handle hover events.
10766     * <p>
10767     * This method is called whenever a pointer is hovering into, over, or out of the
10768     * bounds of a view and the view is not currently being touched.
10769     * Hover events are represented as pointer events with action
10770     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10771     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10772     * </p>
10773     * <ul>
10774     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10775     * when the pointer enters the bounds of the view.</li>
10776     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10777     * when the pointer has already entered the bounds of the view and has moved.</li>
10778     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10779     * when the pointer has exited the bounds of the view or when the pointer is
10780     * about to go down due to a button click, tap, or similar user action that
10781     * causes the view to be touched.</li>
10782     * </ul>
10783     * <p>
10784     * The view should implement this method to return true to indicate that it is
10785     * handling the hover event, such as by changing its drawable state.
10786     * </p><p>
10787     * The default implementation calls {@link #setHovered} to update the hovered state
10788     * of the view when a hover enter or hover exit event is received, if the view
10789     * is enabled and is clickable.  The default implementation also sends hover
10790     * accessibility events.
10791     * </p>
10792     *
10793     * @param event The motion event that describes the hover.
10794     * @return True if the view handled the hover event.
10795     *
10796     * @see #isHovered
10797     * @see #setHovered
10798     * @see #onHoverChanged
10799     */
10800    public boolean onHoverEvent(MotionEvent event) {
10801        // The root view may receive hover (or touch) events that are outside the bounds of
10802        // the window.  This code ensures that we only send accessibility events for
10803        // hovers that are actually within the bounds of the root view.
10804        final int action = event.getActionMasked();
10805        if (!mSendingHoverAccessibilityEvents) {
10806            if ((action == MotionEvent.ACTION_HOVER_ENTER
10807                    || action == MotionEvent.ACTION_HOVER_MOVE)
10808                    && !hasHoveredChild()
10809                    && pointInView(event.getX(), event.getY())) {
10810                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10811                mSendingHoverAccessibilityEvents = true;
10812            }
10813        } else {
10814            if (action == MotionEvent.ACTION_HOVER_EXIT
10815                    || (action == MotionEvent.ACTION_MOVE
10816                            && !pointInView(event.getX(), event.getY()))) {
10817                mSendingHoverAccessibilityEvents = false;
10818                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10819            }
10820        }
10821
10822        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
10823                && event.isFromSource(InputDevice.SOURCE_MOUSE)
10824                && isOnScrollbar(event.getX(), event.getY())) {
10825            awakenScrollBars();
10826        }
10827        if (isHoverable()) {
10828            switch (action) {
10829                case MotionEvent.ACTION_HOVER_ENTER:
10830                    setHovered(true);
10831                    break;
10832                case MotionEvent.ACTION_HOVER_EXIT:
10833                    setHovered(false);
10834                    break;
10835            }
10836
10837            // Dispatch the event to onGenericMotionEvent before returning true.
10838            // This is to provide compatibility with existing applications that
10839            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10840            // break because of the new default handling for hoverable views
10841            // in onHoverEvent.
10842            // Note that onGenericMotionEvent will be called by default when
10843            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10844            dispatchGenericMotionEventInternal(event);
10845            // The event was already handled by calling setHovered(), so always
10846            // return true.
10847            return true;
10848        }
10849
10850        return false;
10851    }
10852
10853    /**
10854     * Returns true if the view should handle {@link #onHoverEvent}
10855     * by calling {@link #setHovered} to change its hovered state.
10856     *
10857     * @return True if the view is hoverable.
10858     */
10859    private boolean isHoverable() {
10860        final int viewFlags = mViewFlags;
10861        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10862            return false;
10863        }
10864
10865        return (viewFlags & CLICKABLE) == CLICKABLE
10866                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10867                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10868    }
10869
10870    /**
10871     * Returns true if the view is currently hovered.
10872     *
10873     * @return True if the view is currently hovered.
10874     *
10875     * @see #setHovered
10876     * @see #onHoverChanged
10877     */
10878    @ViewDebug.ExportedProperty
10879    public boolean isHovered() {
10880        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10881    }
10882
10883    /**
10884     * Sets whether the view is currently hovered.
10885     * <p>
10886     * Calling this method also changes the drawable state of the view.  This
10887     * enables the view to react to hover by using different drawable resources
10888     * to change its appearance.
10889     * </p><p>
10890     * The {@link #onHoverChanged} method is called when the hovered state changes.
10891     * </p>
10892     *
10893     * @param hovered True if the view is hovered.
10894     *
10895     * @see #isHovered
10896     * @see #onHoverChanged
10897     */
10898    public void setHovered(boolean hovered) {
10899        if (hovered) {
10900            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
10901                mPrivateFlags |= PFLAG_HOVERED;
10902                refreshDrawableState();
10903                onHoverChanged(true);
10904            }
10905        } else {
10906            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
10907                mPrivateFlags &= ~PFLAG_HOVERED;
10908                refreshDrawableState();
10909                onHoverChanged(false);
10910            }
10911        }
10912    }
10913
10914    /**
10915     * Implement this method to handle hover state changes.
10916     * <p>
10917     * This method is called whenever the hover state changes as a result of a
10918     * call to {@link #setHovered}.
10919     * </p>
10920     *
10921     * @param hovered The current hover state, as returned by {@link #isHovered}.
10922     *
10923     * @see #isHovered
10924     * @see #setHovered
10925     */
10926    public void onHoverChanged(boolean hovered) {
10927    }
10928
10929    /**
10930     * Handles scroll bar dragging by mouse input.
10931     *
10932     * @hide
10933     * @param event The motion event.
10934     *
10935     * @return true if the event was handled as a scroll bar dragging, false otherwise.
10936     */
10937    protected boolean handleScrollBarDragging(MotionEvent event) {
10938        if (mScrollCache == null) {
10939            return false;
10940        }
10941        final float x = event.getX();
10942        final float y = event.getY();
10943        final int action = event.getAction();
10944        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
10945                && action != MotionEvent.ACTION_DOWN)
10946                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
10947                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
10948            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
10949            return false;
10950        }
10951
10952        switch (action) {
10953            case MotionEvent.ACTION_MOVE:
10954                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
10955                    return false;
10956                }
10957                if (mScrollCache.mScrollBarDraggingState
10958                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
10959                    final Rect bounds = mScrollCache.mScrollBarBounds;
10960                    getVerticalScrollBarBounds(bounds);
10961                    final int range = computeVerticalScrollRange();
10962                    final int offset = computeVerticalScrollOffset();
10963                    final int extent = computeVerticalScrollExtent();
10964
10965                    final int thumbLength = ScrollBarUtils.getThumbLength(
10966                            bounds.height(), bounds.width(), extent, range);
10967                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
10968                            bounds.height(), thumbLength, extent, range, offset);
10969
10970                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
10971                    final float maxThumbOffset = bounds.height() - thumbLength;
10972                    final float newThumbOffset =
10973                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
10974                    final int height = getHeight();
10975                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
10976                            && height > 0 && extent > 0) {
10977                        final int newY = Math.round((range - extent)
10978                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
10979                        if (newY != getScrollY()) {
10980                            mScrollCache.mScrollBarDraggingPos = y;
10981                            setScrollY(newY);
10982                        }
10983                    }
10984                    return true;
10985                }
10986                if (mScrollCache.mScrollBarDraggingState
10987                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
10988                    final Rect bounds = mScrollCache.mScrollBarBounds;
10989                    getHorizontalScrollBarBounds(bounds);
10990                    final int range = computeHorizontalScrollRange();
10991                    final int offset = computeHorizontalScrollOffset();
10992                    final int extent = computeHorizontalScrollExtent();
10993
10994                    final int thumbLength = ScrollBarUtils.getThumbLength(
10995                            bounds.width(), bounds.height(), extent, range);
10996                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
10997                            bounds.width(), thumbLength, extent, range, offset);
10998
10999                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11000                    final float maxThumbOffset = bounds.width() - thumbLength;
11001                    final float newThumbOffset =
11002                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11003                    final int width = getWidth();
11004                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11005                            && width > 0 && extent > 0) {
11006                        final int newX = Math.round((range - extent)
11007                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11008                        if (newX != getScrollX()) {
11009                            mScrollCache.mScrollBarDraggingPos = x;
11010                            setScrollX(newX);
11011                        }
11012                    }
11013                    return true;
11014                }
11015            case MotionEvent.ACTION_DOWN:
11016                if (mScrollCache.state == ScrollabilityCache.OFF) {
11017                    return false;
11018                }
11019                if (isOnVerticalScrollbarThumb(x, y)) {
11020                    mScrollCache.mScrollBarDraggingState =
11021                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11022                    mScrollCache.mScrollBarDraggingPos = y;
11023                    return true;
11024                }
11025                if (isOnHorizontalScrollbarThumb(x, y)) {
11026                    mScrollCache.mScrollBarDraggingState =
11027                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11028                    mScrollCache.mScrollBarDraggingPos = x;
11029                    return true;
11030                }
11031        }
11032        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11033        return false;
11034    }
11035
11036    /**
11037     * Implement this method to handle touch screen motion events.
11038     * <p>
11039     * If this method is used to detect click actions, it is recommended that
11040     * the actions be performed by implementing and calling
11041     * {@link #performClick()}. This will ensure consistent system behavior,
11042     * including:
11043     * <ul>
11044     * <li>obeying click sound preferences
11045     * <li>dispatching OnClickListener calls
11046     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11047     * accessibility features are enabled
11048     * </ul>
11049     *
11050     * @param event The motion event.
11051     * @return True if the event was handled, false otherwise.
11052     */
11053    public boolean onTouchEvent(MotionEvent event) {
11054        final float x = event.getX();
11055        final float y = event.getY();
11056        final int viewFlags = mViewFlags;
11057        final int action = event.getAction();
11058
11059        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11060            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11061                setPressed(false);
11062            }
11063            // A disabled view that is clickable still consumes the touch
11064            // events, it just doesn't respond to them.
11065            return (((viewFlags & CLICKABLE) == CLICKABLE
11066                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11067                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
11068        }
11069        if (mTouchDelegate != null) {
11070            if (mTouchDelegate.onTouchEvent(event)) {
11071                return true;
11072            }
11073        }
11074
11075        if (((viewFlags & CLICKABLE) == CLICKABLE ||
11076                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
11077                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
11078            switch (action) {
11079                case MotionEvent.ACTION_UP:
11080                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11081                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11082                        // take focus if we don't have it already and we should in
11083                        // touch mode.
11084                        boolean focusTaken = false;
11085                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11086                            focusTaken = requestFocus();
11087                        }
11088
11089                        if (prepressed) {
11090                            // The button is being released before we actually
11091                            // showed it as pressed.  Make it show the pressed
11092                            // state now (before scheduling the click) to ensure
11093                            // the user sees it.
11094                            setPressed(true, x, y);
11095                       }
11096
11097                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11098                            // This is a tap, so remove the longpress check
11099                            removeLongPressCallback();
11100
11101                            // Only perform take click actions if we were in the pressed state
11102                            if (!focusTaken) {
11103                                // Use a Runnable and post this rather than calling
11104                                // performClick directly. This lets other visual state
11105                                // of the view update before click actions start.
11106                                if (mPerformClick == null) {
11107                                    mPerformClick = new PerformClick();
11108                                }
11109                                if (!post(mPerformClick)) {
11110                                    performClick();
11111                                }
11112                            }
11113                        }
11114
11115                        if (mUnsetPressedState == null) {
11116                            mUnsetPressedState = new UnsetPressedState();
11117                        }
11118
11119                        if (prepressed) {
11120                            postDelayed(mUnsetPressedState,
11121                                    ViewConfiguration.getPressedStateDuration());
11122                        } else if (!post(mUnsetPressedState)) {
11123                            // If the post failed, unpress right now
11124                            mUnsetPressedState.run();
11125                        }
11126
11127                        removeTapCallback();
11128                    }
11129                    mIgnoreNextUpEvent = false;
11130                    break;
11131
11132                case MotionEvent.ACTION_DOWN:
11133                    mHasPerformedLongPress = false;
11134
11135                    if (performButtonActionOnTouchDown(event)) {
11136                        break;
11137                    }
11138
11139                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11140                    boolean isInScrollingContainer = isInScrollingContainer();
11141
11142                    // For views inside a scrolling container, delay the pressed feedback for
11143                    // a short period in case this is a scroll.
11144                    if (isInScrollingContainer) {
11145                        mPrivateFlags |= PFLAG_PREPRESSED;
11146                        if (mPendingCheckForTap == null) {
11147                            mPendingCheckForTap = new CheckForTap();
11148                        }
11149                        mPendingCheckForTap.x = event.getX();
11150                        mPendingCheckForTap.y = event.getY();
11151                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11152                    } else {
11153                        // Not inside a scrolling container, so show the feedback right away
11154                        setPressed(true, x, y);
11155                        checkForLongClick(0, x, y);
11156                    }
11157                    break;
11158
11159                case MotionEvent.ACTION_CANCEL:
11160                    setPressed(false);
11161                    removeTapCallback();
11162                    removeLongPressCallback();
11163                    mInContextButtonPress = false;
11164                    mHasPerformedLongPress = false;
11165                    mIgnoreNextUpEvent = false;
11166                    break;
11167
11168                case MotionEvent.ACTION_MOVE:
11169                    drawableHotspotChanged(x, y);
11170
11171                    // Be lenient about moving outside of buttons
11172                    if (!pointInView(x, y, mTouchSlop)) {
11173                        // Outside button
11174                        removeTapCallback();
11175                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11176                            // Remove any future long press/tap checks
11177                            removeLongPressCallback();
11178
11179                            setPressed(false);
11180                        }
11181                    }
11182                    break;
11183            }
11184
11185            return true;
11186        }
11187
11188        return false;
11189    }
11190
11191    /**
11192     * @hide
11193     */
11194    public boolean isInScrollingContainer() {
11195        ViewParent p = getParent();
11196        while (p != null && p instanceof ViewGroup) {
11197            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11198                return true;
11199            }
11200            p = p.getParent();
11201        }
11202        return false;
11203    }
11204
11205    /**
11206     * Remove the longpress detection timer.
11207     */
11208    private void removeLongPressCallback() {
11209        if (mPendingCheckForLongPress != null) {
11210          removeCallbacks(mPendingCheckForLongPress);
11211        }
11212    }
11213
11214    /**
11215     * Remove the pending click action
11216     */
11217    private void removePerformClickCallback() {
11218        if (mPerformClick != null) {
11219            removeCallbacks(mPerformClick);
11220        }
11221    }
11222
11223    /**
11224     * Remove the prepress detection timer.
11225     */
11226    private void removeUnsetPressCallback() {
11227        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11228            setPressed(false);
11229            removeCallbacks(mUnsetPressedState);
11230        }
11231    }
11232
11233    /**
11234     * Remove the tap detection timer.
11235     */
11236    private void removeTapCallback() {
11237        if (mPendingCheckForTap != null) {
11238            mPrivateFlags &= ~PFLAG_PREPRESSED;
11239            removeCallbacks(mPendingCheckForTap);
11240        }
11241    }
11242
11243    /**
11244     * Cancels a pending long press.  Your subclass can use this if you
11245     * want the context menu to come up if the user presses and holds
11246     * at the same place, but you don't want it to come up if they press
11247     * and then move around enough to cause scrolling.
11248     */
11249    public void cancelLongPress() {
11250        removeLongPressCallback();
11251
11252        /*
11253         * The prepressed state handled by the tap callback is a display
11254         * construct, but the tap callback will post a long press callback
11255         * less its own timeout. Remove it here.
11256         */
11257        removeTapCallback();
11258    }
11259
11260    /**
11261     * Remove the pending callback for sending a
11262     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11263     */
11264    private void removeSendViewScrolledAccessibilityEventCallback() {
11265        if (mSendViewScrolledAccessibilityEvent != null) {
11266            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11267            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11268        }
11269    }
11270
11271    /**
11272     * Sets the TouchDelegate for this View.
11273     */
11274    public void setTouchDelegate(TouchDelegate delegate) {
11275        mTouchDelegate = delegate;
11276    }
11277
11278    /**
11279     * Gets the TouchDelegate for this View.
11280     */
11281    public TouchDelegate getTouchDelegate() {
11282        return mTouchDelegate;
11283    }
11284
11285    /**
11286     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11287     *
11288     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11289     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11290     * available. This method should only be called for touch events.
11291     *
11292     * <p class="note">This api is not intended for most applications. Buffered dispatch
11293     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11294     * streams will not improve your input latency. Side effects include: increased latency,
11295     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11296     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11297     * you.</p>
11298     */
11299    public final void requestUnbufferedDispatch(MotionEvent event) {
11300        final int action = event.getAction();
11301        if (mAttachInfo == null
11302                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
11303                || !event.isTouchEvent()) {
11304            return;
11305        }
11306        mAttachInfo.mUnbufferedDispatchRequested = true;
11307    }
11308
11309    /**
11310     * Set flags controlling behavior of this view.
11311     *
11312     * @param flags Constant indicating the value which should be set
11313     * @param mask Constant indicating the bit range that should be changed
11314     */
11315    void setFlags(int flags, int mask) {
11316        final boolean accessibilityEnabled =
11317                AccessibilityManager.getInstance(mContext).isEnabled();
11318        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
11319
11320        int old = mViewFlags;
11321        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
11322
11323        int changed = mViewFlags ^ old;
11324        if (changed == 0) {
11325            return;
11326        }
11327        int privateFlags = mPrivateFlags;
11328
11329        /* Check if the FOCUSABLE bit has changed */
11330        if (((changed & FOCUSABLE_MASK) != 0) &&
11331                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
11332            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
11333                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
11334                /* Give up focus if we are no longer focusable */
11335                clearFocus();
11336            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
11337                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
11338                /*
11339                 * Tell the view system that we are now available to take focus
11340                 * if no one else already has it.
11341                 */
11342                if (mParent != null) mParent.focusableViewAvailable(this);
11343            }
11344        }
11345
11346        final int newVisibility = flags & VISIBILITY_MASK;
11347        if (newVisibility == VISIBLE) {
11348            if ((changed & VISIBILITY_MASK) != 0) {
11349                /*
11350                 * If this view is becoming visible, invalidate it in case it changed while
11351                 * it was not visible. Marking it drawn ensures that the invalidation will
11352                 * go through.
11353                 */
11354                mPrivateFlags |= PFLAG_DRAWN;
11355                invalidate(true);
11356
11357                needGlobalAttributesUpdate(true);
11358
11359                // a view becoming visible is worth notifying the parent
11360                // about in case nothing has focus.  even if this specific view
11361                // isn't focusable, it may contain something that is, so let
11362                // the root view try to give this focus if nothing else does.
11363                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
11364                    mParent.focusableViewAvailable(this);
11365                }
11366            }
11367        }
11368
11369        /* Check if the GONE bit has changed */
11370        if ((changed & GONE) != 0) {
11371            needGlobalAttributesUpdate(false);
11372            requestLayout();
11373
11374            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
11375                if (hasFocus()) clearFocus();
11376                clearAccessibilityFocus();
11377                destroyDrawingCache();
11378                if (mParent instanceof View) {
11379                    // GONE views noop invalidation, so invalidate the parent
11380                    ((View) mParent).invalidate(true);
11381                }
11382                // Mark the view drawn to ensure that it gets invalidated properly the next
11383                // time it is visible and gets invalidated
11384                mPrivateFlags |= PFLAG_DRAWN;
11385            }
11386            if (mAttachInfo != null) {
11387                mAttachInfo.mViewVisibilityChanged = true;
11388            }
11389        }
11390
11391        /* Check if the VISIBLE bit has changed */
11392        if ((changed & INVISIBLE) != 0) {
11393            needGlobalAttributesUpdate(false);
11394            /*
11395             * If this view is becoming invisible, set the DRAWN flag so that
11396             * the next invalidate() will not be skipped.
11397             */
11398            mPrivateFlags |= PFLAG_DRAWN;
11399
11400            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
11401                // root view becoming invisible shouldn't clear focus and accessibility focus
11402                if (getRootView() != this) {
11403                    if (hasFocus()) clearFocus();
11404                    clearAccessibilityFocus();
11405                }
11406            }
11407            if (mAttachInfo != null) {
11408                mAttachInfo.mViewVisibilityChanged = true;
11409            }
11410        }
11411
11412        if ((changed & VISIBILITY_MASK) != 0) {
11413            // If the view is invisible, cleanup its display list to free up resources
11414            if (newVisibility != VISIBLE && mAttachInfo != null) {
11415                cleanupDraw();
11416            }
11417
11418            if (mParent instanceof ViewGroup) {
11419                ((ViewGroup) mParent).onChildVisibilityChanged(this,
11420                        (changed & VISIBILITY_MASK), newVisibility);
11421                ((View) mParent).invalidate(true);
11422            } else if (mParent != null) {
11423                mParent.invalidateChild(this, null);
11424            }
11425
11426            if (mAttachInfo != null) {
11427                dispatchVisibilityChanged(this, newVisibility);
11428
11429                // Aggregated visibility changes are dispatched to attached views
11430                // in visible windows where the parent is currently shown/drawn
11431                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
11432                // discounting clipping or overlapping. This makes it a good place
11433                // to change animation states.
11434                if (mParent != null && getWindowVisibility() == VISIBLE &&
11435                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
11436                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
11437                }
11438                notifySubtreeAccessibilityStateChangedIfNeeded();
11439            }
11440        }
11441
11442        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
11443            destroyDrawingCache();
11444        }
11445
11446        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
11447            destroyDrawingCache();
11448            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11449            invalidateParentCaches();
11450        }
11451
11452        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
11453            destroyDrawingCache();
11454            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11455        }
11456
11457        if ((changed & DRAW_MASK) != 0) {
11458            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
11459                if (mBackground != null
11460                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
11461                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11462                } else {
11463                    mPrivateFlags |= PFLAG_SKIP_DRAW;
11464                }
11465            } else {
11466                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11467            }
11468            requestLayout();
11469            invalidate(true);
11470        }
11471
11472        if ((changed & KEEP_SCREEN_ON) != 0) {
11473            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11474                mParent.recomputeViewAttributes(this);
11475            }
11476        }
11477
11478        if (accessibilityEnabled) {
11479            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
11480                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
11481                    || (changed & CONTEXT_CLICKABLE) != 0) {
11482                if (oldIncludeForAccessibility != includeForAccessibility()) {
11483                    notifySubtreeAccessibilityStateChangedIfNeeded();
11484                } else {
11485                    notifyViewAccessibilityStateChangedIfNeeded(
11486                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11487                }
11488            } else if ((changed & ENABLED_MASK) != 0) {
11489                notifyViewAccessibilityStateChangedIfNeeded(
11490                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11491            }
11492        }
11493    }
11494
11495    /**
11496     * Change the view's z order in the tree, so it's on top of other sibling
11497     * views. This ordering change may affect layout, if the parent container
11498     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
11499     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
11500     * method should be followed by calls to {@link #requestLayout()} and
11501     * {@link View#invalidate()} on the view's parent to force the parent to redraw
11502     * with the new child ordering.
11503     *
11504     * @see ViewGroup#bringChildToFront(View)
11505     */
11506    public void bringToFront() {
11507        if (mParent != null) {
11508            mParent.bringChildToFront(this);
11509        }
11510    }
11511
11512    /**
11513     * This is called in response to an internal scroll in this view (i.e., the
11514     * view scrolled its own contents). This is typically as a result of
11515     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
11516     * called.
11517     *
11518     * @param l Current horizontal scroll origin.
11519     * @param t Current vertical scroll origin.
11520     * @param oldl Previous horizontal scroll origin.
11521     * @param oldt Previous vertical scroll origin.
11522     */
11523    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
11524        notifySubtreeAccessibilityStateChangedIfNeeded();
11525
11526        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11527            postSendViewScrolledAccessibilityEventCallback();
11528        }
11529
11530        mBackgroundSizeChanged = true;
11531        if (mForegroundInfo != null) {
11532            mForegroundInfo.mBoundsChanged = true;
11533        }
11534
11535        final AttachInfo ai = mAttachInfo;
11536        if (ai != null) {
11537            ai.mViewScrollChanged = true;
11538        }
11539
11540        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
11541            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
11542        }
11543    }
11544
11545    /**
11546     * Interface definition for a callback to be invoked when the scroll
11547     * X or Y positions of a view change.
11548     * <p>
11549     * <b>Note:</b> Some views handle scrolling independently from View and may
11550     * have their own separate listeners for scroll-type events. For example,
11551     * {@link android.widget.ListView ListView} allows clients to register an
11552     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
11553     * to listen for changes in list scroll position.
11554     *
11555     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
11556     */
11557    public interface OnScrollChangeListener {
11558        /**
11559         * Called when the scroll position of a view changes.
11560         *
11561         * @param v The view whose scroll position has changed.
11562         * @param scrollX Current horizontal scroll origin.
11563         * @param scrollY Current vertical scroll origin.
11564         * @param oldScrollX Previous horizontal scroll origin.
11565         * @param oldScrollY Previous vertical scroll origin.
11566         */
11567        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
11568    }
11569
11570    /**
11571     * Interface definition for a callback to be invoked when the layout bounds of a view
11572     * changes due to layout processing.
11573     */
11574    public interface OnLayoutChangeListener {
11575        /**
11576         * Called when the layout bounds of a view changes due to layout processing.
11577         *
11578         * @param v The view whose bounds have changed.
11579         * @param left The new value of the view's left property.
11580         * @param top The new value of the view's top property.
11581         * @param right The new value of the view's right property.
11582         * @param bottom The new value of the view's bottom property.
11583         * @param oldLeft The previous value of the view's left property.
11584         * @param oldTop The previous value of the view's top property.
11585         * @param oldRight The previous value of the view's right property.
11586         * @param oldBottom The previous value of the view's bottom property.
11587         */
11588        void onLayoutChange(View v, int left, int top, int right, int bottom,
11589            int oldLeft, int oldTop, int oldRight, int oldBottom);
11590    }
11591
11592    /**
11593     * This is called during layout when the size of this view has changed. If
11594     * you were just added to the view hierarchy, you're called with the old
11595     * values of 0.
11596     *
11597     * @param w Current width of this view.
11598     * @param h Current height of this view.
11599     * @param oldw Old width of this view.
11600     * @param oldh Old height of this view.
11601     */
11602    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
11603    }
11604
11605    /**
11606     * Called by draw to draw the child views. This may be overridden
11607     * by derived classes to gain control just before its children are drawn
11608     * (but after its own view has been drawn).
11609     * @param canvas the canvas on which to draw the view
11610     */
11611    protected void dispatchDraw(Canvas canvas) {
11612
11613    }
11614
11615    /**
11616     * Gets the parent of this view. Note that the parent is a
11617     * ViewParent and not necessarily a View.
11618     *
11619     * @return Parent of this view.
11620     */
11621    public final ViewParent getParent() {
11622        return mParent;
11623    }
11624
11625    /**
11626     * Set the horizontal scrolled position of your view. This will cause a call to
11627     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11628     * invalidated.
11629     * @param value the x position to scroll to
11630     */
11631    public void setScrollX(int value) {
11632        scrollTo(value, mScrollY);
11633    }
11634
11635    /**
11636     * Set the vertical scrolled position of your view. This will cause a call to
11637     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11638     * invalidated.
11639     * @param value the y position to scroll to
11640     */
11641    public void setScrollY(int value) {
11642        scrollTo(mScrollX, value);
11643    }
11644
11645    /**
11646     * Return the scrolled left position of this view. This is the left edge of
11647     * the displayed part of your view. You do not need to draw any pixels
11648     * farther left, since those are outside of the frame of your view on
11649     * screen.
11650     *
11651     * @return The left edge of the displayed part of your view, in pixels.
11652     */
11653    public final int getScrollX() {
11654        return mScrollX;
11655    }
11656
11657    /**
11658     * Return the scrolled top position of this view. This is the top edge of
11659     * the displayed part of your view. You do not need to draw any pixels above
11660     * it, since those are outside of the frame of your view on screen.
11661     *
11662     * @return The top edge of the displayed part of your view, in pixels.
11663     */
11664    public final int getScrollY() {
11665        return mScrollY;
11666    }
11667
11668    /**
11669     * Return the width of the your view.
11670     *
11671     * @return The width of your view, in pixels.
11672     */
11673    @ViewDebug.ExportedProperty(category = "layout")
11674    public final int getWidth() {
11675        return mRight - mLeft;
11676    }
11677
11678    /**
11679     * Return the height of your view.
11680     *
11681     * @return The height of your view, in pixels.
11682     */
11683    @ViewDebug.ExportedProperty(category = "layout")
11684    public final int getHeight() {
11685        return mBottom - mTop;
11686    }
11687
11688    /**
11689     * Return the visible drawing bounds of your view. Fills in the output
11690     * rectangle with the values from getScrollX(), getScrollY(),
11691     * getWidth(), and getHeight(). These bounds do not account for any
11692     * transformation properties currently set on the view, such as
11693     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
11694     *
11695     * @param outRect The (scrolled) drawing bounds of the view.
11696     */
11697    public void getDrawingRect(Rect outRect) {
11698        outRect.left = mScrollX;
11699        outRect.top = mScrollY;
11700        outRect.right = mScrollX + (mRight - mLeft);
11701        outRect.bottom = mScrollY + (mBottom - mTop);
11702    }
11703
11704    /**
11705     * Like {@link #getMeasuredWidthAndState()}, but only returns the
11706     * raw width component (that is the result is masked by
11707     * {@link #MEASURED_SIZE_MASK}).
11708     *
11709     * @return The raw measured width of this view.
11710     */
11711    public final int getMeasuredWidth() {
11712        return mMeasuredWidth & MEASURED_SIZE_MASK;
11713    }
11714
11715    /**
11716     * Return the full width measurement information for this view as computed
11717     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11718     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11719     * This should be used during measurement and layout calculations only. Use
11720     * {@link #getWidth()} to see how wide a view is after layout.
11721     *
11722     * @return The measured width of this view as a bit mask.
11723     */
11724    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11725            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11726                    name = "MEASURED_STATE_TOO_SMALL"),
11727    })
11728    public final int getMeasuredWidthAndState() {
11729        return mMeasuredWidth;
11730    }
11731
11732    /**
11733     * Like {@link #getMeasuredHeightAndState()}, but only returns the
11734     * raw height component (that is the result is masked by
11735     * {@link #MEASURED_SIZE_MASK}).
11736     *
11737     * @return The raw measured height of this view.
11738     */
11739    public final int getMeasuredHeight() {
11740        return mMeasuredHeight & MEASURED_SIZE_MASK;
11741    }
11742
11743    /**
11744     * Return the full height measurement information for this view as computed
11745     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11746     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11747     * This should be used during measurement and layout calculations only. Use
11748     * {@link #getHeight()} to see how wide a view is after layout.
11749     *
11750     * @return The measured height of this view as a bit mask.
11751     */
11752    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11753            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11754                    name = "MEASURED_STATE_TOO_SMALL"),
11755    })
11756    public final int getMeasuredHeightAndState() {
11757        return mMeasuredHeight;
11758    }
11759
11760    /**
11761     * Return only the state bits of {@link #getMeasuredWidthAndState()}
11762     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
11763     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
11764     * and the height component is at the shifted bits
11765     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
11766     */
11767    public final int getMeasuredState() {
11768        return (mMeasuredWidth&MEASURED_STATE_MASK)
11769                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
11770                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
11771    }
11772
11773    /**
11774     * The transform matrix of this view, which is calculated based on the current
11775     * rotation, scale, and pivot properties.
11776     *
11777     * @see #getRotation()
11778     * @see #getScaleX()
11779     * @see #getScaleY()
11780     * @see #getPivotX()
11781     * @see #getPivotY()
11782     * @return The current transform matrix for the view
11783     */
11784    public Matrix getMatrix() {
11785        ensureTransformationInfo();
11786        final Matrix matrix = mTransformationInfo.mMatrix;
11787        mRenderNode.getMatrix(matrix);
11788        return matrix;
11789    }
11790
11791    /**
11792     * Returns true if the transform matrix is the identity matrix.
11793     * Recomputes the matrix if necessary.
11794     *
11795     * @return True if the transform matrix is the identity matrix, false otherwise.
11796     */
11797    final boolean hasIdentityMatrix() {
11798        return mRenderNode.hasIdentityMatrix();
11799    }
11800
11801    void ensureTransformationInfo() {
11802        if (mTransformationInfo == null) {
11803            mTransformationInfo = new TransformationInfo();
11804        }
11805    }
11806
11807    /**
11808     * Utility method to retrieve the inverse of the current mMatrix property.
11809     * We cache the matrix to avoid recalculating it when transform properties
11810     * have not changed.
11811     *
11812     * @return The inverse of the current matrix of this view.
11813     * @hide
11814     */
11815    public final Matrix getInverseMatrix() {
11816        ensureTransformationInfo();
11817        if (mTransformationInfo.mInverseMatrix == null) {
11818            mTransformationInfo.mInverseMatrix = new Matrix();
11819        }
11820        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11821        mRenderNode.getInverseMatrix(matrix);
11822        return matrix;
11823    }
11824
11825    /**
11826     * Gets the distance along the Z axis from the camera to this view.
11827     *
11828     * @see #setCameraDistance(float)
11829     *
11830     * @return The distance along the Z axis.
11831     */
11832    public float getCameraDistance() {
11833        final float dpi = mResources.getDisplayMetrics().densityDpi;
11834        return -(mRenderNode.getCameraDistance() * dpi);
11835    }
11836
11837    /**
11838     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11839     * views are drawn) from the camera to this view. The camera's distance
11840     * affects 3D transformations, for instance rotations around the X and Y
11841     * axis. If the rotationX or rotationY properties are changed and this view is
11842     * large (more than half the size of the screen), it is recommended to always
11843     * use a camera distance that's greater than the height (X axis rotation) or
11844     * the width (Y axis rotation) of this view.</p>
11845     *
11846     * <p>The distance of the camera from the view plane can have an affect on the
11847     * perspective distortion of the view when it is rotated around the x or y axis.
11848     * For example, a large distance will result in a large viewing angle, and there
11849     * will not be much perspective distortion of the view as it rotates. A short
11850     * distance may cause much more perspective distortion upon rotation, and can
11851     * also result in some drawing artifacts if the rotated view ends up partially
11852     * behind the camera (which is why the recommendation is to use a distance at
11853     * least as far as the size of the view, if the view is to be rotated.)</p>
11854     *
11855     * <p>The distance is expressed in "depth pixels." The default distance depends
11856     * on the screen density. For instance, on a medium density display, the
11857     * default distance is 1280. On a high density display, the default distance
11858     * is 1920.</p>
11859     *
11860     * <p>If you want to specify a distance that leads to visually consistent
11861     * results across various densities, use the following formula:</p>
11862     * <pre>
11863     * float scale = context.getResources().getDisplayMetrics().density;
11864     * view.setCameraDistance(distance * scale);
11865     * </pre>
11866     *
11867     * <p>The density scale factor of a high density display is 1.5,
11868     * and 1920 = 1280 * 1.5.</p>
11869     *
11870     * @param distance The distance in "depth pixels", if negative the opposite
11871     *        value is used
11872     *
11873     * @see #setRotationX(float)
11874     * @see #setRotationY(float)
11875     */
11876    public void setCameraDistance(float distance) {
11877        final float dpi = mResources.getDisplayMetrics().densityDpi;
11878
11879        invalidateViewProperty(true, false);
11880        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11881        invalidateViewProperty(false, false);
11882
11883        invalidateParentIfNeededAndWasQuickRejected();
11884    }
11885
11886    /**
11887     * The degrees that the view is rotated around the pivot point.
11888     *
11889     * @see #setRotation(float)
11890     * @see #getPivotX()
11891     * @see #getPivotY()
11892     *
11893     * @return The degrees of rotation.
11894     */
11895    @ViewDebug.ExportedProperty(category = "drawing")
11896    public float getRotation() {
11897        return mRenderNode.getRotation();
11898    }
11899
11900    /**
11901     * Sets the degrees that the view is rotated around the pivot point. Increasing values
11902     * result in clockwise rotation.
11903     *
11904     * @param rotation The degrees of rotation.
11905     *
11906     * @see #getRotation()
11907     * @see #getPivotX()
11908     * @see #getPivotY()
11909     * @see #setRotationX(float)
11910     * @see #setRotationY(float)
11911     *
11912     * @attr ref android.R.styleable#View_rotation
11913     */
11914    public void setRotation(float rotation) {
11915        if (rotation != getRotation()) {
11916            // Double-invalidation is necessary to capture view's old and new areas
11917            invalidateViewProperty(true, false);
11918            mRenderNode.setRotation(rotation);
11919            invalidateViewProperty(false, true);
11920
11921            invalidateParentIfNeededAndWasQuickRejected();
11922            notifySubtreeAccessibilityStateChangedIfNeeded();
11923        }
11924    }
11925
11926    /**
11927     * The degrees that the view is rotated around the vertical axis through the pivot point.
11928     *
11929     * @see #getPivotX()
11930     * @see #getPivotY()
11931     * @see #setRotationY(float)
11932     *
11933     * @return The degrees of Y rotation.
11934     */
11935    @ViewDebug.ExportedProperty(category = "drawing")
11936    public float getRotationY() {
11937        return mRenderNode.getRotationY();
11938    }
11939
11940    /**
11941     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
11942     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
11943     * down the y axis.
11944     *
11945     * When rotating large views, it is recommended to adjust the camera distance
11946     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11947     *
11948     * @param rotationY The degrees of Y rotation.
11949     *
11950     * @see #getRotationY()
11951     * @see #getPivotX()
11952     * @see #getPivotY()
11953     * @see #setRotation(float)
11954     * @see #setRotationX(float)
11955     * @see #setCameraDistance(float)
11956     *
11957     * @attr ref android.R.styleable#View_rotationY
11958     */
11959    public void setRotationY(float rotationY) {
11960        if (rotationY != getRotationY()) {
11961            invalidateViewProperty(true, false);
11962            mRenderNode.setRotationY(rotationY);
11963            invalidateViewProperty(false, true);
11964
11965            invalidateParentIfNeededAndWasQuickRejected();
11966            notifySubtreeAccessibilityStateChangedIfNeeded();
11967        }
11968    }
11969
11970    /**
11971     * The degrees that the view is rotated around the horizontal axis through the pivot point.
11972     *
11973     * @see #getPivotX()
11974     * @see #getPivotY()
11975     * @see #setRotationX(float)
11976     *
11977     * @return The degrees of X rotation.
11978     */
11979    @ViewDebug.ExportedProperty(category = "drawing")
11980    public float getRotationX() {
11981        return mRenderNode.getRotationX();
11982    }
11983
11984    /**
11985     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
11986     * Increasing values result in clockwise rotation from the viewpoint of looking down the
11987     * x axis.
11988     *
11989     * When rotating large views, it is recommended to adjust the camera distance
11990     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11991     *
11992     * @param rotationX The degrees of X rotation.
11993     *
11994     * @see #getRotationX()
11995     * @see #getPivotX()
11996     * @see #getPivotY()
11997     * @see #setRotation(float)
11998     * @see #setRotationY(float)
11999     * @see #setCameraDistance(float)
12000     *
12001     * @attr ref android.R.styleable#View_rotationX
12002     */
12003    public void setRotationX(float rotationX) {
12004        if (rotationX != getRotationX()) {
12005            invalidateViewProperty(true, false);
12006            mRenderNode.setRotationX(rotationX);
12007            invalidateViewProperty(false, true);
12008
12009            invalidateParentIfNeededAndWasQuickRejected();
12010            notifySubtreeAccessibilityStateChangedIfNeeded();
12011        }
12012    }
12013
12014    /**
12015     * The amount that the view is scaled in x around the pivot point, as a proportion of
12016     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12017     *
12018     * <p>By default, this is 1.0f.
12019     *
12020     * @see #getPivotX()
12021     * @see #getPivotY()
12022     * @return The scaling factor.
12023     */
12024    @ViewDebug.ExportedProperty(category = "drawing")
12025    public float getScaleX() {
12026        return mRenderNode.getScaleX();
12027    }
12028
12029    /**
12030     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12031     * the view's unscaled width. A value of 1 means that no scaling is applied.
12032     *
12033     * @param scaleX The scaling factor.
12034     * @see #getPivotX()
12035     * @see #getPivotY()
12036     *
12037     * @attr ref android.R.styleable#View_scaleX
12038     */
12039    public void setScaleX(float scaleX) {
12040        if (scaleX != getScaleX()) {
12041            invalidateViewProperty(true, false);
12042            mRenderNode.setScaleX(scaleX);
12043            invalidateViewProperty(false, true);
12044
12045            invalidateParentIfNeededAndWasQuickRejected();
12046            notifySubtreeAccessibilityStateChangedIfNeeded();
12047        }
12048    }
12049
12050    /**
12051     * The amount that the view is scaled in y around the pivot point, as a proportion of
12052     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12053     *
12054     * <p>By default, this is 1.0f.
12055     *
12056     * @see #getPivotX()
12057     * @see #getPivotY()
12058     * @return The scaling factor.
12059     */
12060    @ViewDebug.ExportedProperty(category = "drawing")
12061    public float getScaleY() {
12062        return mRenderNode.getScaleY();
12063    }
12064
12065    /**
12066     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12067     * the view's unscaled width. A value of 1 means that no scaling is applied.
12068     *
12069     * @param scaleY The scaling factor.
12070     * @see #getPivotX()
12071     * @see #getPivotY()
12072     *
12073     * @attr ref android.R.styleable#View_scaleY
12074     */
12075    public void setScaleY(float scaleY) {
12076        if (scaleY != getScaleY()) {
12077            invalidateViewProperty(true, false);
12078            mRenderNode.setScaleY(scaleY);
12079            invalidateViewProperty(false, true);
12080
12081            invalidateParentIfNeededAndWasQuickRejected();
12082            notifySubtreeAccessibilityStateChangedIfNeeded();
12083        }
12084    }
12085
12086    /**
12087     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12088     * and {@link #setScaleX(float) scaled}.
12089     *
12090     * @see #getRotation()
12091     * @see #getScaleX()
12092     * @see #getScaleY()
12093     * @see #getPivotY()
12094     * @return The x location of the pivot point.
12095     *
12096     * @attr ref android.R.styleable#View_transformPivotX
12097     */
12098    @ViewDebug.ExportedProperty(category = "drawing")
12099    public float getPivotX() {
12100        return mRenderNode.getPivotX();
12101    }
12102
12103    /**
12104     * Sets the x location of the point around which the view is
12105     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12106     * By default, the pivot point is centered on the object.
12107     * Setting this property disables this behavior and causes the view to use only the
12108     * explicitly set pivotX and pivotY values.
12109     *
12110     * @param pivotX The x location of the pivot point.
12111     * @see #getRotation()
12112     * @see #getScaleX()
12113     * @see #getScaleY()
12114     * @see #getPivotY()
12115     *
12116     * @attr ref android.R.styleable#View_transformPivotX
12117     */
12118    public void setPivotX(float pivotX) {
12119        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12120            invalidateViewProperty(true, false);
12121            mRenderNode.setPivotX(pivotX);
12122            invalidateViewProperty(false, true);
12123
12124            invalidateParentIfNeededAndWasQuickRejected();
12125        }
12126    }
12127
12128    /**
12129     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12130     * and {@link #setScaleY(float) scaled}.
12131     *
12132     * @see #getRotation()
12133     * @see #getScaleX()
12134     * @see #getScaleY()
12135     * @see #getPivotY()
12136     * @return The y location of the pivot point.
12137     *
12138     * @attr ref android.R.styleable#View_transformPivotY
12139     */
12140    @ViewDebug.ExportedProperty(category = "drawing")
12141    public float getPivotY() {
12142        return mRenderNode.getPivotY();
12143    }
12144
12145    /**
12146     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12147     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12148     * Setting this property disables this behavior and causes the view to use only the
12149     * explicitly set pivotX and pivotY values.
12150     *
12151     * @param pivotY The y location of the pivot point.
12152     * @see #getRotation()
12153     * @see #getScaleX()
12154     * @see #getScaleY()
12155     * @see #getPivotY()
12156     *
12157     * @attr ref android.R.styleable#View_transformPivotY
12158     */
12159    public void setPivotY(float pivotY) {
12160        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12161            invalidateViewProperty(true, false);
12162            mRenderNode.setPivotY(pivotY);
12163            invalidateViewProperty(false, true);
12164
12165            invalidateParentIfNeededAndWasQuickRejected();
12166        }
12167    }
12168
12169    /**
12170     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12171     * completely transparent and 1 means the view is completely opaque.
12172     *
12173     * <p>By default this is 1.0f.
12174     * @return The opacity of the view.
12175     */
12176    @ViewDebug.ExportedProperty(category = "drawing")
12177    public float getAlpha() {
12178        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12179    }
12180
12181    /**
12182     * Sets the behavior for overlapping rendering for this view (see {@link
12183     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12184     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12185     * providing the value which is then used internally. That is, when {@link
12186     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12187     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12188     * instead.
12189     *
12190     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12191     * instead of that returned by {@link #hasOverlappingRendering()}.
12192     *
12193     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12194     */
12195    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12196        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12197        if (hasOverlappingRendering) {
12198            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12199        } else {
12200            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12201        }
12202    }
12203
12204    /**
12205     * Returns the value for overlapping rendering that is used internally. This is either
12206     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12207     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12208     *
12209     * @return The value for overlapping rendering being used internally.
12210     */
12211    public final boolean getHasOverlappingRendering() {
12212        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12213                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12214                hasOverlappingRendering();
12215    }
12216
12217    /**
12218     * Returns whether this View has content which overlaps.
12219     *
12220     * <p>This function, intended to be overridden by specific View types, is an optimization when
12221     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12222     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12223     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12224     * directly. An example of overlapping rendering is a TextView with a background image, such as
12225     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12226     * ImageView with only the foreground image. The default implementation returns true; subclasses
12227     * should override if they have cases which can be optimized.</p>
12228     *
12229     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12230     * necessitates that a View return true if it uses the methods internally without passing the
12231     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12232     *
12233     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12234     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12235     *
12236     * @return true if the content in this view might overlap, false otherwise.
12237     */
12238    @ViewDebug.ExportedProperty(category = "drawing")
12239    public boolean hasOverlappingRendering() {
12240        return true;
12241    }
12242
12243    /**
12244     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12245     * completely transparent and 1 means the view is completely opaque.
12246     *
12247     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12248     * can have significant performance implications, especially for large views. It is best to use
12249     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12250     *
12251     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12252     * strongly recommended for performance reasons to either override
12253     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12254     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12255     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12256     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12257     * of rendering cost, even for simple or small views. Starting with
12258     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12259     * applied to the view at the rendering level.</p>
12260     *
12261     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12262     * responsible for applying the opacity itself.</p>
12263     *
12264     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12265     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12266     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12267     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12268     *
12269     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12270     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12271     * {@link #hasOverlappingRendering}.</p>
12272     *
12273     * @param alpha The opacity of the view.
12274     *
12275     * @see #hasOverlappingRendering()
12276     * @see #setLayerType(int, android.graphics.Paint)
12277     *
12278     * @attr ref android.R.styleable#View_alpha
12279     */
12280    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12281        ensureTransformationInfo();
12282        if (mTransformationInfo.mAlpha != alpha) {
12283            mTransformationInfo.mAlpha = alpha;
12284            if (onSetAlpha((int) (alpha * 255))) {
12285                mPrivateFlags |= PFLAG_ALPHA_SET;
12286                // subclass is handling alpha - don't optimize rendering cache invalidation
12287                invalidateParentCaches();
12288                invalidate(true);
12289            } else {
12290                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12291                invalidateViewProperty(true, false);
12292                mRenderNode.setAlpha(getFinalAlpha());
12293                notifyViewAccessibilityStateChangedIfNeeded(
12294                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12295            }
12296        }
12297    }
12298
12299    /**
12300     * Faster version of setAlpha() which performs the same steps except there are
12301     * no calls to invalidate(). The caller of this function should perform proper invalidation
12302     * on the parent and this object. The return value indicates whether the subclass handles
12303     * alpha (the return value for onSetAlpha()).
12304     *
12305     * @param alpha The new value for the alpha property
12306     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
12307     *         the new value for the alpha property is different from the old value
12308     */
12309    boolean setAlphaNoInvalidation(float alpha) {
12310        ensureTransformationInfo();
12311        if (mTransformationInfo.mAlpha != alpha) {
12312            mTransformationInfo.mAlpha = alpha;
12313            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
12314            if (subclassHandlesAlpha) {
12315                mPrivateFlags |= PFLAG_ALPHA_SET;
12316                return true;
12317            } else {
12318                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12319                mRenderNode.setAlpha(getFinalAlpha());
12320            }
12321        }
12322        return false;
12323    }
12324
12325    /**
12326     * This property is hidden and intended only for use by the Fade transition, which
12327     * animates it to produce a visual translucency that does not side-effect (or get
12328     * affected by) the real alpha property. This value is composited with the other
12329     * alpha value (and the AlphaAnimation value, when that is present) to produce
12330     * a final visual translucency result, which is what is passed into the DisplayList.
12331     *
12332     * @hide
12333     */
12334    public void setTransitionAlpha(float alpha) {
12335        ensureTransformationInfo();
12336        if (mTransformationInfo.mTransitionAlpha != alpha) {
12337            mTransformationInfo.mTransitionAlpha = alpha;
12338            mPrivateFlags &= ~PFLAG_ALPHA_SET;
12339            invalidateViewProperty(true, false);
12340            mRenderNode.setAlpha(getFinalAlpha());
12341        }
12342    }
12343
12344    /**
12345     * Calculates the visual alpha of this view, which is a combination of the actual
12346     * alpha value and the transitionAlpha value (if set).
12347     */
12348    private float getFinalAlpha() {
12349        if (mTransformationInfo != null) {
12350            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
12351        }
12352        return 1;
12353    }
12354
12355    /**
12356     * This property is hidden and intended only for use by the Fade transition, which
12357     * animates it to produce a visual translucency that does not side-effect (or get
12358     * affected by) the real alpha property. This value is composited with the other
12359     * alpha value (and the AlphaAnimation value, when that is present) to produce
12360     * a final visual translucency result, which is what is passed into the DisplayList.
12361     *
12362     * @hide
12363     */
12364    @ViewDebug.ExportedProperty(category = "drawing")
12365    public float getTransitionAlpha() {
12366        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
12367    }
12368
12369    /**
12370     * Top position of this view relative to its parent.
12371     *
12372     * @return The top of this view, in pixels.
12373     */
12374    @ViewDebug.CapturedViewProperty
12375    public final int getTop() {
12376        return mTop;
12377    }
12378
12379    /**
12380     * Sets the top position of this view relative to its parent. This method is meant to be called
12381     * by the layout system and should not generally be called otherwise, because the property
12382     * may be changed at any time by the layout.
12383     *
12384     * @param top The top of this view, in pixels.
12385     */
12386    public final void setTop(int top) {
12387        if (top != mTop) {
12388            final boolean matrixIsIdentity = hasIdentityMatrix();
12389            if (matrixIsIdentity) {
12390                if (mAttachInfo != null) {
12391                    int minTop;
12392                    int yLoc;
12393                    if (top < mTop) {
12394                        minTop = top;
12395                        yLoc = top - mTop;
12396                    } else {
12397                        minTop = mTop;
12398                        yLoc = 0;
12399                    }
12400                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
12401                }
12402            } else {
12403                // Double-invalidation is necessary to capture view's old and new areas
12404                invalidate(true);
12405            }
12406
12407            int width = mRight - mLeft;
12408            int oldHeight = mBottom - mTop;
12409
12410            mTop = top;
12411            mRenderNode.setTop(mTop);
12412
12413            sizeChange(width, mBottom - mTop, width, oldHeight);
12414
12415            if (!matrixIsIdentity) {
12416                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12417                invalidate(true);
12418            }
12419            mBackgroundSizeChanged = true;
12420            if (mForegroundInfo != null) {
12421                mForegroundInfo.mBoundsChanged = true;
12422            }
12423            invalidateParentIfNeeded();
12424            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12425                // View was rejected last time it was drawn by its parent; this may have changed
12426                invalidateParentIfNeeded();
12427            }
12428        }
12429    }
12430
12431    /**
12432     * Bottom position of this view relative to its parent.
12433     *
12434     * @return The bottom of this view, in pixels.
12435     */
12436    @ViewDebug.CapturedViewProperty
12437    public final int getBottom() {
12438        return mBottom;
12439    }
12440
12441    /**
12442     * True if this view has changed since the last time being drawn.
12443     *
12444     * @return The dirty state of this view.
12445     */
12446    public boolean isDirty() {
12447        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
12448    }
12449
12450    /**
12451     * Sets the bottom position of this view relative to its parent. This method is meant to be
12452     * called by the layout system and should not generally be called otherwise, because the
12453     * property may be changed at any time by the layout.
12454     *
12455     * @param bottom The bottom of this view, in pixels.
12456     */
12457    public final void setBottom(int bottom) {
12458        if (bottom != mBottom) {
12459            final boolean matrixIsIdentity = hasIdentityMatrix();
12460            if (matrixIsIdentity) {
12461                if (mAttachInfo != null) {
12462                    int maxBottom;
12463                    if (bottom < mBottom) {
12464                        maxBottom = mBottom;
12465                    } else {
12466                        maxBottom = bottom;
12467                    }
12468                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
12469                }
12470            } else {
12471                // Double-invalidation is necessary to capture view's old and new areas
12472                invalidate(true);
12473            }
12474
12475            int width = mRight - mLeft;
12476            int oldHeight = mBottom - mTop;
12477
12478            mBottom = bottom;
12479            mRenderNode.setBottom(mBottom);
12480
12481            sizeChange(width, mBottom - mTop, width, oldHeight);
12482
12483            if (!matrixIsIdentity) {
12484                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12485                invalidate(true);
12486            }
12487            mBackgroundSizeChanged = true;
12488            if (mForegroundInfo != null) {
12489                mForegroundInfo.mBoundsChanged = true;
12490            }
12491            invalidateParentIfNeeded();
12492            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12493                // View was rejected last time it was drawn by its parent; this may have changed
12494                invalidateParentIfNeeded();
12495            }
12496        }
12497    }
12498
12499    /**
12500     * Left position of this view relative to its parent.
12501     *
12502     * @return The left edge of this view, in pixels.
12503     */
12504    @ViewDebug.CapturedViewProperty
12505    public final int getLeft() {
12506        return mLeft;
12507    }
12508
12509    /**
12510     * Sets the left position of this view relative to its parent. This method is meant to be called
12511     * by the layout system and should not generally be called otherwise, because the property
12512     * may be changed at any time by the layout.
12513     *
12514     * @param left The left of this view, in pixels.
12515     */
12516    public final void setLeft(int left) {
12517        if (left != mLeft) {
12518            final boolean matrixIsIdentity = hasIdentityMatrix();
12519            if (matrixIsIdentity) {
12520                if (mAttachInfo != null) {
12521                    int minLeft;
12522                    int xLoc;
12523                    if (left < mLeft) {
12524                        minLeft = left;
12525                        xLoc = left - mLeft;
12526                    } else {
12527                        minLeft = mLeft;
12528                        xLoc = 0;
12529                    }
12530                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
12531                }
12532            } else {
12533                // Double-invalidation is necessary to capture view's old and new areas
12534                invalidate(true);
12535            }
12536
12537            int oldWidth = mRight - mLeft;
12538            int height = mBottom - mTop;
12539
12540            mLeft = left;
12541            mRenderNode.setLeft(left);
12542
12543            sizeChange(mRight - mLeft, height, oldWidth, height);
12544
12545            if (!matrixIsIdentity) {
12546                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12547                invalidate(true);
12548            }
12549            mBackgroundSizeChanged = true;
12550            if (mForegroundInfo != null) {
12551                mForegroundInfo.mBoundsChanged = true;
12552            }
12553            invalidateParentIfNeeded();
12554            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12555                // View was rejected last time it was drawn by its parent; this may have changed
12556                invalidateParentIfNeeded();
12557            }
12558        }
12559    }
12560
12561    /**
12562     * Right position of this view relative to its parent.
12563     *
12564     * @return The right edge of this view, in pixels.
12565     */
12566    @ViewDebug.CapturedViewProperty
12567    public final int getRight() {
12568        return mRight;
12569    }
12570
12571    /**
12572     * Sets the right position of this view relative to its parent. This method is meant to be called
12573     * by the layout system and should not generally be called otherwise, because the property
12574     * may be changed at any time by the layout.
12575     *
12576     * @param right The right of this view, in pixels.
12577     */
12578    public final void setRight(int right) {
12579        if (right != mRight) {
12580            final boolean matrixIsIdentity = hasIdentityMatrix();
12581            if (matrixIsIdentity) {
12582                if (mAttachInfo != null) {
12583                    int maxRight;
12584                    if (right < mRight) {
12585                        maxRight = mRight;
12586                    } else {
12587                        maxRight = right;
12588                    }
12589                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
12590                }
12591            } else {
12592                // Double-invalidation is necessary to capture view's old and new areas
12593                invalidate(true);
12594            }
12595
12596            int oldWidth = mRight - mLeft;
12597            int height = mBottom - mTop;
12598
12599            mRight = right;
12600            mRenderNode.setRight(mRight);
12601
12602            sizeChange(mRight - mLeft, height, oldWidth, height);
12603
12604            if (!matrixIsIdentity) {
12605                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12606                invalidate(true);
12607            }
12608            mBackgroundSizeChanged = true;
12609            if (mForegroundInfo != null) {
12610                mForegroundInfo.mBoundsChanged = true;
12611            }
12612            invalidateParentIfNeeded();
12613            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12614                // View was rejected last time it was drawn by its parent; this may have changed
12615                invalidateParentIfNeeded();
12616            }
12617        }
12618    }
12619
12620    /**
12621     * The visual x position of this view, in pixels. This is equivalent to the
12622     * {@link #setTranslationX(float) translationX} property plus the current
12623     * {@link #getLeft() left} property.
12624     *
12625     * @return The visual x position of this view, in pixels.
12626     */
12627    @ViewDebug.ExportedProperty(category = "drawing")
12628    public float getX() {
12629        return mLeft + getTranslationX();
12630    }
12631
12632    /**
12633     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
12634     * {@link #setTranslationX(float) translationX} property to be the difference between
12635     * the x value passed in and the current {@link #getLeft() left} property.
12636     *
12637     * @param x The visual x position of this view, in pixels.
12638     */
12639    public void setX(float x) {
12640        setTranslationX(x - mLeft);
12641    }
12642
12643    /**
12644     * The visual y position of this view, in pixels. This is equivalent to the
12645     * {@link #setTranslationY(float) translationY} property plus the current
12646     * {@link #getTop() top} property.
12647     *
12648     * @return The visual y position of this view, in pixels.
12649     */
12650    @ViewDebug.ExportedProperty(category = "drawing")
12651    public float getY() {
12652        return mTop + getTranslationY();
12653    }
12654
12655    /**
12656     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
12657     * {@link #setTranslationY(float) translationY} property to be the difference between
12658     * the y value passed in and the current {@link #getTop() top} property.
12659     *
12660     * @param y The visual y position of this view, in pixels.
12661     */
12662    public void setY(float y) {
12663        setTranslationY(y - mTop);
12664    }
12665
12666    /**
12667     * The visual z position of this view, in pixels. This is equivalent to the
12668     * {@link #setTranslationZ(float) translationZ} property plus the current
12669     * {@link #getElevation() elevation} property.
12670     *
12671     * @return The visual z position of this view, in pixels.
12672     */
12673    @ViewDebug.ExportedProperty(category = "drawing")
12674    public float getZ() {
12675        return getElevation() + getTranslationZ();
12676    }
12677
12678    /**
12679     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
12680     * {@link #setTranslationZ(float) translationZ} property to be the difference between
12681     * the x value passed in and the current {@link #getElevation() elevation} property.
12682     *
12683     * @param z The visual z position of this view, in pixels.
12684     */
12685    public void setZ(float z) {
12686        setTranslationZ(z - getElevation());
12687    }
12688
12689    /**
12690     * The base elevation of this view relative to its parent, in pixels.
12691     *
12692     * @return The base depth position of the view, in pixels.
12693     */
12694    @ViewDebug.ExportedProperty(category = "drawing")
12695    public float getElevation() {
12696        return mRenderNode.getElevation();
12697    }
12698
12699    /**
12700     * Sets the base elevation of this view, in pixels.
12701     *
12702     * @attr ref android.R.styleable#View_elevation
12703     */
12704    public void setElevation(float elevation) {
12705        if (elevation != getElevation()) {
12706            invalidateViewProperty(true, false);
12707            mRenderNode.setElevation(elevation);
12708            invalidateViewProperty(false, true);
12709
12710            invalidateParentIfNeededAndWasQuickRejected();
12711        }
12712    }
12713
12714    /**
12715     * The horizontal location of this view relative to its {@link #getLeft() left} position.
12716     * This position is post-layout, in addition to wherever the object's
12717     * layout placed it.
12718     *
12719     * @return The horizontal position of this view relative to its left position, in pixels.
12720     */
12721    @ViewDebug.ExportedProperty(category = "drawing")
12722    public float getTranslationX() {
12723        return mRenderNode.getTranslationX();
12724    }
12725
12726    /**
12727     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
12728     * This effectively positions the object post-layout, in addition to wherever the object's
12729     * layout placed it.
12730     *
12731     * @param translationX The horizontal position of this view relative to its left position,
12732     * in pixels.
12733     *
12734     * @attr ref android.R.styleable#View_translationX
12735     */
12736    public void setTranslationX(float translationX) {
12737        if (translationX != getTranslationX()) {
12738            invalidateViewProperty(true, false);
12739            mRenderNode.setTranslationX(translationX);
12740            invalidateViewProperty(false, true);
12741
12742            invalidateParentIfNeededAndWasQuickRejected();
12743            notifySubtreeAccessibilityStateChangedIfNeeded();
12744        }
12745    }
12746
12747    /**
12748     * The vertical location of this view relative to its {@link #getTop() top} position.
12749     * This position is post-layout, in addition to wherever the object's
12750     * layout placed it.
12751     *
12752     * @return The vertical position of this view relative to its top position,
12753     * in pixels.
12754     */
12755    @ViewDebug.ExportedProperty(category = "drawing")
12756    public float getTranslationY() {
12757        return mRenderNode.getTranslationY();
12758    }
12759
12760    /**
12761     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
12762     * This effectively positions the object post-layout, in addition to wherever the object's
12763     * layout placed it.
12764     *
12765     * @param translationY The vertical position of this view relative to its top position,
12766     * in pixels.
12767     *
12768     * @attr ref android.R.styleable#View_translationY
12769     */
12770    public void setTranslationY(float translationY) {
12771        if (translationY != getTranslationY()) {
12772            invalidateViewProperty(true, false);
12773            mRenderNode.setTranslationY(translationY);
12774            invalidateViewProperty(false, true);
12775
12776            invalidateParentIfNeededAndWasQuickRejected();
12777            notifySubtreeAccessibilityStateChangedIfNeeded();
12778        }
12779    }
12780
12781    /**
12782     * The depth location of this view relative to its {@link #getElevation() elevation}.
12783     *
12784     * @return The depth of this view relative to its elevation.
12785     */
12786    @ViewDebug.ExportedProperty(category = "drawing")
12787    public float getTranslationZ() {
12788        return mRenderNode.getTranslationZ();
12789    }
12790
12791    /**
12792     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
12793     *
12794     * @attr ref android.R.styleable#View_translationZ
12795     */
12796    public void setTranslationZ(float translationZ) {
12797        if (translationZ != getTranslationZ()) {
12798            invalidateViewProperty(true, false);
12799            mRenderNode.setTranslationZ(translationZ);
12800            invalidateViewProperty(false, true);
12801
12802            invalidateParentIfNeededAndWasQuickRejected();
12803        }
12804    }
12805
12806    /** @hide */
12807    public void setAnimationMatrix(Matrix matrix) {
12808        invalidateViewProperty(true, false);
12809        mRenderNode.setAnimationMatrix(matrix);
12810        invalidateViewProperty(false, true);
12811
12812        invalidateParentIfNeededAndWasQuickRejected();
12813    }
12814
12815    /**
12816     * Returns the current StateListAnimator if exists.
12817     *
12818     * @return StateListAnimator or null if it does not exists
12819     * @see    #setStateListAnimator(android.animation.StateListAnimator)
12820     */
12821    public StateListAnimator getStateListAnimator() {
12822        return mStateListAnimator;
12823    }
12824
12825    /**
12826     * Attaches the provided StateListAnimator to this View.
12827     * <p>
12828     * Any previously attached StateListAnimator will be detached.
12829     *
12830     * @param stateListAnimator The StateListAnimator to update the view
12831     * @see {@link android.animation.StateListAnimator}
12832     */
12833    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12834        if (mStateListAnimator == stateListAnimator) {
12835            return;
12836        }
12837        if (mStateListAnimator != null) {
12838            mStateListAnimator.setTarget(null);
12839        }
12840        mStateListAnimator = stateListAnimator;
12841        if (stateListAnimator != null) {
12842            stateListAnimator.setTarget(this);
12843            if (isAttachedToWindow()) {
12844                stateListAnimator.setState(getDrawableState());
12845            }
12846        }
12847    }
12848
12849    /**
12850     * Returns whether the Outline should be used to clip the contents of the View.
12851     * <p>
12852     * Note that this flag will only be respected if the View's Outline returns true from
12853     * {@link Outline#canClip()}.
12854     *
12855     * @see #setOutlineProvider(ViewOutlineProvider)
12856     * @see #setClipToOutline(boolean)
12857     */
12858    public final boolean getClipToOutline() {
12859        return mRenderNode.getClipToOutline();
12860    }
12861
12862    /**
12863     * Sets whether the View's Outline should be used to clip the contents of the View.
12864     * <p>
12865     * Only a single non-rectangular clip can be applied on a View at any time.
12866     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12867     * circular reveal} animation take priority over Outline clipping, and
12868     * child Outline clipping takes priority over Outline clipping done by a
12869     * parent.
12870     * <p>
12871     * Note that this flag will only be respected if the View's Outline returns true from
12872     * {@link Outline#canClip()}.
12873     *
12874     * @see #setOutlineProvider(ViewOutlineProvider)
12875     * @see #getClipToOutline()
12876     */
12877    public void setClipToOutline(boolean clipToOutline) {
12878        damageInParent();
12879        if (getClipToOutline() != clipToOutline) {
12880            mRenderNode.setClipToOutline(clipToOutline);
12881        }
12882    }
12883
12884    // correspond to the enum values of View_outlineProvider
12885    private static final int PROVIDER_BACKGROUND = 0;
12886    private static final int PROVIDER_NONE = 1;
12887    private static final int PROVIDER_BOUNDS = 2;
12888    private static final int PROVIDER_PADDED_BOUNDS = 3;
12889    private void setOutlineProviderFromAttribute(int providerInt) {
12890        switch (providerInt) {
12891            case PROVIDER_BACKGROUND:
12892                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
12893                break;
12894            case PROVIDER_NONE:
12895                setOutlineProvider(null);
12896                break;
12897            case PROVIDER_BOUNDS:
12898                setOutlineProvider(ViewOutlineProvider.BOUNDS);
12899                break;
12900            case PROVIDER_PADDED_BOUNDS:
12901                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
12902                break;
12903        }
12904    }
12905
12906    /**
12907     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
12908     * the shape of the shadow it casts, and enables outline clipping.
12909     * <p>
12910     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
12911     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
12912     * outline provider with this method allows this behavior to be overridden.
12913     * <p>
12914     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
12915     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
12916     * <p>
12917     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
12918     *
12919     * @see #setClipToOutline(boolean)
12920     * @see #getClipToOutline()
12921     * @see #getOutlineProvider()
12922     */
12923    public void setOutlineProvider(ViewOutlineProvider provider) {
12924        mOutlineProvider = provider;
12925        invalidateOutline();
12926    }
12927
12928    /**
12929     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
12930     * that defines the shape of the shadow it casts, and enables outline clipping.
12931     *
12932     * @see #setOutlineProvider(ViewOutlineProvider)
12933     */
12934    public ViewOutlineProvider getOutlineProvider() {
12935        return mOutlineProvider;
12936    }
12937
12938    /**
12939     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
12940     *
12941     * @see #setOutlineProvider(ViewOutlineProvider)
12942     */
12943    public void invalidateOutline() {
12944        rebuildOutline();
12945
12946        notifySubtreeAccessibilityStateChangedIfNeeded();
12947        invalidateViewProperty(false, false);
12948    }
12949
12950    /**
12951     * Internal version of {@link #invalidateOutline()} which invalidates the
12952     * outline without invalidating the view itself. This is intended to be called from
12953     * within methods in the View class itself which are the result of the view being
12954     * invalidated already. For example, when we are drawing the background of a View,
12955     * we invalidate the outline in case it changed in the meantime, but we do not
12956     * need to invalidate the view because we're already drawing the background as part
12957     * of drawing the view in response to an earlier invalidation of the view.
12958     */
12959    private void rebuildOutline() {
12960        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
12961        if (mAttachInfo == null) return;
12962
12963        if (mOutlineProvider == null) {
12964            // no provider, remove outline
12965            mRenderNode.setOutline(null);
12966        } else {
12967            final Outline outline = mAttachInfo.mTmpOutline;
12968            outline.setEmpty();
12969            outline.setAlpha(1.0f);
12970
12971            mOutlineProvider.getOutline(this, outline);
12972            mRenderNode.setOutline(outline);
12973        }
12974    }
12975
12976    /**
12977     * HierarchyViewer only
12978     *
12979     * @hide
12980     */
12981    @ViewDebug.ExportedProperty(category = "drawing")
12982    public boolean hasShadow() {
12983        return mRenderNode.hasShadow();
12984    }
12985
12986
12987    /** @hide */
12988    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
12989        mRenderNode.setRevealClip(shouldClip, x, y, radius);
12990        invalidateViewProperty(false, false);
12991    }
12992
12993    /**
12994     * Hit rectangle in parent's coordinates
12995     *
12996     * @param outRect The hit rectangle of the view.
12997     */
12998    public void getHitRect(Rect outRect) {
12999        if (hasIdentityMatrix() || mAttachInfo == null) {
13000            outRect.set(mLeft, mTop, mRight, mBottom);
13001        } else {
13002            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13003            tmpRect.set(0, 0, getWidth(), getHeight());
13004            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13005            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13006                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13007        }
13008    }
13009
13010    /**
13011     * Determines whether the given point, in local coordinates is inside the view.
13012     */
13013    /*package*/ final boolean pointInView(float localX, float localY) {
13014        return pointInView(localX, localY, 0);
13015    }
13016
13017    /**
13018     * Utility method to determine whether the given point, in local coordinates,
13019     * is inside the view, where the area of the view is expanded by the slop factor.
13020     * This method is called while processing touch-move events to determine if the event
13021     * is still within the view.
13022     *
13023     * @hide
13024     */
13025    public boolean pointInView(float localX, float localY, float slop) {
13026        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13027                localY < ((mBottom - mTop) + slop);
13028    }
13029
13030    /**
13031     * When a view has focus and the user navigates away from it, the next view is searched for
13032     * starting from the rectangle filled in by this method.
13033     *
13034     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13035     * of the view.  However, if your view maintains some idea of internal selection,
13036     * such as a cursor, or a selected row or column, you should override this method and
13037     * fill in a more specific rectangle.
13038     *
13039     * @param r The rectangle to fill in, in this view's coordinates.
13040     */
13041    public void getFocusedRect(Rect r) {
13042        getDrawingRect(r);
13043    }
13044
13045    /**
13046     * If some part of this view is not clipped by any of its parents, then
13047     * return that area in r in global (root) coordinates. To convert r to local
13048     * coordinates (without taking possible View rotations into account), offset
13049     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13050     * If the view is completely clipped or translated out, return false.
13051     *
13052     * @param r If true is returned, r holds the global coordinates of the
13053     *        visible portion of this view.
13054     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13055     *        between this view and its root. globalOffet may be null.
13056     * @return true if r is non-empty (i.e. part of the view is visible at the
13057     *         root level.
13058     */
13059    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13060        int width = mRight - mLeft;
13061        int height = mBottom - mTop;
13062        if (width > 0 && height > 0) {
13063            r.set(0, 0, width, height);
13064            if (globalOffset != null) {
13065                globalOffset.set(-mScrollX, -mScrollY);
13066            }
13067            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13068        }
13069        return false;
13070    }
13071
13072    public final boolean getGlobalVisibleRect(Rect r) {
13073        return getGlobalVisibleRect(r, null);
13074    }
13075
13076    public final boolean getLocalVisibleRect(Rect r) {
13077        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13078        if (getGlobalVisibleRect(r, offset)) {
13079            r.offset(-offset.x, -offset.y); // make r local
13080            return true;
13081        }
13082        return false;
13083    }
13084
13085    /**
13086     * Offset this view's vertical location by the specified number of pixels.
13087     *
13088     * @param offset the number of pixels to offset the view by
13089     */
13090    public void offsetTopAndBottom(int offset) {
13091        if (offset != 0) {
13092            final boolean matrixIsIdentity = hasIdentityMatrix();
13093            if (matrixIsIdentity) {
13094                if (isHardwareAccelerated()) {
13095                    invalidateViewProperty(false, false);
13096                } else {
13097                    final ViewParent p = mParent;
13098                    if (p != null && mAttachInfo != null) {
13099                        final Rect r = mAttachInfo.mTmpInvalRect;
13100                        int minTop;
13101                        int maxBottom;
13102                        int yLoc;
13103                        if (offset < 0) {
13104                            minTop = mTop + offset;
13105                            maxBottom = mBottom;
13106                            yLoc = offset;
13107                        } else {
13108                            minTop = mTop;
13109                            maxBottom = mBottom + offset;
13110                            yLoc = 0;
13111                        }
13112                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13113                        p.invalidateChild(this, r);
13114                    }
13115                }
13116            } else {
13117                invalidateViewProperty(false, false);
13118            }
13119
13120            mTop += offset;
13121            mBottom += offset;
13122            mRenderNode.offsetTopAndBottom(offset);
13123            if (isHardwareAccelerated()) {
13124                invalidateViewProperty(false, false);
13125                invalidateParentIfNeededAndWasQuickRejected();
13126            } else {
13127                if (!matrixIsIdentity) {
13128                    invalidateViewProperty(false, true);
13129                }
13130                invalidateParentIfNeeded();
13131            }
13132            notifySubtreeAccessibilityStateChangedIfNeeded();
13133        }
13134    }
13135
13136    /**
13137     * Offset this view's horizontal location by the specified amount of pixels.
13138     *
13139     * @param offset the number of pixels to offset the view by
13140     */
13141    public void offsetLeftAndRight(int offset) {
13142        if (offset != 0) {
13143            final boolean matrixIsIdentity = hasIdentityMatrix();
13144            if (matrixIsIdentity) {
13145                if (isHardwareAccelerated()) {
13146                    invalidateViewProperty(false, false);
13147                } else {
13148                    final ViewParent p = mParent;
13149                    if (p != null && mAttachInfo != null) {
13150                        final Rect r = mAttachInfo.mTmpInvalRect;
13151                        int minLeft;
13152                        int maxRight;
13153                        if (offset < 0) {
13154                            minLeft = mLeft + offset;
13155                            maxRight = mRight;
13156                        } else {
13157                            minLeft = mLeft;
13158                            maxRight = mRight + offset;
13159                        }
13160                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13161                        p.invalidateChild(this, r);
13162                    }
13163                }
13164            } else {
13165                invalidateViewProperty(false, false);
13166            }
13167
13168            mLeft += offset;
13169            mRight += offset;
13170            mRenderNode.offsetLeftAndRight(offset);
13171            if (isHardwareAccelerated()) {
13172                invalidateViewProperty(false, false);
13173                invalidateParentIfNeededAndWasQuickRejected();
13174            } else {
13175                if (!matrixIsIdentity) {
13176                    invalidateViewProperty(false, true);
13177                }
13178                invalidateParentIfNeeded();
13179            }
13180            notifySubtreeAccessibilityStateChangedIfNeeded();
13181        }
13182    }
13183
13184    /**
13185     * Get the LayoutParams associated with this view. All views should have
13186     * layout parameters. These supply parameters to the <i>parent</i> of this
13187     * view specifying how it should be arranged. There are many subclasses of
13188     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13189     * of ViewGroup that are responsible for arranging their children.
13190     *
13191     * This method may return null if this View is not attached to a parent
13192     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13193     * was not invoked successfully. When a View is attached to a parent
13194     * ViewGroup, this method must not return null.
13195     *
13196     * @return The LayoutParams associated with this view, or null if no
13197     *         parameters have been set yet
13198     */
13199    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13200    public ViewGroup.LayoutParams getLayoutParams() {
13201        return mLayoutParams;
13202    }
13203
13204    /**
13205     * Set the layout parameters associated with this view. These supply
13206     * parameters to the <i>parent</i> of this view specifying how it should be
13207     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13208     * correspond to the different subclasses of ViewGroup that are responsible
13209     * for arranging their children.
13210     *
13211     * @param params The layout parameters for this view, cannot be null
13212     */
13213    public void setLayoutParams(ViewGroup.LayoutParams params) {
13214        if (params == null) {
13215            throw new NullPointerException("Layout parameters cannot be null");
13216        }
13217        mLayoutParams = params;
13218        resolveLayoutParams();
13219        if (mParent instanceof ViewGroup) {
13220            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13221        }
13222        requestLayout();
13223    }
13224
13225    /**
13226     * Resolve the layout parameters depending on the resolved layout direction
13227     *
13228     * @hide
13229     */
13230    public void resolveLayoutParams() {
13231        if (mLayoutParams != null) {
13232            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13233        }
13234    }
13235
13236    /**
13237     * Set the scrolled position of your view. This will cause a call to
13238     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13239     * invalidated.
13240     * @param x the x position to scroll to
13241     * @param y the y position to scroll to
13242     */
13243    public void scrollTo(int x, int y) {
13244        if (mScrollX != x || mScrollY != y) {
13245            int oldX = mScrollX;
13246            int oldY = mScrollY;
13247            mScrollX = x;
13248            mScrollY = y;
13249            invalidateParentCaches();
13250            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13251            if (!awakenScrollBars()) {
13252                postInvalidateOnAnimation();
13253            }
13254        }
13255    }
13256
13257    /**
13258     * Move the scrolled position of your view. This will cause a call to
13259     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13260     * invalidated.
13261     * @param x the amount of pixels to scroll by horizontally
13262     * @param y the amount of pixels to scroll by vertically
13263     */
13264    public void scrollBy(int x, int y) {
13265        scrollTo(mScrollX + x, mScrollY + y);
13266    }
13267
13268    /**
13269     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13270     * animation to fade the scrollbars out after a default delay. If a subclass
13271     * provides animated scrolling, the start delay should equal the duration
13272     * of the scrolling animation.</p>
13273     *
13274     * <p>The animation starts only if at least one of the scrollbars is
13275     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13276     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13277     * this method returns true, and false otherwise. If the animation is
13278     * started, this method calls {@link #invalidate()}; in that case the
13279     * caller should not call {@link #invalidate()}.</p>
13280     *
13281     * <p>This method should be invoked every time a subclass directly updates
13282     * the scroll parameters.</p>
13283     *
13284     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13285     * and {@link #scrollTo(int, int)}.</p>
13286     *
13287     * @return true if the animation is played, false otherwise
13288     *
13289     * @see #awakenScrollBars(int)
13290     * @see #scrollBy(int, int)
13291     * @see #scrollTo(int, int)
13292     * @see #isHorizontalScrollBarEnabled()
13293     * @see #isVerticalScrollBarEnabled()
13294     * @see #setHorizontalScrollBarEnabled(boolean)
13295     * @see #setVerticalScrollBarEnabled(boolean)
13296     */
13297    protected boolean awakenScrollBars() {
13298        return mScrollCache != null &&
13299                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
13300    }
13301
13302    /**
13303     * Trigger the scrollbars to draw.
13304     * This method differs from awakenScrollBars() only in its default duration.
13305     * initialAwakenScrollBars() will show the scroll bars for longer than
13306     * usual to give the user more of a chance to notice them.
13307     *
13308     * @return true if the animation is played, false otherwise.
13309     */
13310    private boolean initialAwakenScrollBars() {
13311        return mScrollCache != null &&
13312                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
13313    }
13314
13315    /**
13316     * <p>
13317     * Trigger the scrollbars to draw. When invoked this method starts an
13318     * animation to fade the scrollbars out after a fixed delay. If a subclass
13319     * provides animated scrolling, the start delay should equal the duration of
13320     * the scrolling animation.
13321     * </p>
13322     *
13323     * <p>
13324     * The animation starts only if at least one of the scrollbars is enabled,
13325     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13326     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13327     * this method returns true, and false otherwise. If the animation is
13328     * started, this method calls {@link #invalidate()}; in that case the caller
13329     * should not call {@link #invalidate()}.
13330     * </p>
13331     *
13332     * <p>
13333     * This method should be invoked every time a subclass directly updates the
13334     * scroll parameters.
13335     * </p>
13336     *
13337     * @param startDelay the delay, in milliseconds, after which the animation
13338     *        should start; when the delay is 0, the animation starts
13339     *        immediately
13340     * @return true if the animation is played, false otherwise
13341     *
13342     * @see #scrollBy(int, int)
13343     * @see #scrollTo(int, int)
13344     * @see #isHorizontalScrollBarEnabled()
13345     * @see #isVerticalScrollBarEnabled()
13346     * @see #setHorizontalScrollBarEnabled(boolean)
13347     * @see #setVerticalScrollBarEnabled(boolean)
13348     */
13349    protected boolean awakenScrollBars(int startDelay) {
13350        return awakenScrollBars(startDelay, true);
13351    }
13352
13353    /**
13354     * <p>
13355     * Trigger the scrollbars to draw. When invoked this method starts an
13356     * animation to fade the scrollbars out after a fixed delay. If a subclass
13357     * provides animated scrolling, the start delay should equal the duration of
13358     * the scrolling animation.
13359     * </p>
13360     *
13361     * <p>
13362     * The animation starts only if at least one of the scrollbars is enabled,
13363     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13364     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13365     * this method returns true, and false otherwise. If the animation is
13366     * started, this method calls {@link #invalidate()} if the invalidate parameter
13367     * is set to true; in that case the caller
13368     * should not call {@link #invalidate()}.
13369     * </p>
13370     *
13371     * <p>
13372     * This method should be invoked every time a subclass directly updates the
13373     * scroll parameters.
13374     * </p>
13375     *
13376     * @param startDelay the delay, in milliseconds, after which the animation
13377     *        should start; when the delay is 0, the animation starts
13378     *        immediately
13379     *
13380     * @param invalidate Whether this method should call invalidate
13381     *
13382     * @return true if the animation is played, false otherwise
13383     *
13384     * @see #scrollBy(int, int)
13385     * @see #scrollTo(int, int)
13386     * @see #isHorizontalScrollBarEnabled()
13387     * @see #isVerticalScrollBarEnabled()
13388     * @see #setHorizontalScrollBarEnabled(boolean)
13389     * @see #setVerticalScrollBarEnabled(boolean)
13390     */
13391    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
13392        final ScrollabilityCache scrollCache = mScrollCache;
13393
13394        if (scrollCache == null || !scrollCache.fadeScrollBars) {
13395            return false;
13396        }
13397
13398        if (scrollCache.scrollBar == null) {
13399            scrollCache.scrollBar = new ScrollBarDrawable();
13400            scrollCache.scrollBar.setState(getDrawableState());
13401            scrollCache.scrollBar.setCallback(this);
13402        }
13403
13404        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
13405
13406            if (invalidate) {
13407                // Invalidate to show the scrollbars
13408                postInvalidateOnAnimation();
13409            }
13410
13411            if (scrollCache.state == ScrollabilityCache.OFF) {
13412                // FIXME: this is copied from WindowManagerService.
13413                // We should get this value from the system when it
13414                // is possible to do so.
13415                final int KEY_REPEAT_FIRST_DELAY = 750;
13416                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
13417            }
13418
13419            // Tell mScrollCache when we should start fading. This may
13420            // extend the fade start time if one was already scheduled
13421            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
13422            scrollCache.fadeStartTime = fadeStartTime;
13423            scrollCache.state = ScrollabilityCache.ON;
13424
13425            // Schedule our fader to run, unscheduling any old ones first
13426            if (mAttachInfo != null) {
13427                mAttachInfo.mHandler.removeCallbacks(scrollCache);
13428                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
13429            }
13430
13431            return true;
13432        }
13433
13434        return false;
13435    }
13436
13437    /**
13438     * Do not invalidate views which are not visible and which are not running an animation. They
13439     * will not get drawn and they should not set dirty flags as if they will be drawn
13440     */
13441    private boolean skipInvalidate() {
13442        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
13443                (!(mParent instanceof ViewGroup) ||
13444                        !((ViewGroup) mParent).isViewTransitioning(this));
13445    }
13446
13447    /**
13448     * Mark the area defined by dirty as needing to be drawn. If the view is
13449     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13450     * point in the future.
13451     * <p>
13452     * This must be called from a UI thread. To call from a non-UI thread, call
13453     * {@link #postInvalidate()}.
13454     * <p>
13455     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
13456     * {@code dirty}.
13457     *
13458     * @param dirty the rectangle representing the bounds of the dirty region
13459     */
13460    public void invalidate(Rect dirty) {
13461        final int scrollX = mScrollX;
13462        final int scrollY = mScrollY;
13463        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
13464                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
13465    }
13466
13467    /**
13468     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
13469     * coordinates of the dirty rect are relative to the view. If the view is
13470     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13471     * point in the future.
13472     * <p>
13473     * This must be called from a UI thread. To call from a non-UI thread, call
13474     * {@link #postInvalidate()}.
13475     *
13476     * @param l the left position of the dirty region
13477     * @param t the top position of the dirty region
13478     * @param r the right position of the dirty region
13479     * @param b the bottom position of the dirty region
13480     */
13481    public void invalidate(int l, int t, int r, int b) {
13482        final int scrollX = mScrollX;
13483        final int scrollY = mScrollY;
13484        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
13485    }
13486
13487    /**
13488     * Invalidate the whole view. If the view is visible,
13489     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
13490     * the future.
13491     * <p>
13492     * This must be called from a UI thread. To call from a non-UI thread, call
13493     * {@link #postInvalidate()}.
13494     */
13495    public void invalidate() {
13496        invalidate(true);
13497    }
13498
13499    /**
13500     * This is where the invalidate() work actually happens. A full invalidate()
13501     * causes the drawing cache to be invalidated, but this function can be
13502     * called with invalidateCache set to false to skip that invalidation step
13503     * for cases that do not need it (for example, a component that remains at
13504     * the same dimensions with the same content).
13505     *
13506     * @param invalidateCache Whether the drawing cache for this view should be
13507     *            invalidated as well. This is usually true for a full
13508     *            invalidate, but may be set to false if the View's contents or
13509     *            dimensions have not changed.
13510     */
13511    void invalidate(boolean invalidateCache) {
13512        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
13513    }
13514
13515    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
13516            boolean fullInvalidate) {
13517        if (mGhostView != null) {
13518            mGhostView.invalidate(true);
13519            return;
13520        }
13521
13522        if (skipInvalidate()) {
13523            return;
13524        }
13525
13526        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
13527                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
13528                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
13529                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
13530            if (fullInvalidate) {
13531                mLastIsOpaque = isOpaque();
13532                mPrivateFlags &= ~PFLAG_DRAWN;
13533            }
13534
13535            mPrivateFlags |= PFLAG_DIRTY;
13536
13537            if (invalidateCache) {
13538                mPrivateFlags |= PFLAG_INVALIDATED;
13539                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13540            }
13541
13542            // Propagate the damage rectangle to the parent view.
13543            final AttachInfo ai = mAttachInfo;
13544            final ViewParent p = mParent;
13545            if (p != null && ai != null && l < r && t < b) {
13546                final Rect damage = ai.mTmpInvalRect;
13547                damage.set(l, t, r, b);
13548                p.invalidateChild(this, damage);
13549            }
13550
13551            // Damage the entire projection receiver, if necessary.
13552            if (mBackground != null && mBackground.isProjected()) {
13553                final View receiver = getProjectionReceiver();
13554                if (receiver != null) {
13555                    receiver.damageInParent();
13556                }
13557            }
13558
13559            // Damage the entire IsolatedZVolume receiving this view's shadow.
13560            if (isHardwareAccelerated() && getZ() != 0) {
13561                damageShadowReceiver();
13562            }
13563        }
13564    }
13565
13566    /**
13567     * @return this view's projection receiver, or {@code null} if none exists
13568     */
13569    private View getProjectionReceiver() {
13570        ViewParent p = getParent();
13571        while (p != null && p instanceof View) {
13572            final View v = (View) p;
13573            if (v.isProjectionReceiver()) {
13574                return v;
13575            }
13576            p = p.getParent();
13577        }
13578
13579        return null;
13580    }
13581
13582    /**
13583     * @return whether the view is a projection receiver
13584     */
13585    private boolean isProjectionReceiver() {
13586        return mBackground != null;
13587    }
13588
13589    /**
13590     * Damage area of the screen that can be covered by this View's shadow.
13591     *
13592     * This method will guarantee that any changes to shadows cast by a View
13593     * are damaged on the screen for future redraw.
13594     */
13595    private void damageShadowReceiver() {
13596        final AttachInfo ai = mAttachInfo;
13597        if (ai != null) {
13598            ViewParent p = getParent();
13599            if (p != null && p instanceof ViewGroup) {
13600                final ViewGroup vg = (ViewGroup) p;
13601                vg.damageInParent();
13602            }
13603        }
13604    }
13605
13606    /**
13607     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
13608     * set any flags or handle all of the cases handled by the default invalidation methods.
13609     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
13610     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
13611     * walk up the hierarchy, transforming the dirty rect as necessary.
13612     *
13613     * The method also handles normal invalidation logic if display list properties are not
13614     * being used in this view. The invalidateParent and forceRedraw flags are used by that
13615     * backup approach, to handle these cases used in the various property-setting methods.
13616     *
13617     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
13618     * are not being used in this view
13619     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
13620     * list properties are not being used in this view
13621     */
13622    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
13623        if (!isHardwareAccelerated()
13624                || !mRenderNode.isValid()
13625                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
13626            if (invalidateParent) {
13627                invalidateParentCaches();
13628            }
13629            if (forceRedraw) {
13630                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13631            }
13632            invalidate(false);
13633        } else {
13634            damageInParent();
13635        }
13636        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
13637            damageShadowReceiver();
13638        }
13639    }
13640
13641    /**
13642     * Tells the parent view to damage this view's bounds.
13643     *
13644     * @hide
13645     */
13646    protected void damageInParent() {
13647        final AttachInfo ai = mAttachInfo;
13648        final ViewParent p = mParent;
13649        if (p != null && ai != null) {
13650            final Rect r = ai.mTmpInvalRect;
13651            r.set(0, 0, mRight - mLeft, mBottom - mTop);
13652            if (mParent instanceof ViewGroup) {
13653                ((ViewGroup) mParent).damageChild(this, r);
13654            } else {
13655                mParent.invalidateChild(this, r);
13656            }
13657        }
13658    }
13659
13660    /**
13661     * Utility method to transform a given Rect by the current matrix of this view.
13662     */
13663    void transformRect(final Rect rect) {
13664        if (!getMatrix().isIdentity()) {
13665            RectF boundingRect = mAttachInfo.mTmpTransformRect;
13666            boundingRect.set(rect);
13667            getMatrix().mapRect(boundingRect);
13668            rect.set((int) Math.floor(boundingRect.left),
13669                    (int) Math.floor(boundingRect.top),
13670                    (int) Math.ceil(boundingRect.right),
13671                    (int) Math.ceil(boundingRect.bottom));
13672        }
13673    }
13674
13675    /**
13676     * Used to indicate that the parent of this view should clear its caches. This functionality
13677     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13678     * which is necessary when various parent-managed properties of the view change, such as
13679     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
13680     * clears the parent caches and does not causes an invalidate event.
13681     *
13682     * @hide
13683     */
13684    protected void invalidateParentCaches() {
13685        if (mParent instanceof View) {
13686            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
13687        }
13688    }
13689
13690    /**
13691     * Used to indicate that the parent of this view should be invalidated. This functionality
13692     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13693     * which is necessary when various parent-managed properties of the view change, such as
13694     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
13695     * an invalidation event to the parent.
13696     *
13697     * @hide
13698     */
13699    protected void invalidateParentIfNeeded() {
13700        if (isHardwareAccelerated() && mParent instanceof View) {
13701            ((View) mParent).invalidate(true);
13702        }
13703    }
13704
13705    /**
13706     * @hide
13707     */
13708    protected void invalidateParentIfNeededAndWasQuickRejected() {
13709        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
13710            // View was rejected last time it was drawn by its parent; this may have changed
13711            invalidateParentIfNeeded();
13712        }
13713    }
13714
13715    /**
13716     * Indicates whether this View is opaque. An opaque View guarantees that it will
13717     * draw all the pixels overlapping its bounds using a fully opaque color.
13718     *
13719     * Subclasses of View should override this method whenever possible to indicate
13720     * whether an instance is opaque. Opaque Views are treated in a special way by
13721     * the View hierarchy, possibly allowing it to perform optimizations during
13722     * invalidate/draw passes.
13723     *
13724     * @return True if this View is guaranteed to be fully opaque, false otherwise.
13725     */
13726    @ViewDebug.ExportedProperty(category = "drawing")
13727    public boolean isOpaque() {
13728        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
13729                getFinalAlpha() >= 1.0f;
13730    }
13731
13732    /**
13733     * @hide
13734     */
13735    protected void computeOpaqueFlags() {
13736        // Opaque if:
13737        //   - Has a background
13738        //   - Background is opaque
13739        //   - Doesn't have scrollbars or scrollbars overlay
13740
13741        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
13742            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
13743        } else {
13744            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
13745        }
13746
13747        final int flags = mViewFlags;
13748        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
13749                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
13750                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
13751            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
13752        } else {
13753            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
13754        }
13755    }
13756
13757    /**
13758     * @hide
13759     */
13760    protected boolean hasOpaqueScrollbars() {
13761        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
13762    }
13763
13764    /**
13765     * @return A handler associated with the thread running the View. This
13766     * handler can be used to pump events in the UI events queue.
13767     */
13768    public Handler getHandler() {
13769        final AttachInfo attachInfo = mAttachInfo;
13770        if (attachInfo != null) {
13771            return attachInfo.mHandler;
13772        }
13773        return null;
13774    }
13775
13776    /**
13777     * Returns the queue of runnable for this view.
13778     *
13779     * @return the queue of runnables for this view
13780     */
13781    private HandlerActionQueue getRunQueue() {
13782        if (mRunQueue == null) {
13783            mRunQueue = new HandlerActionQueue();
13784        }
13785        return mRunQueue;
13786    }
13787
13788    /**
13789     * Gets the view root associated with the View.
13790     * @return The view root, or null if none.
13791     * @hide
13792     */
13793    public ViewRootImpl getViewRootImpl() {
13794        if (mAttachInfo != null) {
13795            return mAttachInfo.mViewRootImpl;
13796        }
13797        return null;
13798    }
13799
13800    /**
13801     * @hide
13802     */
13803    public ThreadedRenderer getHardwareRenderer() {
13804        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
13805    }
13806
13807    /**
13808     * <p>Causes the Runnable to be added to the message queue.
13809     * The runnable will be run on the user interface thread.</p>
13810     *
13811     * @param action The Runnable that will be executed.
13812     *
13813     * @return Returns true if the Runnable was successfully placed in to the
13814     *         message queue.  Returns false on failure, usually because the
13815     *         looper processing the message queue is exiting.
13816     *
13817     * @see #postDelayed
13818     * @see #removeCallbacks
13819     */
13820    public boolean post(Runnable action) {
13821        final AttachInfo attachInfo = mAttachInfo;
13822        if (attachInfo != null) {
13823            return attachInfo.mHandler.post(action);
13824        }
13825
13826        // Postpone the runnable until we know on which thread it needs to run.
13827        // Assume that the runnable will be successfully placed after attach.
13828        getRunQueue().post(action);
13829        return true;
13830    }
13831
13832    /**
13833     * <p>Causes the Runnable to be added to the message queue, to be run
13834     * after the specified amount of time elapses.
13835     * The runnable will be run on the user interface thread.</p>
13836     *
13837     * @param action The Runnable that will be executed.
13838     * @param delayMillis The delay (in milliseconds) until the Runnable
13839     *        will be executed.
13840     *
13841     * @return true if the Runnable was successfully placed in to the
13842     *         message queue.  Returns false on failure, usually because the
13843     *         looper processing the message queue is exiting.  Note that a
13844     *         result of true does not mean the Runnable will be processed --
13845     *         if the looper is quit before the delivery time of the message
13846     *         occurs then the message will be dropped.
13847     *
13848     * @see #post
13849     * @see #removeCallbacks
13850     */
13851    public boolean postDelayed(Runnable action, long delayMillis) {
13852        final AttachInfo attachInfo = mAttachInfo;
13853        if (attachInfo != null) {
13854            return attachInfo.mHandler.postDelayed(action, delayMillis);
13855        }
13856
13857        // Postpone the runnable until we know on which thread it needs to run.
13858        // Assume that the runnable will be successfully placed after attach.
13859        getRunQueue().postDelayed(action, delayMillis);
13860        return true;
13861    }
13862
13863    /**
13864     * <p>Causes the Runnable to execute on the next animation time step.
13865     * The runnable will be run on the user interface thread.</p>
13866     *
13867     * @param action The Runnable that will be executed.
13868     *
13869     * @see #postOnAnimationDelayed
13870     * @see #removeCallbacks
13871     */
13872    public void postOnAnimation(Runnable action) {
13873        final AttachInfo attachInfo = mAttachInfo;
13874        if (attachInfo != null) {
13875            attachInfo.mViewRootImpl.mChoreographer.postCallback(
13876                    Choreographer.CALLBACK_ANIMATION, action, null);
13877        } else {
13878            // Postpone the runnable until we know
13879            // on which thread it needs to run.
13880            getRunQueue().post(action);
13881        }
13882    }
13883
13884    /**
13885     * <p>Causes the Runnable to execute on the next animation time step,
13886     * after the specified amount of time elapses.
13887     * The runnable will be run on the user interface thread.</p>
13888     *
13889     * @param action The Runnable that will be executed.
13890     * @param delayMillis The delay (in milliseconds) until the Runnable
13891     *        will be executed.
13892     *
13893     * @see #postOnAnimation
13894     * @see #removeCallbacks
13895     */
13896    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
13897        final AttachInfo attachInfo = mAttachInfo;
13898        if (attachInfo != null) {
13899            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13900                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
13901        } else {
13902            // Postpone the runnable until we know
13903            // on which thread it needs to run.
13904            getRunQueue().postDelayed(action, delayMillis);
13905        }
13906    }
13907
13908    /**
13909     * <p>Removes the specified Runnable from the message queue.</p>
13910     *
13911     * @param action The Runnable to remove from the message handling queue
13912     *
13913     * @return true if this view could ask the Handler to remove the Runnable,
13914     *         false otherwise. When the returned value is true, the Runnable
13915     *         may or may not have been actually removed from the message queue
13916     *         (for instance, if the Runnable was not in the queue already.)
13917     *
13918     * @see #post
13919     * @see #postDelayed
13920     * @see #postOnAnimation
13921     * @see #postOnAnimationDelayed
13922     */
13923    public boolean removeCallbacks(Runnable action) {
13924        if (action != null) {
13925            final AttachInfo attachInfo = mAttachInfo;
13926            if (attachInfo != null) {
13927                attachInfo.mHandler.removeCallbacks(action);
13928                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13929                        Choreographer.CALLBACK_ANIMATION, action, null);
13930            }
13931            getRunQueue().removeCallbacks(action);
13932        }
13933        return true;
13934    }
13935
13936    /**
13937     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
13938     * Use this to invalidate the View from a non-UI thread.</p>
13939     *
13940     * <p>This method can be invoked from outside of the UI thread
13941     * only when this View is attached to a window.</p>
13942     *
13943     * @see #invalidate()
13944     * @see #postInvalidateDelayed(long)
13945     */
13946    public void postInvalidate() {
13947        postInvalidateDelayed(0);
13948    }
13949
13950    /**
13951     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13952     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
13953     *
13954     * <p>This method can be invoked from outside of the UI thread
13955     * only when this View is attached to a window.</p>
13956     *
13957     * @param left The left coordinate of the rectangle to invalidate.
13958     * @param top The top coordinate of the rectangle to invalidate.
13959     * @param right The right coordinate of the rectangle to invalidate.
13960     * @param bottom The bottom coordinate of the rectangle to invalidate.
13961     *
13962     * @see #invalidate(int, int, int, int)
13963     * @see #invalidate(Rect)
13964     * @see #postInvalidateDelayed(long, int, int, int, int)
13965     */
13966    public void postInvalidate(int left, int top, int right, int bottom) {
13967        postInvalidateDelayed(0, left, top, right, bottom);
13968    }
13969
13970    /**
13971     * <p>Cause an invalidate to happen on a subsequent cycle through the event
13972     * loop. Waits for the specified amount of time.</p>
13973     *
13974     * <p>This method can be invoked from outside of the UI thread
13975     * only when this View is attached to a window.</p>
13976     *
13977     * @param delayMilliseconds the duration in milliseconds to delay the
13978     *         invalidation by
13979     *
13980     * @see #invalidate()
13981     * @see #postInvalidate()
13982     */
13983    public void postInvalidateDelayed(long delayMilliseconds) {
13984        // We try only with the AttachInfo because there's no point in invalidating
13985        // if we are not attached to our window
13986        final AttachInfo attachInfo = mAttachInfo;
13987        if (attachInfo != null) {
13988            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
13989        }
13990    }
13991
13992    /**
13993     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13994     * through the event loop. Waits for the specified amount of time.</p>
13995     *
13996     * <p>This method can be invoked from outside of the UI thread
13997     * only when this View is attached to a window.</p>
13998     *
13999     * @param delayMilliseconds the duration in milliseconds to delay the
14000     *         invalidation by
14001     * @param left The left coordinate of the rectangle to invalidate.
14002     * @param top The top coordinate of the rectangle to invalidate.
14003     * @param right The right coordinate of the rectangle to invalidate.
14004     * @param bottom The bottom coordinate of the rectangle to invalidate.
14005     *
14006     * @see #invalidate(int, int, int, int)
14007     * @see #invalidate(Rect)
14008     * @see #postInvalidate(int, int, int, int)
14009     */
14010    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14011            int right, int bottom) {
14012
14013        // We try only with the AttachInfo because there's no point in invalidating
14014        // if we are not attached to our window
14015        final AttachInfo attachInfo = mAttachInfo;
14016        if (attachInfo != null) {
14017            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14018            info.target = this;
14019            info.left = left;
14020            info.top = top;
14021            info.right = right;
14022            info.bottom = bottom;
14023
14024            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14025        }
14026    }
14027
14028    /**
14029     * <p>Cause an invalidate to happen on the next animation time step, typically the
14030     * next display frame.</p>
14031     *
14032     * <p>This method can be invoked from outside of the UI thread
14033     * only when this View is attached to a window.</p>
14034     *
14035     * @see #invalidate()
14036     */
14037    public void postInvalidateOnAnimation() {
14038        // We try only with the AttachInfo because there's no point in invalidating
14039        // if we are not attached to our window
14040        final AttachInfo attachInfo = mAttachInfo;
14041        if (attachInfo != null) {
14042            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14043        }
14044    }
14045
14046    /**
14047     * <p>Cause an invalidate of the specified area to happen on the next animation
14048     * time step, typically the next display frame.</p>
14049     *
14050     * <p>This method can be invoked from outside of the UI thread
14051     * only when this View is attached to a window.</p>
14052     *
14053     * @param left The left coordinate of the rectangle to invalidate.
14054     * @param top The top coordinate of the rectangle to invalidate.
14055     * @param right The right coordinate of the rectangle to invalidate.
14056     * @param bottom The bottom coordinate of the rectangle to invalidate.
14057     *
14058     * @see #invalidate(int, int, int, int)
14059     * @see #invalidate(Rect)
14060     */
14061    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14062        // We try only with the AttachInfo because there's no point in invalidating
14063        // if we are not attached to our window
14064        final AttachInfo attachInfo = mAttachInfo;
14065        if (attachInfo != null) {
14066            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14067            info.target = this;
14068            info.left = left;
14069            info.top = top;
14070            info.right = right;
14071            info.bottom = bottom;
14072
14073            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14074        }
14075    }
14076
14077    /**
14078     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14079     * This event is sent at most once every
14080     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14081     */
14082    private void postSendViewScrolledAccessibilityEventCallback() {
14083        if (mSendViewScrolledAccessibilityEvent == null) {
14084            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14085        }
14086        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14087            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14088            postDelayed(mSendViewScrolledAccessibilityEvent,
14089                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14090        }
14091    }
14092
14093    /**
14094     * Called by a parent to request that a child update its values for mScrollX
14095     * and mScrollY if necessary. This will typically be done if the child is
14096     * animating a scroll using a {@link android.widget.Scroller Scroller}
14097     * object.
14098     */
14099    public void computeScroll() {
14100    }
14101
14102    /**
14103     * <p>Indicate whether the horizontal edges are faded when the view is
14104     * scrolled horizontally.</p>
14105     *
14106     * @return true if the horizontal edges should are faded on scroll, false
14107     *         otherwise
14108     *
14109     * @see #setHorizontalFadingEdgeEnabled(boolean)
14110     *
14111     * @attr ref android.R.styleable#View_requiresFadingEdge
14112     */
14113    public boolean isHorizontalFadingEdgeEnabled() {
14114        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14115    }
14116
14117    /**
14118     * <p>Define whether the horizontal edges should be faded when this view
14119     * is scrolled horizontally.</p>
14120     *
14121     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14122     *                                    be faded when the view is scrolled
14123     *                                    horizontally
14124     *
14125     * @see #isHorizontalFadingEdgeEnabled()
14126     *
14127     * @attr ref android.R.styleable#View_requiresFadingEdge
14128     */
14129    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14130        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14131            if (horizontalFadingEdgeEnabled) {
14132                initScrollCache();
14133            }
14134
14135            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14136        }
14137    }
14138
14139    /**
14140     * <p>Indicate whether the vertical edges are faded when the view is
14141     * scrolled horizontally.</p>
14142     *
14143     * @return true if the vertical edges should are faded on scroll, false
14144     *         otherwise
14145     *
14146     * @see #setVerticalFadingEdgeEnabled(boolean)
14147     *
14148     * @attr ref android.R.styleable#View_requiresFadingEdge
14149     */
14150    public boolean isVerticalFadingEdgeEnabled() {
14151        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14152    }
14153
14154    /**
14155     * <p>Define whether the vertical edges should be faded when this view
14156     * is scrolled vertically.</p>
14157     *
14158     * @param verticalFadingEdgeEnabled true if the vertical edges should
14159     *                                  be faded when the view is scrolled
14160     *                                  vertically
14161     *
14162     * @see #isVerticalFadingEdgeEnabled()
14163     *
14164     * @attr ref android.R.styleable#View_requiresFadingEdge
14165     */
14166    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14167        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14168            if (verticalFadingEdgeEnabled) {
14169                initScrollCache();
14170            }
14171
14172            mViewFlags ^= FADING_EDGE_VERTICAL;
14173        }
14174    }
14175
14176    /**
14177     * Returns the strength, or intensity, of the top faded edge. The strength is
14178     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14179     * returns 0.0 or 1.0 but no value in between.
14180     *
14181     * Subclasses should override this method to provide a smoother fade transition
14182     * when scrolling occurs.
14183     *
14184     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14185     */
14186    protected float getTopFadingEdgeStrength() {
14187        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14188    }
14189
14190    /**
14191     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14192     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14193     * returns 0.0 or 1.0 but no value in between.
14194     *
14195     * Subclasses should override this method to provide a smoother fade transition
14196     * when scrolling occurs.
14197     *
14198     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14199     */
14200    protected float getBottomFadingEdgeStrength() {
14201        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14202                computeVerticalScrollRange() ? 1.0f : 0.0f;
14203    }
14204
14205    /**
14206     * Returns the strength, or intensity, of the left faded edge. The strength is
14207     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14208     * returns 0.0 or 1.0 but no value in between.
14209     *
14210     * Subclasses should override this method to provide a smoother fade transition
14211     * when scrolling occurs.
14212     *
14213     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14214     */
14215    protected float getLeftFadingEdgeStrength() {
14216        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14217    }
14218
14219    /**
14220     * Returns the strength, or intensity, of the right faded edge. The strength is
14221     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14222     * returns 0.0 or 1.0 but no value in between.
14223     *
14224     * Subclasses should override this method to provide a smoother fade transition
14225     * when scrolling occurs.
14226     *
14227     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14228     */
14229    protected float getRightFadingEdgeStrength() {
14230        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14231                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14232    }
14233
14234    /**
14235     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14236     * scrollbar is not drawn by default.</p>
14237     *
14238     * @return true if the horizontal scrollbar should be painted, false
14239     *         otherwise
14240     *
14241     * @see #setHorizontalScrollBarEnabled(boolean)
14242     */
14243    public boolean isHorizontalScrollBarEnabled() {
14244        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14245    }
14246
14247    /**
14248     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14249     * scrollbar is not drawn by default.</p>
14250     *
14251     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14252     *                                   be painted
14253     *
14254     * @see #isHorizontalScrollBarEnabled()
14255     */
14256    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14257        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14258            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14259            computeOpaqueFlags();
14260            resolvePadding();
14261        }
14262    }
14263
14264    /**
14265     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14266     * scrollbar is not drawn by default.</p>
14267     *
14268     * @return true if the vertical scrollbar should be painted, false
14269     *         otherwise
14270     *
14271     * @see #setVerticalScrollBarEnabled(boolean)
14272     */
14273    public boolean isVerticalScrollBarEnabled() {
14274        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14275    }
14276
14277    /**
14278     * <p>Define whether the vertical scrollbar should be drawn or not. The
14279     * scrollbar is not drawn by default.</p>
14280     *
14281     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14282     *                                 be painted
14283     *
14284     * @see #isVerticalScrollBarEnabled()
14285     */
14286    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14287        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14288            mViewFlags ^= SCROLLBARS_VERTICAL;
14289            computeOpaqueFlags();
14290            resolvePadding();
14291        }
14292    }
14293
14294    /**
14295     * @hide
14296     */
14297    protected void recomputePadding() {
14298        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14299    }
14300
14301    /**
14302     * Define whether scrollbars will fade when the view is not scrolling.
14303     *
14304     * @param fadeScrollbars whether to enable fading
14305     *
14306     * @attr ref android.R.styleable#View_fadeScrollbars
14307     */
14308    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14309        initScrollCache();
14310        final ScrollabilityCache scrollabilityCache = mScrollCache;
14311        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14312        if (fadeScrollbars) {
14313            scrollabilityCache.state = ScrollabilityCache.OFF;
14314        } else {
14315            scrollabilityCache.state = ScrollabilityCache.ON;
14316        }
14317    }
14318
14319    /**
14320     *
14321     * Returns true if scrollbars will fade when this view is not scrolling
14322     *
14323     * @return true if scrollbar fading is enabled
14324     *
14325     * @attr ref android.R.styleable#View_fadeScrollbars
14326     */
14327    public boolean isScrollbarFadingEnabled() {
14328        return mScrollCache != null && mScrollCache.fadeScrollBars;
14329    }
14330
14331    /**
14332     *
14333     * Returns the delay before scrollbars fade.
14334     *
14335     * @return the delay before scrollbars fade
14336     *
14337     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14338     */
14339    public int getScrollBarDefaultDelayBeforeFade() {
14340        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14341                mScrollCache.scrollBarDefaultDelayBeforeFade;
14342    }
14343
14344    /**
14345     * Define the delay before scrollbars fade.
14346     *
14347     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14348     *
14349     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14350     */
14351    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14352        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14353    }
14354
14355    /**
14356     *
14357     * Returns the scrollbar fade duration.
14358     *
14359     * @return the scrollbar fade duration
14360     *
14361     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14362     */
14363    public int getScrollBarFadeDuration() {
14364        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14365                mScrollCache.scrollBarFadeDuration;
14366    }
14367
14368    /**
14369     * Define the scrollbar fade duration.
14370     *
14371     * @param scrollBarFadeDuration - the scrollbar fade duration
14372     *
14373     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14374     */
14375    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14376        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14377    }
14378
14379    /**
14380     *
14381     * Returns the scrollbar size.
14382     *
14383     * @return the scrollbar size
14384     *
14385     * @attr ref android.R.styleable#View_scrollbarSize
14386     */
14387    public int getScrollBarSize() {
14388        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14389                mScrollCache.scrollBarSize;
14390    }
14391
14392    /**
14393     * Define the scrollbar size.
14394     *
14395     * @param scrollBarSize - the scrollbar size
14396     *
14397     * @attr ref android.R.styleable#View_scrollbarSize
14398     */
14399    public void setScrollBarSize(int scrollBarSize) {
14400        getScrollCache().scrollBarSize = scrollBarSize;
14401    }
14402
14403    /**
14404     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14405     * inset. When inset, they add to the padding of the view. And the scrollbars
14406     * can be drawn inside the padding area or on the edge of the view. For example,
14407     * if a view has a background drawable and you want to draw the scrollbars
14408     * inside the padding specified by the drawable, you can use
14409     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14410     * appear at the edge of the view, ignoring the padding, then you can use
14411     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14412     * @param style the style of the scrollbars. Should be one of
14413     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14414     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14415     * @see #SCROLLBARS_INSIDE_OVERLAY
14416     * @see #SCROLLBARS_INSIDE_INSET
14417     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14418     * @see #SCROLLBARS_OUTSIDE_INSET
14419     *
14420     * @attr ref android.R.styleable#View_scrollbarStyle
14421     */
14422    public void setScrollBarStyle(@ScrollBarStyle int style) {
14423        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14424            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14425            computeOpaqueFlags();
14426            resolvePadding();
14427        }
14428    }
14429
14430    /**
14431     * <p>Returns the current scrollbar style.</p>
14432     * @return the current scrollbar style
14433     * @see #SCROLLBARS_INSIDE_OVERLAY
14434     * @see #SCROLLBARS_INSIDE_INSET
14435     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14436     * @see #SCROLLBARS_OUTSIDE_INSET
14437     *
14438     * @attr ref android.R.styleable#View_scrollbarStyle
14439     */
14440    @ViewDebug.ExportedProperty(mapping = {
14441            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14442            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14443            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14444            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14445    })
14446    @ScrollBarStyle
14447    public int getScrollBarStyle() {
14448        return mViewFlags & SCROLLBARS_STYLE_MASK;
14449    }
14450
14451    /**
14452     * <p>Compute the horizontal range that the horizontal scrollbar
14453     * represents.</p>
14454     *
14455     * <p>The range is expressed in arbitrary units that must be the same as the
14456     * units used by {@link #computeHorizontalScrollExtent()} and
14457     * {@link #computeHorizontalScrollOffset()}.</p>
14458     *
14459     * <p>The default range is the drawing width of this view.</p>
14460     *
14461     * @return the total horizontal range represented by the horizontal
14462     *         scrollbar
14463     *
14464     * @see #computeHorizontalScrollExtent()
14465     * @see #computeHorizontalScrollOffset()
14466     * @see android.widget.ScrollBarDrawable
14467     */
14468    protected int computeHorizontalScrollRange() {
14469        return getWidth();
14470    }
14471
14472    /**
14473     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14474     * within the horizontal range. This value is used to compute the position
14475     * of the thumb within the scrollbar's track.</p>
14476     *
14477     * <p>The range is expressed in arbitrary units that must be the same as the
14478     * units used by {@link #computeHorizontalScrollRange()} and
14479     * {@link #computeHorizontalScrollExtent()}.</p>
14480     *
14481     * <p>The default offset is the scroll offset of this view.</p>
14482     *
14483     * @return the horizontal offset of the scrollbar's thumb
14484     *
14485     * @see #computeHorizontalScrollRange()
14486     * @see #computeHorizontalScrollExtent()
14487     * @see android.widget.ScrollBarDrawable
14488     */
14489    protected int computeHorizontalScrollOffset() {
14490        return mScrollX;
14491    }
14492
14493    /**
14494     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14495     * within the horizontal range. This value is used to compute the length
14496     * of the thumb within the scrollbar's track.</p>
14497     *
14498     * <p>The range is expressed in arbitrary units that must be the same as the
14499     * units used by {@link #computeHorizontalScrollRange()} and
14500     * {@link #computeHorizontalScrollOffset()}.</p>
14501     *
14502     * <p>The default extent is the drawing width of this view.</p>
14503     *
14504     * @return the horizontal extent of the scrollbar's thumb
14505     *
14506     * @see #computeHorizontalScrollRange()
14507     * @see #computeHorizontalScrollOffset()
14508     * @see android.widget.ScrollBarDrawable
14509     */
14510    protected int computeHorizontalScrollExtent() {
14511        return getWidth();
14512    }
14513
14514    /**
14515     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
14516     *
14517     * <p>The range is expressed in arbitrary units that must be the same as the
14518     * units used by {@link #computeVerticalScrollExtent()} and
14519     * {@link #computeVerticalScrollOffset()}.</p>
14520     *
14521     * @return the total vertical range represented by the vertical scrollbar
14522     *
14523     * <p>The default range is the drawing height of this view.</p>
14524     *
14525     * @see #computeVerticalScrollExtent()
14526     * @see #computeVerticalScrollOffset()
14527     * @see android.widget.ScrollBarDrawable
14528     */
14529    protected int computeVerticalScrollRange() {
14530        return getHeight();
14531    }
14532
14533    /**
14534     * <p>Compute the vertical offset of the vertical scrollbar's thumb
14535     * within the horizontal range. This value is used to compute the position
14536     * of the thumb within the scrollbar's track.</p>
14537     *
14538     * <p>The range is expressed in arbitrary units that must be the same as the
14539     * units used by {@link #computeVerticalScrollRange()} and
14540     * {@link #computeVerticalScrollExtent()}.</p>
14541     *
14542     * <p>The default offset is the scroll offset of this view.</p>
14543     *
14544     * @return the vertical offset of the scrollbar's thumb
14545     *
14546     * @see #computeVerticalScrollRange()
14547     * @see #computeVerticalScrollExtent()
14548     * @see android.widget.ScrollBarDrawable
14549     */
14550    protected int computeVerticalScrollOffset() {
14551        return mScrollY;
14552    }
14553
14554    /**
14555     * <p>Compute the vertical extent of the vertical scrollbar's thumb
14556     * within the vertical range. This value is used to compute the length
14557     * of the thumb within the scrollbar's track.</p>
14558     *
14559     * <p>The range is expressed in arbitrary units that must be the same as the
14560     * units used by {@link #computeVerticalScrollRange()} and
14561     * {@link #computeVerticalScrollOffset()}.</p>
14562     *
14563     * <p>The default extent is the drawing height of this view.</p>
14564     *
14565     * @return the vertical extent of the scrollbar's thumb
14566     *
14567     * @see #computeVerticalScrollRange()
14568     * @see #computeVerticalScrollOffset()
14569     * @see android.widget.ScrollBarDrawable
14570     */
14571    protected int computeVerticalScrollExtent() {
14572        return getHeight();
14573    }
14574
14575    /**
14576     * Check if this view can be scrolled horizontally in a certain direction.
14577     *
14578     * @param direction Negative to check scrolling left, positive to check scrolling right.
14579     * @return true if this view can be scrolled in the specified direction, false otherwise.
14580     */
14581    public boolean canScrollHorizontally(int direction) {
14582        final int offset = computeHorizontalScrollOffset();
14583        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
14584        if (range == 0) return false;
14585        if (direction < 0) {
14586            return offset > 0;
14587        } else {
14588            return offset < range - 1;
14589        }
14590    }
14591
14592    /**
14593     * Check if this view can be scrolled vertically in a certain direction.
14594     *
14595     * @param direction Negative to check scrolling up, positive to check scrolling down.
14596     * @return true if this view can be scrolled in the specified direction, false otherwise.
14597     */
14598    public boolean canScrollVertically(int direction) {
14599        final int offset = computeVerticalScrollOffset();
14600        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
14601        if (range == 0) return false;
14602        if (direction < 0) {
14603            return offset > 0;
14604        } else {
14605            return offset < range - 1;
14606        }
14607    }
14608
14609    void getScrollIndicatorBounds(@NonNull Rect out) {
14610        out.left = mScrollX;
14611        out.right = mScrollX + mRight - mLeft;
14612        out.top = mScrollY;
14613        out.bottom = mScrollY + mBottom - mTop;
14614    }
14615
14616    private void onDrawScrollIndicators(Canvas c) {
14617        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
14618            // No scroll indicators enabled.
14619            return;
14620        }
14621
14622        final Drawable dr = mScrollIndicatorDrawable;
14623        if (dr == null) {
14624            // Scroll indicators aren't supported here.
14625            return;
14626        }
14627
14628        final int h = dr.getIntrinsicHeight();
14629        final int w = dr.getIntrinsicWidth();
14630        final Rect rect = mAttachInfo.mTmpInvalRect;
14631        getScrollIndicatorBounds(rect);
14632
14633        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
14634            final boolean canScrollUp = canScrollVertically(-1);
14635            if (canScrollUp) {
14636                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
14637                dr.draw(c);
14638            }
14639        }
14640
14641        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
14642            final boolean canScrollDown = canScrollVertically(1);
14643            if (canScrollDown) {
14644                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
14645                dr.draw(c);
14646            }
14647        }
14648
14649        final int leftRtl;
14650        final int rightRtl;
14651        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14652            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
14653            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
14654        } else {
14655            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
14656            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
14657        }
14658
14659        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
14660        if ((mPrivateFlags3 & leftMask) != 0) {
14661            final boolean canScrollLeft = canScrollHorizontally(-1);
14662            if (canScrollLeft) {
14663                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
14664                dr.draw(c);
14665            }
14666        }
14667
14668        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
14669        if ((mPrivateFlags3 & rightMask) != 0) {
14670            final boolean canScrollRight = canScrollHorizontally(1);
14671            if (canScrollRight) {
14672                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
14673                dr.draw(c);
14674            }
14675        }
14676    }
14677
14678    private void getHorizontalScrollBarBounds(Rect bounds) {
14679        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14680        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14681                && !isVerticalScrollBarHidden();
14682        final int size = getHorizontalScrollbarHeight();
14683        final int verticalScrollBarGap = drawVerticalScrollBar ?
14684                getVerticalScrollbarWidth() : 0;
14685        final int width = mRight - mLeft;
14686        final int height = mBottom - mTop;
14687        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
14688        bounds.left = mScrollX + (mPaddingLeft & inside);
14689        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
14690        bounds.bottom = bounds.top + size;
14691    }
14692
14693    private void getVerticalScrollBarBounds(Rect bounds) {
14694        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14695        final int size = getVerticalScrollbarWidth();
14696        int verticalScrollbarPosition = mVerticalScrollbarPosition;
14697        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
14698            verticalScrollbarPosition = isLayoutRtl() ?
14699                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
14700        }
14701        final int width = mRight - mLeft;
14702        final int height = mBottom - mTop;
14703        switch (verticalScrollbarPosition) {
14704            default:
14705            case SCROLLBAR_POSITION_RIGHT:
14706                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
14707                break;
14708            case SCROLLBAR_POSITION_LEFT:
14709                bounds.left = mScrollX + (mUserPaddingLeft & inside);
14710                break;
14711        }
14712        bounds.top = mScrollY + (mPaddingTop & inside);
14713        bounds.right = bounds.left + size;
14714        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
14715    }
14716
14717    /**
14718     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
14719     * scrollbars are painted only if they have been awakened first.</p>
14720     *
14721     * @param canvas the canvas on which to draw the scrollbars
14722     *
14723     * @see #awakenScrollBars(int)
14724     */
14725    protected final void onDrawScrollBars(Canvas canvas) {
14726        // scrollbars are drawn only when the animation is running
14727        final ScrollabilityCache cache = mScrollCache;
14728        if (cache != null) {
14729
14730            int state = cache.state;
14731
14732            if (state == ScrollabilityCache.OFF) {
14733                return;
14734            }
14735
14736            boolean invalidate = false;
14737
14738            if (state == ScrollabilityCache.FADING) {
14739                // We're fading -- get our fade interpolation
14740                if (cache.interpolatorValues == null) {
14741                    cache.interpolatorValues = new float[1];
14742                }
14743
14744                float[] values = cache.interpolatorValues;
14745
14746                // Stops the animation if we're done
14747                if (cache.scrollBarInterpolator.timeToValues(values) ==
14748                        Interpolator.Result.FREEZE_END) {
14749                    cache.state = ScrollabilityCache.OFF;
14750                } else {
14751                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
14752                }
14753
14754                // This will make the scroll bars inval themselves after
14755                // drawing. We only want this when we're fading so that
14756                // we prevent excessive redraws
14757                invalidate = true;
14758            } else {
14759                // We're just on -- but we may have been fading before so
14760                // reset alpha
14761                cache.scrollBar.mutate().setAlpha(255);
14762            }
14763
14764            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
14765            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14766                    && !isVerticalScrollBarHidden();
14767
14768            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
14769                final ScrollBarDrawable scrollBar = cache.scrollBar;
14770
14771                if (drawHorizontalScrollBar) {
14772                    scrollBar.setParameters(computeHorizontalScrollRange(),
14773                                            computeHorizontalScrollOffset(),
14774                                            computeHorizontalScrollExtent(), false);
14775                    final Rect bounds = cache.mScrollBarBounds;
14776                    getHorizontalScrollBarBounds(bounds);
14777                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14778                            bounds.right, bounds.bottom);
14779                    if (invalidate) {
14780                        invalidate(bounds);
14781                    }
14782                }
14783
14784                if (drawVerticalScrollBar) {
14785                    scrollBar.setParameters(computeVerticalScrollRange(),
14786                                            computeVerticalScrollOffset(),
14787                                            computeVerticalScrollExtent(), true);
14788                    final Rect bounds = cache.mScrollBarBounds;
14789                    getVerticalScrollBarBounds(bounds);
14790                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14791                            bounds.right, bounds.bottom);
14792                    if (invalidate) {
14793                        invalidate(bounds);
14794                    }
14795                }
14796            }
14797        }
14798    }
14799
14800    /**
14801     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
14802     * FastScroller is visible.
14803     * @return whether to temporarily hide the vertical scrollbar
14804     * @hide
14805     */
14806    protected boolean isVerticalScrollBarHidden() {
14807        return false;
14808    }
14809
14810    /**
14811     * <p>Draw the horizontal scrollbar if
14812     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
14813     *
14814     * @param canvas the canvas on which to draw the scrollbar
14815     * @param scrollBar the scrollbar's drawable
14816     *
14817     * @see #isHorizontalScrollBarEnabled()
14818     * @see #computeHorizontalScrollRange()
14819     * @see #computeHorizontalScrollExtent()
14820     * @see #computeHorizontalScrollOffset()
14821     * @see android.widget.ScrollBarDrawable
14822     * @hide
14823     */
14824    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
14825            int l, int t, int r, int b) {
14826        scrollBar.setBounds(l, t, r, b);
14827        scrollBar.draw(canvas);
14828    }
14829
14830    /**
14831     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
14832     * returns true.</p>
14833     *
14834     * @param canvas the canvas on which to draw the scrollbar
14835     * @param scrollBar the scrollbar's drawable
14836     *
14837     * @see #isVerticalScrollBarEnabled()
14838     * @see #computeVerticalScrollRange()
14839     * @see #computeVerticalScrollExtent()
14840     * @see #computeVerticalScrollOffset()
14841     * @see android.widget.ScrollBarDrawable
14842     * @hide
14843     */
14844    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
14845            int l, int t, int r, int b) {
14846        scrollBar.setBounds(l, t, r, b);
14847        scrollBar.draw(canvas);
14848    }
14849
14850    /**
14851     * Implement this to do your drawing.
14852     *
14853     * @param canvas the canvas on which the background will be drawn
14854     */
14855    protected void onDraw(Canvas canvas) {
14856    }
14857
14858    /*
14859     * Caller is responsible for calling requestLayout if necessary.
14860     * (This allows addViewInLayout to not request a new layout.)
14861     */
14862    void assignParent(ViewParent parent) {
14863        if (mParent == null) {
14864            mParent = parent;
14865        } else if (parent == null) {
14866            mParent = null;
14867        } else {
14868            throw new RuntimeException("view " + this + " being added, but"
14869                    + " it already has a parent");
14870        }
14871    }
14872
14873    /**
14874     * This is called when the view is attached to a window.  At this point it
14875     * has a Surface and will start drawing.  Note that this function is
14876     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
14877     * however it may be called any time before the first onDraw -- including
14878     * before or after {@link #onMeasure(int, int)}.
14879     *
14880     * @see #onDetachedFromWindow()
14881     */
14882    @CallSuper
14883    protected void onAttachedToWindow() {
14884        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
14885            mParent.requestTransparentRegion(this);
14886        }
14887
14888        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
14889
14890        jumpDrawablesToCurrentState();
14891
14892        resetSubtreeAccessibilityStateChanged();
14893
14894        // rebuild, since Outline not maintained while View is detached
14895        rebuildOutline();
14896
14897        if (isFocused()) {
14898            InputMethodManager imm = InputMethodManager.peekInstance();
14899            if (imm != null) {
14900                imm.focusIn(this);
14901            }
14902        }
14903    }
14904
14905    /**
14906     * Resolve all RTL related properties.
14907     *
14908     * @return true if resolution of RTL properties has been done
14909     *
14910     * @hide
14911     */
14912    public boolean resolveRtlPropertiesIfNeeded() {
14913        if (!needRtlPropertiesResolution()) return false;
14914
14915        // Order is important here: LayoutDirection MUST be resolved first
14916        if (!isLayoutDirectionResolved()) {
14917            resolveLayoutDirection();
14918            resolveLayoutParams();
14919        }
14920        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
14921        if (!isTextDirectionResolved()) {
14922            resolveTextDirection();
14923        }
14924        if (!isTextAlignmentResolved()) {
14925            resolveTextAlignment();
14926        }
14927        // Should resolve Drawables before Padding because we need the layout direction of the
14928        // Drawable to correctly resolve Padding.
14929        if (!areDrawablesResolved()) {
14930            resolveDrawables();
14931        }
14932        if (!isPaddingResolved()) {
14933            resolvePadding();
14934        }
14935        onRtlPropertiesChanged(getLayoutDirection());
14936        return true;
14937    }
14938
14939    /**
14940     * Reset resolution of all RTL related properties.
14941     *
14942     * @hide
14943     */
14944    public void resetRtlProperties() {
14945        resetResolvedLayoutDirection();
14946        resetResolvedTextDirection();
14947        resetResolvedTextAlignment();
14948        resetResolvedPadding();
14949        resetResolvedDrawables();
14950    }
14951
14952    /**
14953     * @see #onScreenStateChanged(int)
14954     */
14955    void dispatchScreenStateChanged(int screenState) {
14956        onScreenStateChanged(screenState);
14957    }
14958
14959    /**
14960     * This method is called whenever the state of the screen this view is
14961     * attached to changes. A state change will usually occurs when the screen
14962     * turns on or off (whether it happens automatically or the user does it
14963     * manually.)
14964     *
14965     * @param screenState The new state of the screen. Can be either
14966     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
14967     */
14968    public void onScreenStateChanged(int screenState) {
14969    }
14970
14971    /**
14972     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
14973     */
14974    private boolean hasRtlSupport() {
14975        return mContext.getApplicationInfo().hasRtlSupport();
14976    }
14977
14978    /**
14979     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
14980     * RTL not supported)
14981     */
14982    private boolean isRtlCompatibilityMode() {
14983        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
14984        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
14985    }
14986
14987    /**
14988     * @return true if RTL properties need resolution.
14989     *
14990     */
14991    private boolean needRtlPropertiesResolution() {
14992        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
14993    }
14994
14995    /**
14996     * Called when any RTL property (layout direction or text direction or text alignment) has
14997     * been changed.
14998     *
14999     * Subclasses need to override this method to take care of cached information that depends on the
15000     * resolved layout direction, or to inform child views that inherit their layout direction.
15001     *
15002     * The default implementation does nothing.
15003     *
15004     * @param layoutDirection the direction of the layout
15005     *
15006     * @see #LAYOUT_DIRECTION_LTR
15007     * @see #LAYOUT_DIRECTION_RTL
15008     */
15009    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15010    }
15011
15012    /**
15013     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15014     * that the parent directionality can and will be resolved before its children.
15015     *
15016     * @return true if resolution has been done, false otherwise.
15017     *
15018     * @hide
15019     */
15020    public boolean resolveLayoutDirection() {
15021        // Clear any previous layout direction resolution
15022        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15023
15024        if (hasRtlSupport()) {
15025            // Set resolved depending on layout direction
15026            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15027                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15028                case LAYOUT_DIRECTION_INHERIT:
15029                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15030                    // later to get the correct resolved value
15031                    if (!canResolveLayoutDirection()) return false;
15032
15033                    // Parent has not yet resolved, LTR is still the default
15034                    try {
15035                        if (!mParent.isLayoutDirectionResolved()) return false;
15036
15037                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15038                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15039                        }
15040                    } catch (AbstractMethodError e) {
15041                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15042                                " does not fully implement ViewParent", e);
15043                    }
15044                    break;
15045                case LAYOUT_DIRECTION_RTL:
15046                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15047                    break;
15048                case LAYOUT_DIRECTION_LOCALE:
15049                    if((LAYOUT_DIRECTION_RTL ==
15050                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15051                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15052                    }
15053                    break;
15054                default:
15055                    // Nothing to do, LTR by default
15056            }
15057        }
15058
15059        // Set to resolved
15060        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15061        return true;
15062    }
15063
15064    /**
15065     * Check if layout direction resolution can be done.
15066     *
15067     * @return true if layout direction resolution can be done otherwise return false.
15068     */
15069    public boolean canResolveLayoutDirection() {
15070        switch (getRawLayoutDirection()) {
15071            case LAYOUT_DIRECTION_INHERIT:
15072                if (mParent != null) {
15073                    try {
15074                        return mParent.canResolveLayoutDirection();
15075                    } catch (AbstractMethodError e) {
15076                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15077                                " does not fully implement ViewParent", e);
15078                    }
15079                }
15080                return false;
15081
15082            default:
15083                return true;
15084        }
15085    }
15086
15087    /**
15088     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15089     * {@link #onMeasure(int, int)}.
15090     *
15091     * @hide
15092     */
15093    public void resetResolvedLayoutDirection() {
15094        // Reset the current resolved bits
15095        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15096    }
15097
15098    /**
15099     * @return true if the layout direction is inherited.
15100     *
15101     * @hide
15102     */
15103    public boolean isLayoutDirectionInherited() {
15104        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15105    }
15106
15107    /**
15108     * @return true if layout direction has been resolved.
15109     */
15110    public boolean isLayoutDirectionResolved() {
15111        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15112    }
15113
15114    /**
15115     * Return if padding has been resolved
15116     *
15117     * @hide
15118     */
15119    boolean isPaddingResolved() {
15120        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15121    }
15122
15123    /**
15124     * Resolves padding depending on layout direction, if applicable, and
15125     * recomputes internal padding values to adjust for scroll bars.
15126     *
15127     * @hide
15128     */
15129    public void resolvePadding() {
15130        final int resolvedLayoutDirection = getLayoutDirection();
15131
15132        if (!isRtlCompatibilityMode()) {
15133            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15134            // If start / end padding are defined, they will be resolved (hence overriding) to
15135            // left / right or right / left depending on the resolved layout direction.
15136            // If start / end padding are not defined, use the left / right ones.
15137            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15138                Rect padding = sThreadLocal.get();
15139                if (padding == null) {
15140                    padding = new Rect();
15141                    sThreadLocal.set(padding);
15142                }
15143                mBackground.getPadding(padding);
15144                if (!mLeftPaddingDefined) {
15145                    mUserPaddingLeftInitial = padding.left;
15146                }
15147                if (!mRightPaddingDefined) {
15148                    mUserPaddingRightInitial = padding.right;
15149                }
15150            }
15151            switch (resolvedLayoutDirection) {
15152                case LAYOUT_DIRECTION_RTL:
15153                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15154                        mUserPaddingRight = mUserPaddingStart;
15155                    } else {
15156                        mUserPaddingRight = mUserPaddingRightInitial;
15157                    }
15158                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15159                        mUserPaddingLeft = mUserPaddingEnd;
15160                    } else {
15161                        mUserPaddingLeft = mUserPaddingLeftInitial;
15162                    }
15163                    break;
15164                case LAYOUT_DIRECTION_LTR:
15165                default:
15166                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15167                        mUserPaddingLeft = mUserPaddingStart;
15168                    } else {
15169                        mUserPaddingLeft = mUserPaddingLeftInitial;
15170                    }
15171                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15172                        mUserPaddingRight = mUserPaddingEnd;
15173                    } else {
15174                        mUserPaddingRight = mUserPaddingRightInitial;
15175                    }
15176            }
15177
15178            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15179        }
15180
15181        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15182        onRtlPropertiesChanged(resolvedLayoutDirection);
15183
15184        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15185    }
15186
15187    /**
15188     * Reset the resolved layout direction.
15189     *
15190     * @hide
15191     */
15192    public void resetResolvedPadding() {
15193        resetResolvedPaddingInternal();
15194    }
15195
15196    /**
15197     * Used when we only want to reset *this* view's padding and not trigger overrides
15198     * in ViewGroup that reset children too.
15199     */
15200    void resetResolvedPaddingInternal() {
15201        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15202    }
15203
15204    /**
15205     * This is called when the view is detached from a window.  At this point it
15206     * no longer has a surface for drawing.
15207     *
15208     * @see #onAttachedToWindow()
15209     */
15210    @CallSuper
15211    protected void onDetachedFromWindow() {
15212    }
15213
15214    /**
15215     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15216     * after onDetachedFromWindow().
15217     *
15218     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15219     * The super method should be called at the end of the overridden method to ensure
15220     * subclasses are destroyed first
15221     *
15222     * @hide
15223     */
15224    @CallSuper
15225    protected void onDetachedFromWindowInternal() {
15226        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15227        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15228        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15229
15230        removeUnsetPressCallback();
15231        removeLongPressCallback();
15232        removePerformClickCallback();
15233        removeSendViewScrolledAccessibilityEventCallback();
15234        stopNestedScroll();
15235
15236        // Anything that started animating right before detach should already
15237        // be in its final state when re-attached.
15238        jumpDrawablesToCurrentState();
15239
15240        destroyDrawingCache();
15241
15242        cleanupDraw();
15243        releasePointerCapture();
15244        mCurrentAnimation = null;
15245    }
15246
15247    private void cleanupDraw() {
15248        resetDisplayList();
15249        if (mAttachInfo != null) {
15250            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15251        }
15252    }
15253
15254    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15255    }
15256
15257    /**
15258     * @return The number of times this view has been attached to a window
15259     */
15260    protected int getWindowAttachCount() {
15261        return mWindowAttachCount;
15262    }
15263
15264    /**
15265     * Retrieve a unique token identifying the window this view is attached to.
15266     * @return Return the window's token for use in
15267     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15268     */
15269    public IBinder getWindowToken() {
15270        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15271    }
15272
15273    /**
15274     * Retrieve the {@link WindowId} for the window this view is
15275     * currently attached to.
15276     */
15277    public WindowId getWindowId() {
15278        if (mAttachInfo == null) {
15279            return null;
15280        }
15281        if (mAttachInfo.mWindowId == null) {
15282            try {
15283                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15284                        mAttachInfo.mWindowToken);
15285                mAttachInfo.mWindowId = new WindowId(
15286                        mAttachInfo.mIWindowId);
15287            } catch (RemoteException e) {
15288            }
15289        }
15290        return mAttachInfo.mWindowId;
15291    }
15292
15293    /**
15294     * Retrieve a unique token identifying the top-level "real" window of
15295     * the window that this view is attached to.  That is, this is like
15296     * {@link #getWindowToken}, except if the window this view in is a panel
15297     * window (attached to another containing window), then the token of
15298     * the containing window is returned instead.
15299     *
15300     * @return Returns the associated window token, either
15301     * {@link #getWindowToken()} or the containing window's token.
15302     */
15303    public IBinder getApplicationWindowToken() {
15304        AttachInfo ai = mAttachInfo;
15305        if (ai != null) {
15306            IBinder appWindowToken = ai.mPanelParentWindowToken;
15307            if (appWindowToken == null) {
15308                appWindowToken = ai.mWindowToken;
15309            }
15310            return appWindowToken;
15311        }
15312        return null;
15313    }
15314
15315    /**
15316     * Gets the logical display to which the view's window has been attached.
15317     *
15318     * @return The logical display, or null if the view is not currently attached to a window.
15319     */
15320    public Display getDisplay() {
15321        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15322    }
15323
15324    /**
15325     * Retrieve private session object this view hierarchy is using to
15326     * communicate with the window manager.
15327     * @return the session object to communicate with the window manager
15328     */
15329    /*package*/ IWindowSession getWindowSession() {
15330        return mAttachInfo != null ? mAttachInfo.mSession : null;
15331    }
15332
15333    /**
15334     * Return the visibility value of the least visible component passed.
15335     */
15336    int combineVisibility(int vis1, int vis2) {
15337        // This works because VISIBLE < INVISIBLE < GONE.
15338        return Math.max(vis1, vis2);
15339    }
15340
15341    /**
15342     * @param info the {@link android.view.View.AttachInfo} to associated with
15343     *        this view
15344     */
15345    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15346        mAttachInfo = info;
15347        if (mOverlay != null) {
15348            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15349        }
15350        mWindowAttachCount++;
15351        // We will need to evaluate the drawable state at least once.
15352        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15353        if (mFloatingTreeObserver != null) {
15354            info.mTreeObserver.merge(mFloatingTreeObserver);
15355            mFloatingTreeObserver = null;
15356        }
15357
15358        registerPendingFrameMetricsObservers();
15359
15360        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15361            mAttachInfo.mScrollContainers.add(this);
15362            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15363        }
15364        // Transfer all pending runnables.
15365        if (mRunQueue != null) {
15366            mRunQueue.executeActions(info.mHandler);
15367            mRunQueue = null;
15368        }
15369        performCollectViewAttributes(mAttachInfo, visibility);
15370        onAttachedToWindow();
15371
15372        ListenerInfo li = mListenerInfo;
15373        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15374                li != null ? li.mOnAttachStateChangeListeners : null;
15375        if (listeners != null && listeners.size() > 0) {
15376            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15377            // perform the dispatching. The iterator is a safe guard against listeners that
15378            // could mutate the list by calling the various add/remove methods. This prevents
15379            // the array from being modified while we iterate it.
15380            for (OnAttachStateChangeListener listener : listeners) {
15381                listener.onViewAttachedToWindow(this);
15382            }
15383        }
15384
15385        int vis = info.mWindowVisibility;
15386        if (vis != GONE) {
15387            onWindowVisibilityChanged(vis);
15388            if (isShown()) {
15389                // Calling onVisibilityChanged directly here since the subtree will also
15390                // receive dispatchAttachedToWindow and this same call
15391                onVisibilityAggregated(vis == VISIBLE);
15392            }
15393        }
15394
15395        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15396        // As all views in the subtree will already receive dispatchAttachedToWindow
15397        // traversing the subtree again here is not desired.
15398        onVisibilityChanged(this, visibility);
15399
15400        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15401            // If nobody has evaluated the drawable state yet, then do it now.
15402            refreshDrawableState();
15403        }
15404        needGlobalAttributesUpdate(false);
15405    }
15406
15407    void dispatchDetachedFromWindow() {
15408        AttachInfo info = mAttachInfo;
15409        if (info != null) {
15410            int vis = info.mWindowVisibility;
15411            if (vis != GONE) {
15412                onWindowVisibilityChanged(GONE);
15413                if (isShown()) {
15414                    // Invoking onVisibilityAggregated directly here since the subtree
15415                    // will also receive detached from window
15416                    onVisibilityAggregated(false);
15417                }
15418            }
15419        }
15420
15421        onDetachedFromWindow();
15422        onDetachedFromWindowInternal();
15423
15424        InputMethodManager imm = InputMethodManager.peekInstance();
15425        if (imm != null) {
15426            imm.onViewDetachedFromWindow(this);
15427        }
15428
15429        ListenerInfo li = mListenerInfo;
15430        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15431                li != null ? li.mOnAttachStateChangeListeners : null;
15432        if (listeners != null && listeners.size() > 0) {
15433            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15434            // perform the dispatching. The iterator is a safe guard against listeners that
15435            // could mutate the list by calling the various add/remove methods. This prevents
15436            // the array from being modified while we iterate it.
15437            for (OnAttachStateChangeListener listener : listeners) {
15438                listener.onViewDetachedFromWindow(this);
15439            }
15440        }
15441
15442        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15443            mAttachInfo.mScrollContainers.remove(this);
15444            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15445        }
15446
15447        mAttachInfo = null;
15448        if (mOverlay != null) {
15449            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15450        }
15451    }
15452
15453    /**
15454     * Cancel any deferred high-level input events that were previously posted to the event queue.
15455     *
15456     * <p>Many views post high-level events such as click handlers to the event queue
15457     * to run deferred in order to preserve a desired user experience - clearing visible
15458     * pressed states before executing, etc. This method will abort any events of this nature
15459     * that are currently in flight.</p>
15460     *
15461     * <p>Custom views that generate their own high-level deferred input events should override
15462     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15463     *
15464     * <p>This will also cancel pending input events for any child views.</p>
15465     *
15466     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15467     * This will not impact newer events posted after this call that may occur as a result of
15468     * lower-level input events still waiting in the queue. If you are trying to prevent
15469     * double-submitted  events for the duration of some sort of asynchronous transaction
15470     * you should also take other steps to protect against unexpected double inputs e.g. calling
15471     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15472     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15473     */
15474    public final void cancelPendingInputEvents() {
15475        dispatchCancelPendingInputEvents();
15476    }
15477
15478    /**
15479     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
15480     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
15481     */
15482    void dispatchCancelPendingInputEvents() {
15483        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
15484        onCancelPendingInputEvents();
15485        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
15486            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
15487                    " did not call through to super.onCancelPendingInputEvents()");
15488        }
15489    }
15490
15491    /**
15492     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
15493     * a parent view.
15494     *
15495     * <p>This method is responsible for removing any pending high-level input events that were
15496     * posted to the event queue to run later. Custom view classes that post their own deferred
15497     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
15498     * {@link android.os.Handler} should override this method, call
15499     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
15500     * </p>
15501     */
15502    public void onCancelPendingInputEvents() {
15503        removePerformClickCallback();
15504        cancelLongPress();
15505        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
15506    }
15507
15508    /**
15509     * Store this view hierarchy's frozen state into the given container.
15510     *
15511     * @param container The SparseArray in which to save the view's state.
15512     *
15513     * @see #restoreHierarchyState(android.util.SparseArray)
15514     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15515     * @see #onSaveInstanceState()
15516     */
15517    public void saveHierarchyState(SparseArray<Parcelable> container) {
15518        dispatchSaveInstanceState(container);
15519    }
15520
15521    /**
15522     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
15523     * this view and its children. May be overridden to modify how freezing happens to a
15524     * view's children; for example, some views may want to not store state for their children.
15525     *
15526     * @param container The SparseArray in which to save the view's state.
15527     *
15528     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15529     * @see #saveHierarchyState(android.util.SparseArray)
15530     * @see #onSaveInstanceState()
15531     */
15532    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
15533        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
15534            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15535            Parcelable state = onSaveInstanceState();
15536            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15537                throw new IllegalStateException(
15538                        "Derived class did not call super.onSaveInstanceState()");
15539            }
15540            if (state != null) {
15541                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
15542                // + ": " + state);
15543                container.put(mID, state);
15544            }
15545        }
15546    }
15547
15548    /**
15549     * Hook allowing a view to generate a representation of its internal state
15550     * that can later be used to create a new instance with that same state.
15551     * This state should only contain information that is not persistent or can
15552     * not be reconstructed later. For example, you will never store your
15553     * current position on screen because that will be computed again when a
15554     * new instance of the view is placed in its view hierarchy.
15555     * <p>
15556     * Some examples of things you may store here: the current cursor position
15557     * in a text view (but usually not the text itself since that is stored in a
15558     * content provider or other persistent storage), the currently selected
15559     * item in a list view.
15560     *
15561     * @return Returns a Parcelable object containing the view's current dynamic
15562     *         state, or null if there is nothing interesting to save. The
15563     *         default implementation returns null.
15564     * @see #onRestoreInstanceState(android.os.Parcelable)
15565     * @see #saveHierarchyState(android.util.SparseArray)
15566     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15567     * @see #setSaveEnabled(boolean)
15568     */
15569    @CallSuper
15570    protected Parcelable onSaveInstanceState() {
15571        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15572        if (mStartActivityRequestWho != null) {
15573            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
15574            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
15575            return state;
15576        }
15577        return BaseSavedState.EMPTY_STATE;
15578    }
15579
15580    /**
15581     * Restore this view hierarchy's frozen state from the given container.
15582     *
15583     * @param container The SparseArray which holds previously frozen states.
15584     *
15585     * @see #saveHierarchyState(android.util.SparseArray)
15586     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15587     * @see #onRestoreInstanceState(android.os.Parcelable)
15588     */
15589    public void restoreHierarchyState(SparseArray<Parcelable> container) {
15590        dispatchRestoreInstanceState(container);
15591    }
15592
15593    /**
15594     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
15595     * state for this view and its children. May be overridden to modify how restoring
15596     * happens to a view's children; for example, some views may want to not store state
15597     * for their children.
15598     *
15599     * @param container The SparseArray which holds previously saved state.
15600     *
15601     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15602     * @see #restoreHierarchyState(android.util.SparseArray)
15603     * @see #onRestoreInstanceState(android.os.Parcelable)
15604     */
15605    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
15606        if (mID != NO_ID) {
15607            Parcelable state = container.get(mID);
15608            if (state != null) {
15609                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
15610                // + ": " + state);
15611                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15612                onRestoreInstanceState(state);
15613                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15614                    throw new IllegalStateException(
15615                            "Derived class did not call super.onRestoreInstanceState()");
15616                }
15617            }
15618        }
15619    }
15620
15621    /**
15622     * Hook allowing a view to re-apply a representation of its internal state that had previously
15623     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
15624     * null state.
15625     *
15626     * @param state The frozen state that had previously been returned by
15627     *        {@link #onSaveInstanceState}.
15628     *
15629     * @see #onSaveInstanceState()
15630     * @see #restoreHierarchyState(android.util.SparseArray)
15631     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15632     */
15633    @CallSuper
15634    protected void onRestoreInstanceState(Parcelable state) {
15635        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15636        if (state != null && !(state instanceof AbsSavedState)) {
15637            throw new IllegalArgumentException("Wrong state class, expecting View State but "
15638                    + "received " + state.getClass().toString() + " instead. This usually happens "
15639                    + "when two views of different type have the same id in the same hierarchy. "
15640                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
15641                    + "other views do not use the same id.");
15642        }
15643        if (state != null && state instanceof BaseSavedState) {
15644            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
15645        }
15646    }
15647
15648    /**
15649     * <p>Return the time at which the drawing of the view hierarchy started.</p>
15650     *
15651     * @return the drawing start time in milliseconds
15652     */
15653    public long getDrawingTime() {
15654        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
15655    }
15656
15657    /**
15658     * <p>Enables or disables the duplication of the parent's state into this view. When
15659     * duplication is enabled, this view gets its drawable state from its parent rather
15660     * than from its own internal properties.</p>
15661     *
15662     * <p>Note: in the current implementation, setting this property to true after the
15663     * view was added to a ViewGroup might have no effect at all. This property should
15664     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
15665     *
15666     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
15667     * property is enabled, an exception will be thrown.</p>
15668     *
15669     * <p>Note: if the child view uses and updates additional states which are unknown to the
15670     * parent, these states should not be affected by this method.</p>
15671     *
15672     * @param enabled True to enable duplication of the parent's drawable state, false
15673     *                to disable it.
15674     *
15675     * @see #getDrawableState()
15676     * @see #isDuplicateParentStateEnabled()
15677     */
15678    public void setDuplicateParentStateEnabled(boolean enabled) {
15679        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
15680    }
15681
15682    /**
15683     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
15684     *
15685     * @return True if this view's drawable state is duplicated from the parent,
15686     *         false otherwise
15687     *
15688     * @see #getDrawableState()
15689     * @see #setDuplicateParentStateEnabled(boolean)
15690     */
15691    public boolean isDuplicateParentStateEnabled() {
15692        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
15693    }
15694
15695    /**
15696     * <p>Specifies the type of layer backing this view. The layer can be
15697     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15698     * {@link #LAYER_TYPE_HARDWARE}.</p>
15699     *
15700     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15701     * instance that controls how the layer is composed on screen. The following
15702     * properties of the paint are taken into account when composing the layer:</p>
15703     * <ul>
15704     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15705     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15706     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15707     * </ul>
15708     *
15709     * <p>If this view has an alpha value set to < 1.0 by calling
15710     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
15711     * by this view's alpha value.</p>
15712     *
15713     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
15714     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
15715     * for more information on when and how to use layers.</p>
15716     *
15717     * @param layerType The type of layer to use with this view, must be one of
15718     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15719     *        {@link #LAYER_TYPE_HARDWARE}
15720     * @param paint The paint used to compose the layer. This argument is optional
15721     *        and can be null. It is ignored when the layer type is
15722     *        {@link #LAYER_TYPE_NONE}
15723     *
15724     * @see #getLayerType()
15725     * @see #LAYER_TYPE_NONE
15726     * @see #LAYER_TYPE_SOFTWARE
15727     * @see #LAYER_TYPE_HARDWARE
15728     * @see #setAlpha(float)
15729     *
15730     * @attr ref android.R.styleable#View_layerType
15731     */
15732    public void setLayerType(int layerType, @Nullable Paint paint) {
15733        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
15734            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
15735                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
15736        }
15737
15738        boolean typeChanged = mRenderNode.setLayerType(layerType);
15739
15740        if (!typeChanged) {
15741            setLayerPaint(paint);
15742            return;
15743        }
15744
15745        if (layerType != LAYER_TYPE_SOFTWARE) {
15746            // Destroy any previous software drawing cache if present
15747            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
15748            // drawing cache created in View#draw when drawing to a SW canvas.
15749            destroyDrawingCache();
15750        }
15751
15752        mLayerType = layerType;
15753        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
15754        mRenderNode.setLayerPaint(mLayerPaint);
15755
15756        // draw() behaves differently if we are on a layer, so we need to
15757        // invalidate() here
15758        invalidateParentCaches();
15759        invalidate(true);
15760    }
15761
15762    /**
15763     * Updates the {@link Paint} object used with the current layer (used only if the current
15764     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
15765     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
15766     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
15767     * ensure that the view gets redrawn immediately.
15768     *
15769     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15770     * instance that controls how the layer is composed on screen. The following
15771     * properties of the paint are taken into account when composing the layer:</p>
15772     * <ul>
15773     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15774     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15775     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15776     * </ul>
15777     *
15778     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
15779     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
15780     *
15781     * @param paint The paint used to compose the layer. This argument is optional
15782     *        and can be null. It is ignored when the layer type is
15783     *        {@link #LAYER_TYPE_NONE}
15784     *
15785     * @see #setLayerType(int, android.graphics.Paint)
15786     */
15787    public void setLayerPaint(@Nullable Paint paint) {
15788        int layerType = getLayerType();
15789        if (layerType != LAYER_TYPE_NONE) {
15790            mLayerPaint = paint;
15791            if (layerType == LAYER_TYPE_HARDWARE) {
15792                if (mRenderNode.setLayerPaint(paint)) {
15793                    invalidateViewProperty(false, false);
15794                }
15795            } else {
15796                invalidate();
15797            }
15798        }
15799    }
15800
15801    /**
15802     * Indicates what type of layer is currently associated with this view. By default
15803     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
15804     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
15805     * for more information on the different types of layers.
15806     *
15807     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15808     *         {@link #LAYER_TYPE_HARDWARE}
15809     *
15810     * @see #setLayerType(int, android.graphics.Paint)
15811     * @see #buildLayer()
15812     * @see #LAYER_TYPE_NONE
15813     * @see #LAYER_TYPE_SOFTWARE
15814     * @see #LAYER_TYPE_HARDWARE
15815     */
15816    public int getLayerType() {
15817        return mLayerType;
15818    }
15819
15820    /**
15821     * Forces this view's layer to be created and this view to be rendered
15822     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
15823     * invoking this method will have no effect.
15824     *
15825     * This method can for instance be used to render a view into its layer before
15826     * starting an animation. If this view is complex, rendering into the layer
15827     * before starting the animation will avoid skipping frames.
15828     *
15829     * @throws IllegalStateException If this view is not attached to a window
15830     *
15831     * @see #setLayerType(int, android.graphics.Paint)
15832     */
15833    public void buildLayer() {
15834        if (mLayerType == LAYER_TYPE_NONE) return;
15835
15836        final AttachInfo attachInfo = mAttachInfo;
15837        if (attachInfo == null) {
15838            throw new IllegalStateException("This view must be attached to a window first");
15839        }
15840
15841        if (getWidth() == 0 || getHeight() == 0) {
15842            return;
15843        }
15844
15845        switch (mLayerType) {
15846            case LAYER_TYPE_HARDWARE:
15847                updateDisplayListIfDirty();
15848                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
15849                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
15850                }
15851                break;
15852            case LAYER_TYPE_SOFTWARE:
15853                buildDrawingCache(true);
15854                break;
15855        }
15856    }
15857
15858    /**
15859     * Destroys all hardware rendering resources. This method is invoked
15860     * when the system needs to reclaim resources. Upon execution of this
15861     * method, you should free any OpenGL resources created by the view.
15862     *
15863     * Note: you <strong>must</strong> call
15864     * <code>super.destroyHardwareResources()</code> when overriding
15865     * this method.
15866     *
15867     * @hide
15868     */
15869    @CallSuper
15870    protected void destroyHardwareResources() {
15871        // Although the Layer will be destroyed by RenderNode, we want to release
15872        // the staging display list, which is also a signal to RenderNode that it's
15873        // safe to free its copy of the display list as it knows that we will
15874        // push an updated DisplayList if we try to draw again
15875        resetDisplayList();
15876    }
15877
15878    /**
15879     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
15880     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
15881     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
15882     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
15883     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
15884     * null.</p>
15885     *
15886     * <p>Enabling the drawing cache is similar to
15887     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
15888     * acceleration is turned off. When hardware acceleration is turned on, enabling the
15889     * drawing cache has no effect on rendering because the system uses a different mechanism
15890     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
15891     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
15892     * for information on how to enable software and hardware layers.</p>
15893     *
15894     * <p>This API can be used to manually generate
15895     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
15896     * {@link #getDrawingCache()}.</p>
15897     *
15898     * @param enabled true to enable the drawing cache, false otherwise
15899     *
15900     * @see #isDrawingCacheEnabled()
15901     * @see #getDrawingCache()
15902     * @see #buildDrawingCache()
15903     * @see #setLayerType(int, android.graphics.Paint)
15904     */
15905    public void setDrawingCacheEnabled(boolean enabled) {
15906        mCachingFailed = false;
15907        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
15908    }
15909
15910    /**
15911     * <p>Indicates whether the drawing cache is enabled for this view.</p>
15912     *
15913     * @return true if the drawing cache is enabled
15914     *
15915     * @see #setDrawingCacheEnabled(boolean)
15916     * @see #getDrawingCache()
15917     */
15918    @ViewDebug.ExportedProperty(category = "drawing")
15919    public boolean isDrawingCacheEnabled() {
15920        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
15921    }
15922
15923    /**
15924     * Debugging utility which recursively outputs the dirty state of a view and its
15925     * descendants.
15926     *
15927     * @hide
15928     */
15929    @SuppressWarnings({"UnusedDeclaration"})
15930    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
15931        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
15932                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
15933                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
15934                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
15935        if (clear) {
15936            mPrivateFlags &= clearMask;
15937        }
15938        if (this instanceof ViewGroup) {
15939            ViewGroup parent = (ViewGroup) this;
15940            final int count = parent.getChildCount();
15941            for (int i = 0; i < count; i++) {
15942                final View child = parent.getChildAt(i);
15943                child.outputDirtyFlags(indent + "  ", clear, clearMask);
15944            }
15945        }
15946    }
15947
15948    /**
15949     * This method is used by ViewGroup to cause its children to restore or recreate their
15950     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
15951     * to recreate its own display list, which would happen if it went through the normal
15952     * draw/dispatchDraw mechanisms.
15953     *
15954     * @hide
15955     */
15956    protected void dispatchGetDisplayList() {}
15957
15958    /**
15959     * A view that is not attached or hardware accelerated cannot create a display list.
15960     * This method checks these conditions and returns the appropriate result.
15961     *
15962     * @return true if view has the ability to create a display list, false otherwise.
15963     *
15964     * @hide
15965     */
15966    public boolean canHaveDisplayList() {
15967        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
15968    }
15969
15970    /**
15971     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
15972     * @hide
15973     */
15974    @NonNull
15975    public RenderNode updateDisplayListIfDirty() {
15976        final RenderNode renderNode = mRenderNode;
15977        if (!canHaveDisplayList()) {
15978            // can't populate RenderNode, don't try
15979            return renderNode;
15980        }
15981
15982        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
15983                || !renderNode.isValid()
15984                || (mRecreateDisplayList)) {
15985            // Don't need to recreate the display list, just need to tell our
15986            // children to restore/recreate theirs
15987            if (renderNode.isValid()
15988                    && !mRecreateDisplayList) {
15989                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
15990                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15991                dispatchGetDisplayList();
15992
15993                return renderNode; // no work needed
15994            }
15995
15996            // If we got here, we're recreating it. Mark it as such to ensure that
15997            // we copy in child display lists into ours in drawChild()
15998            mRecreateDisplayList = true;
15999
16000            int width = mRight - mLeft;
16001            int height = mBottom - mTop;
16002            int layerType = getLayerType();
16003
16004            final DisplayListCanvas canvas = renderNode.start(width, height);
16005            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16006
16007            try {
16008                if (layerType == LAYER_TYPE_SOFTWARE) {
16009                    buildDrawingCache(true);
16010                    Bitmap cache = getDrawingCache(true);
16011                    if (cache != null) {
16012                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16013                    }
16014                } else {
16015                    computeScroll();
16016
16017                    canvas.translate(-mScrollX, -mScrollY);
16018                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16019                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16020
16021                    // Fast path for layouts with no backgrounds
16022                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16023                        dispatchDraw(canvas);
16024                        if (mOverlay != null && !mOverlay.isEmpty()) {
16025                            mOverlay.getOverlayView().draw(canvas);
16026                        }
16027                    } else {
16028                        draw(canvas);
16029                    }
16030                }
16031            } finally {
16032                renderNode.end(canvas);
16033                setDisplayListProperties(renderNode);
16034            }
16035        } else {
16036            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16037            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16038        }
16039        return renderNode;
16040    }
16041
16042    private void resetDisplayList() {
16043        if (mRenderNode.isValid()) {
16044            mRenderNode.discardDisplayList();
16045        }
16046
16047        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16048            mBackgroundRenderNode.discardDisplayList();
16049        }
16050    }
16051
16052    /**
16053     * Called when the passed RenderNode is removed from the draw tree
16054     * @hide
16055     */
16056    public void onRenderNodeDetached(RenderNode renderNode) {
16057        if (renderNode == mRenderNode && mRenderNodeDetachedCallback != null) {
16058            mRenderNodeDetachedCallback.run();
16059        }
16060    }
16061
16062    /**
16063     * Set callback for functor detach. Exposed to WebView through WebViewDelegate.
16064     * Should not be used otherwise.
16065     * @hide
16066     */
16067    public final Runnable setRenderNodeDetachedCallback(@Nullable Runnable callback) {
16068        Runnable oldCallback = mRenderNodeDetachedCallback;
16069        mRenderNodeDetachedCallback = callback;
16070        return oldCallback;
16071    }
16072
16073    /**
16074     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16075     *
16076     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16077     *
16078     * @see #getDrawingCache(boolean)
16079     */
16080    public Bitmap getDrawingCache() {
16081        return getDrawingCache(false);
16082    }
16083
16084    /**
16085     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16086     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16087     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16088     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16089     * request the drawing cache by calling this method and draw it on screen if the
16090     * returned bitmap is not null.</p>
16091     *
16092     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16093     * this method will create a bitmap of the same size as this view. Because this bitmap
16094     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16095     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16096     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16097     * size than the view. This implies that your application must be able to handle this
16098     * size.</p>
16099     *
16100     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16101     *        the current density of the screen when the application is in compatibility
16102     *        mode.
16103     *
16104     * @return A bitmap representing this view or null if cache is disabled.
16105     *
16106     * @see #setDrawingCacheEnabled(boolean)
16107     * @see #isDrawingCacheEnabled()
16108     * @see #buildDrawingCache(boolean)
16109     * @see #destroyDrawingCache()
16110     */
16111    public Bitmap getDrawingCache(boolean autoScale) {
16112        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16113            return null;
16114        }
16115        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16116            buildDrawingCache(autoScale);
16117        }
16118        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16119    }
16120
16121    /**
16122     * <p>Frees the resources used by the drawing cache. If you call
16123     * {@link #buildDrawingCache()} manually without calling
16124     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16125     * should cleanup the cache with this method afterwards.</p>
16126     *
16127     * @see #setDrawingCacheEnabled(boolean)
16128     * @see #buildDrawingCache()
16129     * @see #getDrawingCache()
16130     */
16131    public void destroyDrawingCache() {
16132        if (mDrawingCache != null) {
16133            mDrawingCache.recycle();
16134            mDrawingCache = null;
16135        }
16136        if (mUnscaledDrawingCache != null) {
16137            mUnscaledDrawingCache.recycle();
16138            mUnscaledDrawingCache = null;
16139        }
16140    }
16141
16142    /**
16143     * Setting a solid background color for the drawing cache's bitmaps will improve
16144     * performance and memory usage. Note, though that this should only be used if this
16145     * view will always be drawn on top of a solid color.
16146     *
16147     * @param color The background color to use for the drawing cache's bitmap
16148     *
16149     * @see #setDrawingCacheEnabled(boolean)
16150     * @see #buildDrawingCache()
16151     * @see #getDrawingCache()
16152     */
16153    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16154        if (color != mDrawingCacheBackgroundColor) {
16155            mDrawingCacheBackgroundColor = color;
16156            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16157        }
16158    }
16159
16160    /**
16161     * @see #setDrawingCacheBackgroundColor(int)
16162     *
16163     * @return The background color to used for the drawing cache's bitmap
16164     */
16165    @ColorInt
16166    public int getDrawingCacheBackgroundColor() {
16167        return mDrawingCacheBackgroundColor;
16168    }
16169
16170    /**
16171     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16172     *
16173     * @see #buildDrawingCache(boolean)
16174     */
16175    public void buildDrawingCache() {
16176        buildDrawingCache(false);
16177    }
16178
16179    /**
16180     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16181     *
16182     * <p>If you call {@link #buildDrawingCache()} manually without calling
16183     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16184     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16185     *
16186     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16187     * this method will create a bitmap of the same size as this view. Because this bitmap
16188     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16189     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16190     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16191     * size than the view. This implies that your application must be able to handle this
16192     * size.</p>
16193     *
16194     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16195     * you do not need the drawing cache bitmap, calling this method will increase memory
16196     * usage and cause the view to be rendered in software once, thus negatively impacting
16197     * performance.</p>
16198     *
16199     * @see #getDrawingCache()
16200     * @see #destroyDrawingCache()
16201     */
16202    public void buildDrawingCache(boolean autoScale) {
16203        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16204                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16205            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16206                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16207                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16208            }
16209            try {
16210                buildDrawingCacheImpl(autoScale);
16211            } finally {
16212                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16213            }
16214        }
16215    }
16216
16217    /**
16218     * private, internal implementation of buildDrawingCache, used to enable tracing
16219     */
16220    private void buildDrawingCacheImpl(boolean autoScale) {
16221        mCachingFailed = false;
16222
16223        int width = mRight - mLeft;
16224        int height = mBottom - mTop;
16225
16226        final AttachInfo attachInfo = mAttachInfo;
16227        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16228
16229        if (autoScale && scalingRequired) {
16230            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16231            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16232        }
16233
16234        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16235        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16236        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16237
16238        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16239        final long drawingCacheSize =
16240                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16241        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16242            if (width > 0 && height > 0) {
16243                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16244                        + " too large to fit into a software layer (or drawing cache), needs "
16245                        + projectedBitmapSize + " bytes, only "
16246                        + drawingCacheSize + " available");
16247            }
16248            destroyDrawingCache();
16249            mCachingFailed = true;
16250            return;
16251        }
16252
16253        boolean clear = true;
16254        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16255
16256        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16257            Bitmap.Config quality;
16258            if (!opaque) {
16259                // Never pick ARGB_4444 because it looks awful
16260                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16261                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16262                    case DRAWING_CACHE_QUALITY_AUTO:
16263                    case DRAWING_CACHE_QUALITY_LOW:
16264                    case DRAWING_CACHE_QUALITY_HIGH:
16265                    default:
16266                        quality = Bitmap.Config.ARGB_8888;
16267                        break;
16268                }
16269            } else {
16270                // Optimization for translucent windows
16271                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16272                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16273            }
16274
16275            // Try to cleanup memory
16276            if (bitmap != null) bitmap.recycle();
16277
16278            try {
16279                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16280                        width, height, quality);
16281                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16282                if (autoScale) {
16283                    mDrawingCache = bitmap;
16284                } else {
16285                    mUnscaledDrawingCache = bitmap;
16286                }
16287                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16288            } catch (OutOfMemoryError e) {
16289                // If there is not enough memory to create the bitmap cache, just
16290                // ignore the issue as bitmap caches are not required to draw the
16291                // view hierarchy
16292                if (autoScale) {
16293                    mDrawingCache = null;
16294                } else {
16295                    mUnscaledDrawingCache = null;
16296                }
16297                mCachingFailed = true;
16298                return;
16299            }
16300
16301            clear = drawingCacheBackgroundColor != 0;
16302        }
16303
16304        Canvas canvas;
16305        if (attachInfo != null) {
16306            canvas = attachInfo.mCanvas;
16307            if (canvas == null) {
16308                canvas = new Canvas();
16309            }
16310            canvas.setBitmap(bitmap);
16311            // Temporarily clobber the cached Canvas in case one of our children
16312            // is also using a drawing cache. Without this, the children would
16313            // steal the canvas by attaching their own bitmap to it and bad, bad
16314            // thing would happen (invisible views, corrupted drawings, etc.)
16315            attachInfo.mCanvas = null;
16316        } else {
16317            // This case should hopefully never or seldom happen
16318            canvas = new Canvas(bitmap);
16319        }
16320
16321        if (clear) {
16322            bitmap.eraseColor(drawingCacheBackgroundColor);
16323        }
16324
16325        computeScroll();
16326        final int restoreCount = canvas.save();
16327
16328        if (autoScale && scalingRequired) {
16329            final float scale = attachInfo.mApplicationScale;
16330            canvas.scale(scale, scale);
16331        }
16332
16333        canvas.translate(-mScrollX, -mScrollY);
16334
16335        mPrivateFlags |= PFLAG_DRAWN;
16336        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16337                mLayerType != LAYER_TYPE_NONE) {
16338            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16339        }
16340
16341        // Fast path for layouts with no backgrounds
16342        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16343            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16344            dispatchDraw(canvas);
16345            if (mOverlay != null && !mOverlay.isEmpty()) {
16346                mOverlay.getOverlayView().draw(canvas);
16347            }
16348        } else {
16349            draw(canvas);
16350        }
16351
16352        canvas.restoreToCount(restoreCount);
16353        canvas.setBitmap(null);
16354
16355        if (attachInfo != null) {
16356            // Restore the cached Canvas for our siblings
16357            attachInfo.mCanvas = canvas;
16358        }
16359    }
16360
16361    /**
16362     * Create a snapshot of the view into a bitmap.  We should probably make
16363     * some form of this public, but should think about the API.
16364     *
16365     * @hide
16366     */
16367    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16368        int width = mRight - mLeft;
16369        int height = mBottom - mTop;
16370
16371        final AttachInfo attachInfo = mAttachInfo;
16372        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16373        width = (int) ((width * scale) + 0.5f);
16374        height = (int) ((height * scale) + 0.5f);
16375
16376        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16377                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16378        if (bitmap == null) {
16379            throw new OutOfMemoryError();
16380        }
16381
16382        Resources resources = getResources();
16383        if (resources != null) {
16384            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16385        }
16386
16387        Canvas canvas;
16388        if (attachInfo != null) {
16389            canvas = attachInfo.mCanvas;
16390            if (canvas == null) {
16391                canvas = new Canvas();
16392            }
16393            canvas.setBitmap(bitmap);
16394            // Temporarily clobber the cached Canvas in case one of our children
16395            // is also using a drawing cache. Without this, the children would
16396            // steal the canvas by attaching their own bitmap to it and bad, bad
16397            // things would happen (invisible views, corrupted drawings, etc.)
16398            attachInfo.mCanvas = null;
16399        } else {
16400            // This case should hopefully never or seldom happen
16401            canvas = new Canvas(bitmap);
16402        }
16403
16404        if ((backgroundColor & 0xff000000) != 0) {
16405            bitmap.eraseColor(backgroundColor);
16406        }
16407
16408        computeScroll();
16409        final int restoreCount = canvas.save();
16410        canvas.scale(scale, scale);
16411        canvas.translate(-mScrollX, -mScrollY);
16412
16413        // Temporarily remove the dirty mask
16414        int flags = mPrivateFlags;
16415        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16416
16417        // Fast path for layouts with no backgrounds
16418        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16419            dispatchDraw(canvas);
16420            if (mOverlay != null && !mOverlay.isEmpty()) {
16421                mOverlay.getOverlayView().draw(canvas);
16422            }
16423        } else {
16424            draw(canvas);
16425        }
16426
16427        mPrivateFlags = flags;
16428
16429        canvas.restoreToCount(restoreCount);
16430        canvas.setBitmap(null);
16431
16432        if (attachInfo != null) {
16433            // Restore the cached Canvas for our siblings
16434            attachInfo.mCanvas = canvas;
16435        }
16436
16437        return bitmap;
16438    }
16439
16440    /**
16441     * Indicates whether this View is currently in edit mode. A View is usually
16442     * in edit mode when displayed within a developer tool. For instance, if
16443     * this View is being drawn by a visual user interface builder, this method
16444     * should return true.
16445     *
16446     * Subclasses should check the return value of this method to provide
16447     * different behaviors if their normal behavior might interfere with the
16448     * host environment. For instance: the class spawns a thread in its
16449     * constructor, the drawing code relies on device-specific features, etc.
16450     *
16451     * This method is usually checked in the drawing code of custom widgets.
16452     *
16453     * @return True if this View is in edit mode, false otherwise.
16454     */
16455    public boolean isInEditMode() {
16456        return false;
16457    }
16458
16459    /**
16460     * If the View draws content inside its padding and enables fading edges,
16461     * it needs to support padding offsets. Padding offsets are added to the
16462     * fading edges to extend the length of the fade so that it covers pixels
16463     * drawn inside the padding.
16464     *
16465     * Subclasses of this class should override this method if they need
16466     * to draw content inside the padding.
16467     *
16468     * @return True if padding offset must be applied, false otherwise.
16469     *
16470     * @see #getLeftPaddingOffset()
16471     * @see #getRightPaddingOffset()
16472     * @see #getTopPaddingOffset()
16473     * @see #getBottomPaddingOffset()
16474     *
16475     * @since CURRENT
16476     */
16477    protected boolean isPaddingOffsetRequired() {
16478        return false;
16479    }
16480
16481    /**
16482     * Amount by which to extend the left fading region. Called only when
16483     * {@link #isPaddingOffsetRequired()} returns true.
16484     *
16485     * @return The left padding offset in pixels.
16486     *
16487     * @see #isPaddingOffsetRequired()
16488     *
16489     * @since CURRENT
16490     */
16491    protected int getLeftPaddingOffset() {
16492        return 0;
16493    }
16494
16495    /**
16496     * Amount by which to extend the right fading region. Called only when
16497     * {@link #isPaddingOffsetRequired()} returns true.
16498     *
16499     * @return The right padding offset in pixels.
16500     *
16501     * @see #isPaddingOffsetRequired()
16502     *
16503     * @since CURRENT
16504     */
16505    protected int getRightPaddingOffset() {
16506        return 0;
16507    }
16508
16509    /**
16510     * Amount by which to extend the top fading region. Called only when
16511     * {@link #isPaddingOffsetRequired()} returns true.
16512     *
16513     * @return The top padding offset in pixels.
16514     *
16515     * @see #isPaddingOffsetRequired()
16516     *
16517     * @since CURRENT
16518     */
16519    protected int getTopPaddingOffset() {
16520        return 0;
16521    }
16522
16523    /**
16524     * Amount by which to extend the bottom fading region. Called only when
16525     * {@link #isPaddingOffsetRequired()} returns true.
16526     *
16527     * @return The bottom padding offset in pixels.
16528     *
16529     * @see #isPaddingOffsetRequired()
16530     *
16531     * @since CURRENT
16532     */
16533    protected int getBottomPaddingOffset() {
16534        return 0;
16535    }
16536
16537    /**
16538     * @hide
16539     * @param offsetRequired
16540     */
16541    protected int getFadeTop(boolean offsetRequired) {
16542        int top = mPaddingTop;
16543        if (offsetRequired) top += getTopPaddingOffset();
16544        return top;
16545    }
16546
16547    /**
16548     * @hide
16549     * @param offsetRequired
16550     */
16551    protected int getFadeHeight(boolean offsetRequired) {
16552        int padding = mPaddingTop;
16553        if (offsetRequired) padding += getTopPaddingOffset();
16554        return mBottom - mTop - mPaddingBottom - padding;
16555    }
16556
16557    /**
16558     * <p>Indicates whether this view is attached to a hardware accelerated
16559     * window or not.</p>
16560     *
16561     * <p>Even if this method returns true, it does not mean that every call
16562     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
16563     * accelerated {@link android.graphics.Canvas}. For instance, if this view
16564     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
16565     * window is hardware accelerated,
16566     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
16567     * return false, and this method will return true.</p>
16568     *
16569     * @return True if the view is attached to a window and the window is
16570     *         hardware accelerated; false in any other case.
16571     */
16572    @ViewDebug.ExportedProperty(category = "drawing")
16573    public boolean isHardwareAccelerated() {
16574        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
16575    }
16576
16577    /**
16578     * Sets a rectangular area on this view to which the view will be clipped
16579     * when it is drawn. Setting the value to null will remove the clip bounds
16580     * and the view will draw normally, using its full bounds.
16581     *
16582     * @param clipBounds The rectangular area, in the local coordinates of
16583     * this view, to which future drawing operations will be clipped.
16584     */
16585    public void setClipBounds(Rect clipBounds) {
16586        if (clipBounds == mClipBounds
16587                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
16588            return;
16589        }
16590        if (clipBounds != null) {
16591            if (mClipBounds == null) {
16592                mClipBounds = new Rect(clipBounds);
16593            } else {
16594                mClipBounds.set(clipBounds);
16595            }
16596        } else {
16597            mClipBounds = null;
16598        }
16599        mRenderNode.setClipBounds(mClipBounds);
16600        invalidateViewProperty(false, false);
16601    }
16602
16603    /**
16604     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
16605     *
16606     * @return A copy of the current clip bounds if clip bounds are set,
16607     * otherwise null.
16608     */
16609    public Rect getClipBounds() {
16610        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
16611    }
16612
16613
16614    /**
16615     * Populates an output rectangle with the clip bounds of the view,
16616     * returning {@code true} if successful or {@code false} if the view's
16617     * clip bounds are {@code null}.
16618     *
16619     * @param outRect rectangle in which to place the clip bounds of the view
16620     * @return {@code true} if successful or {@code false} if the view's
16621     *         clip bounds are {@code null}
16622     */
16623    public boolean getClipBounds(Rect outRect) {
16624        if (mClipBounds != null) {
16625            outRect.set(mClipBounds);
16626            return true;
16627        }
16628        return false;
16629    }
16630
16631    /**
16632     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
16633     * case of an active Animation being run on the view.
16634     */
16635    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
16636            Animation a, boolean scalingRequired) {
16637        Transformation invalidationTransform;
16638        final int flags = parent.mGroupFlags;
16639        final boolean initialized = a.isInitialized();
16640        if (!initialized) {
16641            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
16642            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
16643            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
16644            onAnimationStart();
16645        }
16646
16647        final Transformation t = parent.getChildTransformation();
16648        boolean more = a.getTransformation(drawingTime, t, 1f);
16649        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
16650            if (parent.mInvalidationTransformation == null) {
16651                parent.mInvalidationTransformation = new Transformation();
16652            }
16653            invalidationTransform = parent.mInvalidationTransformation;
16654            a.getTransformation(drawingTime, invalidationTransform, 1f);
16655        } else {
16656            invalidationTransform = t;
16657        }
16658
16659        if (more) {
16660            if (!a.willChangeBounds()) {
16661                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
16662                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
16663                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
16664                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
16665                    // The child need to draw an animation, potentially offscreen, so
16666                    // make sure we do not cancel invalidate requests
16667                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16668                    parent.invalidate(mLeft, mTop, mRight, mBottom);
16669                }
16670            } else {
16671                if (parent.mInvalidateRegion == null) {
16672                    parent.mInvalidateRegion = new RectF();
16673                }
16674                final RectF region = parent.mInvalidateRegion;
16675                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
16676                        invalidationTransform);
16677
16678                // The child need to draw an animation, potentially offscreen, so
16679                // make sure we do not cancel invalidate requests
16680                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16681
16682                final int left = mLeft + (int) region.left;
16683                final int top = mTop + (int) region.top;
16684                parent.invalidate(left, top, left + (int) (region.width() + .5f),
16685                        top + (int) (region.height() + .5f));
16686            }
16687        }
16688        return more;
16689    }
16690
16691    /**
16692     * This method is called by getDisplayList() when a display list is recorded for a View.
16693     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
16694     */
16695    void setDisplayListProperties(RenderNode renderNode) {
16696        if (renderNode != null) {
16697            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
16698            renderNode.setClipToBounds(mParent instanceof ViewGroup
16699                    && ((ViewGroup) mParent).getClipChildren());
16700
16701            float alpha = 1;
16702            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
16703                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16704                ViewGroup parentVG = (ViewGroup) mParent;
16705                final Transformation t = parentVG.getChildTransformation();
16706                if (parentVG.getChildStaticTransformation(this, t)) {
16707                    final int transformType = t.getTransformationType();
16708                    if (transformType != Transformation.TYPE_IDENTITY) {
16709                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
16710                            alpha = t.getAlpha();
16711                        }
16712                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
16713                            renderNode.setStaticMatrix(t.getMatrix());
16714                        }
16715                    }
16716                }
16717            }
16718            if (mTransformationInfo != null) {
16719                alpha *= getFinalAlpha();
16720                if (alpha < 1) {
16721                    final int multipliedAlpha = (int) (255 * alpha);
16722                    if (onSetAlpha(multipliedAlpha)) {
16723                        alpha = 1;
16724                    }
16725                }
16726                renderNode.setAlpha(alpha);
16727            } else if (alpha < 1) {
16728                renderNode.setAlpha(alpha);
16729            }
16730        }
16731    }
16732
16733    /**
16734     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
16735     *
16736     * This is where the View specializes rendering behavior based on layer type,
16737     * and hardware acceleration.
16738     */
16739    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
16740        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
16741        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
16742         *
16743         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
16744         * HW accelerated, it can't handle drawing RenderNodes.
16745         */
16746        boolean drawingWithRenderNode = mAttachInfo != null
16747                && mAttachInfo.mHardwareAccelerated
16748                && hardwareAcceleratedCanvas;
16749
16750        boolean more = false;
16751        final boolean childHasIdentityMatrix = hasIdentityMatrix();
16752        final int parentFlags = parent.mGroupFlags;
16753
16754        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
16755            parent.getChildTransformation().clear();
16756            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16757        }
16758
16759        Transformation transformToApply = null;
16760        boolean concatMatrix = false;
16761        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
16762        final Animation a = getAnimation();
16763        if (a != null) {
16764            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
16765            concatMatrix = a.willChangeTransformationMatrix();
16766            if (concatMatrix) {
16767                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16768            }
16769            transformToApply = parent.getChildTransformation();
16770        } else {
16771            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
16772                // No longer animating: clear out old animation matrix
16773                mRenderNode.setAnimationMatrix(null);
16774                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16775            }
16776            if (!drawingWithRenderNode
16777                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16778                final Transformation t = parent.getChildTransformation();
16779                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
16780                if (hasTransform) {
16781                    final int transformType = t.getTransformationType();
16782                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
16783                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
16784                }
16785            }
16786        }
16787
16788        concatMatrix |= !childHasIdentityMatrix;
16789
16790        // Sets the flag as early as possible to allow draw() implementations
16791        // to call invalidate() successfully when doing animations
16792        mPrivateFlags |= PFLAG_DRAWN;
16793
16794        if (!concatMatrix &&
16795                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
16796                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
16797                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
16798                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
16799            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
16800            return more;
16801        }
16802        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
16803
16804        if (hardwareAcceleratedCanvas) {
16805            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
16806            // retain the flag's value temporarily in the mRecreateDisplayList flag
16807            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
16808            mPrivateFlags &= ~PFLAG_INVALIDATED;
16809        }
16810
16811        RenderNode renderNode = null;
16812        Bitmap cache = null;
16813        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
16814        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
16815             if (layerType != LAYER_TYPE_NONE) {
16816                 // If not drawing with RenderNode, treat HW layers as SW
16817                 layerType = LAYER_TYPE_SOFTWARE;
16818                 buildDrawingCache(true);
16819            }
16820            cache = getDrawingCache(true);
16821        }
16822
16823        if (drawingWithRenderNode) {
16824            // Delay getting the display list until animation-driven alpha values are
16825            // set up and possibly passed on to the view
16826            renderNode = updateDisplayListIfDirty();
16827            if (!renderNode.isValid()) {
16828                // Uncommon, but possible. If a view is removed from the hierarchy during the call
16829                // to getDisplayList(), the display list will be marked invalid and we should not
16830                // try to use it again.
16831                renderNode = null;
16832                drawingWithRenderNode = false;
16833            }
16834        }
16835
16836        int sx = 0;
16837        int sy = 0;
16838        if (!drawingWithRenderNode) {
16839            computeScroll();
16840            sx = mScrollX;
16841            sy = mScrollY;
16842        }
16843
16844        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
16845        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
16846
16847        int restoreTo = -1;
16848        if (!drawingWithRenderNode || transformToApply != null) {
16849            restoreTo = canvas.save();
16850        }
16851        if (offsetForScroll) {
16852            canvas.translate(mLeft - sx, mTop - sy);
16853        } else {
16854            if (!drawingWithRenderNode) {
16855                canvas.translate(mLeft, mTop);
16856            }
16857            if (scalingRequired) {
16858                if (drawingWithRenderNode) {
16859                    // TODO: Might not need this if we put everything inside the DL
16860                    restoreTo = canvas.save();
16861                }
16862                // mAttachInfo cannot be null, otherwise scalingRequired == false
16863                final float scale = 1.0f / mAttachInfo.mApplicationScale;
16864                canvas.scale(scale, scale);
16865            }
16866        }
16867
16868        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
16869        if (transformToApply != null
16870                || alpha < 1
16871                || !hasIdentityMatrix()
16872                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16873            if (transformToApply != null || !childHasIdentityMatrix) {
16874                int transX = 0;
16875                int transY = 0;
16876
16877                if (offsetForScroll) {
16878                    transX = -sx;
16879                    transY = -sy;
16880                }
16881
16882                if (transformToApply != null) {
16883                    if (concatMatrix) {
16884                        if (drawingWithRenderNode) {
16885                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
16886                        } else {
16887                            // Undo the scroll translation, apply the transformation matrix,
16888                            // then redo the scroll translate to get the correct result.
16889                            canvas.translate(-transX, -transY);
16890                            canvas.concat(transformToApply.getMatrix());
16891                            canvas.translate(transX, transY);
16892                        }
16893                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16894                    }
16895
16896                    float transformAlpha = transformToApply.getAlpha();
16897                    if (transformAlpha < 1) {
16898                        alpha *= transformAlpha;
16899                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16900                    }
16901                }
16902
16903                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
16904                    canvas.translate(-transX, -transY);
16905                    canvas.concat(getMatrix());
16906                    canvas.translate(transX, transY);
16907                }
16908            }
16909
16910            // Deal with alpha if it is or used to be <1
16911            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16912                if (alpha < 1) {
16913                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16914                } else {
16915                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16916                }
16917                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16918                if (!drawingWithDrawingCache) {
16919                    final int multipliedAlpha = (int) (255 * alpha);
16920                    if (!onSetAlpha(multipliedAlpha)) {
16921                        if (drawingWithRenderNode) {
16922                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
16923                        } else if (layerType == LAYER_TYPE_NONE) {
16924                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
16925                                    multipliedAlpha);
16926                        }
16927                    } else {
16928                        // Alpha is handled by the child directly, clobber the layer's alpha
16929                        mPrivateFlags |= PFLAG_ALPHA_SET;
16930                    }
16931                }
16932            }
16933        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16934            onSetAlpha(255);
16935            mPrivateFlags &= ~PFLAG_ALPHA_SET;
16936        }
16937
16938        if (!drawingWithRenderNode) {
16939            // apply clips directly, since RenderNode won't do it for this draw
16940            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
16941                if (offsetForScroll) {
16942                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
16943                } else {
16944                    if (!scalingRequired || cache == null) {
16945                        canvas.clipRect(0, 0, getWidth(), getHeight());
16946                    } else {
16947                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
16948                    }
16949                }
16950            }
16951
16952            if (mClipBounds != null) {
16953                // clip bounds ignore scroll
16954                canvas.clipRect(mClipBounds);
16955            }
16956        }
16957
16958        if (!drawingWithDrawingCache) {
16959            if (drawingWithRenderNode) {
16960                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16961                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
16962            } else {
16963                // Fast path for layouts with no backgrounds
16964                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16965                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16966                    dispatchDraw(canvas);
16967                } else {
16968                    draw(canvas);
16969                }
16970            }
16971        } else if (cache != null) {
16972            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16973            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
16974                // no layer paint, use temporary paint to draw bitmap
16975                Paint cachePaint = parent.mCachePaint;
16976                if (cachePaint == null) {
16977                    cachePaint = new Paint();
16978                    cachePaint.setDither(false);
16979                    parent.mCachePaint = cachePaint;
16980                }
16981                cachePaint.setAlpha((int) (alpha * 255));
16982                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
16983            } else {
16984                // use layer paint to draw the bitmap, merging the two alphas, but also restore
16985                int layerPaintAlpha = mLayerPaint.getAlpha();
16986                if (alpha < 1) {
16987                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
16988                }
16989                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
16990                if (alpha < 1) {
16991                    mLayerPaint.setAlpha(layerPaintAlpha);
16992                }
16993            }
16994        }
16995
16996        if (restoreTo >= 0) {
16997            canvas.restoreToCount(restoreTo);
16998        }
16999
17000        if (a != null && !more) {
17001            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17002                onSetAlpha(255);
17003            }
17004            parent.finishAnimatingView(this, a);
17005        }
17006
17007        if (more && hardwareAcceleratedCanvas) {
17008            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17009                // alpha animations should cause the child to recreate its display list
17010                invalidate(true);
17011            }
17012        }
17013
17014        mRecreateDisplayList = false;
17015
17016        return more;
17017    }
17018
17019    /**
17020     * Manually render this view (and all of its children) to the given Canvas.
17021     * The view must have already done a full layout before this function is
17022     * called.  When implementing a view, implement
17023     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17024     * If you do need to override this method, call the superclass version.
17025     *
17026     * @param canvas The Canvas to which the View is rendered.
17027     */
17028    @CallSuper
17029    public void draw(Canvas canvas) {
17030        final int privateFlags = mPrivateFlags;
17031        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17032                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17033        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17034
17035        /*
17036         * Draw traversal performs several drawing steps which must be executed
17037         * in the appropriate order:
17038         *
17039         *      1. Draw the background
17040         *      2. If necessary, save the canvas' layers to prepare for fading
17041         *      3. Draw view's content
17042         *      4. Draw children
17043         *      5. If necessary, draw the fading edges and restore layers
17044         *      6. Draw decorations (scrollbars for instance)
17045         */
17046
17047        // Step 1, draw the background, if needed
17048        int saveCount;
17049
17050        if (!dirtyOpaque) {
17051            drawBackground(canvas);
17052        }
17053
17054        // skip step 2 & 5 if possible (common case)
17055        final int viewFlags = mViewFlags;
17056        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17057        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17058        if (!verticalEdges && !horizontalEdges) {
17059            // Step 3, draw the content
17060            if (!dirtyOpaque) onDraw(canvas);
17061
17062            // Step 4, draw the children
17063            dispatchDraw(canvas);
17064
17065            // Overlay is part of the content and draws beneath Foreground
17066            if (mOverlay != null && !mOverlay.isEmpty()) {
17067                mOverlay.getOverlayView().dispatchDraw(canvas);
17068            }
17069
17070            // Step 6, draw decorations (foreground, scrollbars)
17071            onDrawForeground(canvas);
17072
17073            // we're done...
17074            return;
17075        }
17076
17077        /*
17078         * Here we do the full fledged routine...
17079         * (this is an uncommon case where speed matters less,
17080         * this is why we repeat some of the tests that have been
17081         * done above)
17082         */
17083
17084        boolean drawTop = false;
17085        boolean drawBottom = false;
17086        boolean drawLeft = false;
17087        boolean drawRight = false;
17088
17089        float topFadeStrength = 0.0f;
17090        float bottomFadeStrength = 0.0f;
17091        float leftFadeStrength = 0.0f;
17092        float rightFadeStrength = 0.0f;
17093
17094        // Step 2, save the canvas' layers
17095        int paddingLeft = mPaddingLeft;
17096
17097        final boolean offsetRequired = isPaddingOffsetRequired();
17098        if (offsetRequired) {
17099            paddingLeft += getLeftPaddingOffset();
17100        }
17101
17102        int left = mScrollX + paddingLeft;
17103        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17104        int top = mScrollY + getFadeTop(offsetRequired);
17105        int bottom = top + getFadeHeight(offsetRequired);
17106
17107        if (offsetRequired) {
17108            right += getRightPaddingOffset();
17109            bottom += getBottomPaddingOffset();
17110        }
17111
17112        final ScrollabilityCache scrollabilityCache = mScrollCache;
17113        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17114        int length = (int) fadeHeight;
17115
17116        // clip the fade length if top and bottom fades overlap
17117        // overlapping fades produce odd-looking artifacts
17118        if (verticalEdges && (top + length > bottom - length)) {
17119            length = (bottom - top) / 2;
17120        }
17121
17122        // also clip horizontal fades if necessary
17123        if (horizontalEdges && (left + length > right - length)) {
17124            length = (right - left) / 2;
17125        }
17126
17127        if (verticalEdges) {
17128            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17129            drawTop = topFadeStrength * fadeHeight > 1.0f;
17130            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17131            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17132        }
17133
17134        if (horizontalEdges) {
17135            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17136            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17137            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17138            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17139        }
17140
17141        saveCount = canvas.getSaveCount();
17142
17143        int solidColor = getSolidColor();
17144        if (solidColor == 0) {
17145            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17146
17147            if (drawTop) {
17148                canvas.saveLayer(left, top, right, top + length, null, flags);
17149            }
17150
17151            if (drawBottom) {
17152                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17153            }
17154
17155            if (drawLeft) {
17156                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17157            }
17158
17159            if (drawRight) {
17160                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17161            }
17162        } else {
17163            scrollabilityCache.setFadeColor(solidColor);
17164        }
17165
17166        // Step 3, draw the content
17167        if (!dirtyOpaque) onDraw(canvas);
17168
17169        // Step 4, draw the children
17170        dispatchDraw(canvas);
17171
17172        // Step 5, draw the fade effect and restore layers
17173        final Paint p = scrollabilityCache.paint;
17174        final Matrix matrix = scrollabilityCache.matrix;
17175        final Shader fade = scrollabilityCache.shader;
17176
17177        if (drawTop) {
17178            matrix.setScale(1, fadeHeight * topFadeStrength);
17179            matrix.postTranslate(left, top);
17180            fade.setLocalMatrix(matrix);
17181            p.setShader(fade);
17182            canvas.drawRect(left, top, right, top + length, p);
17183        }
17184
17185        if (drawBottom) {
17186            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17187            matrix.postRotate(180);
17188            matrix.postTranslate(left, bottom);
17189            fade.setLocalMatrix(matrix);
17190            p.setShader(fade);
17191            canvas.drawRect(left, bottom - length, right, bottom, p);
17192        }
17193
17194        if (drawLeft) {
17195            matrix.setScale(1, fadeHeight * leftFadeStrength);
17196            matrix.postRotate(-90);
17197            matrix.postTranslate(left, top);
17198            fade.setLocalMatrix(matrix);
17199            p.setShader(fade);
17200            canvas.drawRect(left, top, left + length, bottom, p);
17201        }
17202
17203        if (drawRight) {
17204            matrix.setScale(1, fadeHeight * rightFadeStrength);
17205            matrix.postRotate(90);
17206            matrix.postTranslate(right, top);
17207            fade.setLocalMatrix(matrix);
17208            p.setShader(fade);
17209            canvas.drawRect(right - length, top, right, bottom, p);
17210        }
17211
17212        canvas.restoreToCount(saveCount);
17213
17214        // Overlay is part of the content and draws beneath Foreground
17215        if (mOverlay != null && !mOverlay.isEmpty()) {
17216            mOverlay.getOverlayView().dispatchDraw(canvas);
17217        }
17218
17219        // Step 6, draw decorations (foreground, scrollbars)
17220        onDrawForeground(canvas);
17221    }
17222
17223    /**
17224     * Draws the background onto the specified canvas.
17225     *
17226     * @param canvas Canvas on which to draw the background
17227     */
17228    private void drawBackground(Canvas canvas) {
17229        final Drawable background = mBackground;
17230        if (background == null) {
17231            return;
17232        }
17233
17234        setBackgroundBounds();
17235
17236        // Attempt to use a display list if requested.
17237        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17238                && mAttachInfo.mHardwareRenderer != null) {
17239            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17240
17241            final RenderNode renderNode = mBackgroundRenderNode;
17242            if (renderNode != null && renderNode.isValid()) {
17243                setBackgroundRenderNodeProperties(renderNode);
17244                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17245                return;
17246            }
17247        }
17248
17249        final int scrollX = mScrollX;
17250        final int scrollY = mScrollY;
17251        if ((scrollX | scrollY) == 0) {
17252            background.draw(canvas);
17253        } else {
17254            canvas.translate(scrollX, scrollY);
17255            background.draw(canvas);
17256            canvas.translate(-scrollX, -scrollY);
17257        }
17258    }
17259
17260    /**
17261     * Sets the correct background bounds and rebuilds the outline, if needed.
17262     * <p/>
17263     * This is called by LayoutLib.
17264     */
17265    void setBackgroundBounds() {
17266        if (mBackgroundSizeChanged && mBackground != null) {
17267            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17268            mBackgroundSizeChanged = false;
17269            rebuildOutline();
17270        }
17271    }
17272
17273    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17274        renderNode.setTranslationX(mScrollX);
17275        renderNode.setTranslationY(mScrollY);
17276    }
17277
17278    /**
17279     * Creates a new display list or updates the existing display list for the
17280     * specified Drawable.
17281     *
17282     * @param drawable Drawable for which to create a display list
17283     * @param renderNode Existing RenderNode, or {@code null}
17284     * @return A valid display list for the specified drawable
17285     */
17286    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17287        if (renderNode == null) {
17288            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17289        }
17290
17291        final Rect bounds = drawable.getBounds();
17292        final int width = bounds.width();
17293        final int height = bounds.height();
17294        final DisplayListCanvas canvas = renderNode.start(width, height);
17295
17296        // Reverse left/top translation done by drawable canvas, which will
17297        // instead be applied by rendernode's LTRB bounds below. This way, the
17298        // drawable's bounds match with its rendernode bounds and its content
17299        // will lie within those bounds in the rendernode tree.
17300        canvas.translate(-bounds.left, -bounds.top);
17301
17302        try {
17303            drawable.draw(canvas);
17304        } finally {
17305            renderNode.end(canvas);
17306        }
17307
17308        // Set up drawable properties that are view-independent.
17309        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17310        renderNode.setProjectBackwards(drawable.isProjected());
17311        renderNode.setProjectionReceiver(true);
17312        renderNode.setClipToBounds(false);
17313        return renderNode;
17314    }
17315
17316    /**
17317     * Returns the overlay for this view, creating it if it does not yet exist.
17318     * Adding drawables to the overlay will cause them to be displayed whenever
17319     * the view itself is redrawn. Objects in the overlay should be actively
17320     * managed: remove them when they should not be displayed anymore. The
17321     * overlay will always have the same size as its host view.
17322     *
17323     * <p>Note: Overlays do not currently work correctly with {@link
17324     * SurfaceView} or {@link TextureView}; contents in overlays for these
17325     * types of views may not display correctly.</p>
17326     *
17327     * @return The ViewOverlay object for this view.
17328     * @see ViewOverlay
17329     */
17330    public ViewOverlay getOverlay() {
17331        if (mOverlay == null) {
17332            mOverlay = new ViewOverlay(mContext, this);
17333        }
17334        return mOverlay;
17335    }
17336
17337    /**
17338     * Override this if your view is known to always be drawn on top of a solid color background,
17339     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17340     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17341     * should be set to 0xFF.
17342     *
17343     * @see #setVerticalFadingEdgeEnabled(boolean)
17344     * @see #setHorizontalFadingEdgeEnabled(boolean)
17345     *
17346     * @return The known solid color background for this view, or 0 if the color may vary
17347     */
17348    @ViewDebug.ExportedProperty(category = "drawing")
17349    @ColorInt
17350    public int getSolidColor() {
17351        return 0;
17352    }
17353
17354    /**
17355     * Build a human readable string representation of the specified view flags.
17356     *
17357     * @param flags the view flags to convert to a string
17358     * @return a String representing the supplied flags
17359     */
17360    private static String printFlags(int flags) {
17361        String output = "";
17362        int numFlags = 0;
17363        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17364            output += "TAKES_FOCUS";
17365            numFlags++;
17366        }
17367
17368        switch (flags & VISIBILITY_MASK) {
17369        case INVISIBLE:
17370            if (numFlags > 0) {
17371                output += " ";
17372            }
17373            output += "INVISIBLE";
17374            // USELESS HERE numFlags++;
17375            break;
17376        case GONE:
17377            if (numFlags > 0) {
17378                output += " ";
17379            }
17380            output += "GONE";
17381            // USELESS HERE numFlags++;
17382            break;
17383        default:
17384            break;
17385        }
17386        return output;
17387    }
17388
17389    /**
17390     * Build a human readable string representation of the specified private
17391     * view flags.
17392     *
17393     * @param privateFlags the private view flags to convert to a string
17394     * @return a String representing the supplied flags
17395     */
17396    private static String printPrivateFlags(int privateFlags) {
17397        String output = "";
17398        int numFlags = 0;
17399
17400        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17401            output += "WANTS_FOCUS";
17402            numFlags++;
17403        }
17404
17405        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17406            if (numFlags > 0) {
17407                output += " ";
17408            }
17409            output += "FOCUSED";
17410            numFlags++;
17411        }
17412
17413        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17414            if (numFlags > 0) {
17415                output += " ";
17416            }
17417            output += "SELECTED";
17418            numFlags++;
17419        }
17420
17421        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17422            if (numFlags > 0) {
17423                output += " ";
17424            }
17425            output += "IS_ROOT_NAMESPACE";
17426            numFlags++;
17427        }
17428
17429        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17430            if (numFlags > 0) {
17431                output += " ";
17432            }
17433            output += "HAS_BOUNDS";
17434            numFlags++;
17435        }
17436
17437        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17438            if (numFlags > 0) {
17439                output += " ";
17440            }
17441            output += "DRAWN";
17442            // USELESS HERE numFlags++;
17443        }
17444        return output;
17445    }
17446
17447    /**
17448     * <p>Indicates whether or not this view's layout will be requested during
17449     * the next hierarchy layout pass.</p>
17450     *
17451     * @return true if the layout will be forced during next layout pass
17452     */
17453    public boolean isLayoutRequested() {
17454        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17455    }
17456
17457    /**
17458     * Return true if o is a ViewGroup that is laying out using optical bounds.
17459     * @hide
17460     */
17461    public static boolean isLayoutModeOptical(Object o) {
17462        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
17463    }
17464
17465    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
17466        Insets parentInsets = mParent instanceof View ?
17467                ((View) mParent).getOpticalInsets() : Insets.NONE;
17468        Insets childInsets = getOpticalInsets();
17469        return setFrame(
17470                left   + parentInsets.left - childInsets.left,
17471                top    + parentInsets.top  - childInsets.top,
17472                right  + parentInsets.left + childInsets.right,
17473                bottom + parentInsets.top  + childInsets.bottom);
17474    }
17475
17476    /**
17477     * Assign a size and position to a view and all of its
17478     * descendants
17479     *
17480     * <p>This is the second phase of the layout mechanism.
17481     * (The first is measuring). In this phase, each parent calls
17482     * layout on all of its children to position them.
17483     * This is typically done using the child measurements
17484     * that were stored in the measure pass().</p>
17485     *
17486     * <p>Derived classes should not override this method.
17487     * Derived classes with children should override
17488     * onLayout. In that method, they should
17489     * call layout on each of their children.</p>
17490     *
17491     * @param l Left position, relative to parent
17492     * @param t Top position, relative to parent
17493     * @param r Right position, relative to parent
17494     * @param b Bottom position, relative to parent
17495     */
17496    @SuppressWarnings({"unchecked"})
17497    public void layout(int l, int t, int r, int b) {
17498        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
17499            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
17500            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17501        }
17502
17503        int oldL = mLeft;
17504        int oldT = mTop;
17505        int oldB = mBottom;
17506        int oldR = mRight;
17507
17508        boolean changed = isLayoutModeOptical(mParent) ?
17509                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
17510
17511        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
17512            onLayout(changed, l, t, r, b);
17513            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
17514
17515            ListenerInfo li = mListenerInfo;
17516            if (li != null && li.mOnLayoutChangeListeners != null) {
17517                ArrayList<OnLayoutChangeListener> listenersCopy =
17518                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
17519                int numListeners = listenersCopy.size();
17520                for (int i = 0; i < numListeners; ++i) {
17521                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
17522                }
17523            }
17524        }
17525
17526        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
17527        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
17528    }
17529
17530    /**
17531     * Called from layout when this view should
17532     * assign a size and position to each of its children.
17533     *
17534     * Derived classes with children should override
17535     * this method and call layout on each of
17536     * their children.
17537     * @param changed This is a new size or position for this view
17538     * @param left Left position, relative to parent
17539     * @param top Top position, relative to parent
17540     * @param right Right position, relative to parent
17541     * @param bottom Bottom position, relative to parent
17542     */
17543    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
17544    }
17545
17546    /**
17547     * Assign a size and position to this view.
17548     *
17549     * This is called from layout.
17550     *
17551     * @param left Left position, relative to parent
17552     * @param top Top position, relative to parent
17553     * @param right Right position, relative to parent
17554     * @param bottom Bottom position, relative to parent
17555     * @return true if the new size and position are different than the
17556     *         previous ones
17557     * {@hide}
17558     */
17559    protected boolean setFrame(int left, int top, int right, int bottom) {
17560        boolean changed = false;
17561
17562        if (DBG) {
17563            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
17564                    + right + "," + bottom + ")");
17565        }
17566
17567        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
17568            changed = true;
17569
17570            // Remember our drawn bit
17571            int drawn = mPrivateFlags & PFLAG_DRAWN;
17572
17573            int oldWidth = mRight - mLeft;
17574            int oldHeight = mBottom - mTop;
17575            int newWidth = right - left;
17576            int newHeight = bottom - top;
17577            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
17578
17579            // Invalidate our old position
17580            invalidate(sizeChanged);
17581
17582            mLeft = left;
17583            mTop = top;
17584            mRight = right;
17585            mBottom = bottom;
17586            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
17587
17588            mPrivateFlags |= PFLAG_HAS_BOUNDS;
17589
17590
17591            if (sizeChanged) {
17592                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
17593            }
17594
17595            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
17596                // If we are visible, force the DRAWN bit to on so that
17597                // this invalidate will go through (at least to our parent).
17598                // This is because someone may have invalidated this view
17599                // before this call to setFrame came in, thereby clearing
17600                // the DRAWN bit.
17601                mPrivateFlags |= PFLAG_DRAWN;
17602                invalidate(sizeChanged);
17603                // parent display list may need to be recreated based on a change in the bounds
17604                // of any child
17605                invalidateParentCaches();
17606            }
17607
17608            // Reset drawn bit to original value (invalidate turns it off)
17609            mPrivateFlags |= drawn;
17610
17611            mBackgroundSizeChanged = true;
17612            if (mForegroundInfo != null) {
17613                mForegroundInfo.mBoundsChanged = true;
17614            }
17615
17616            notifySubtreeAccessibilityStateChangedIfNeeded();
17617        }
17618        return changed;
17619    }
17620
17621    /**
17622     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
17623     * @hide
17624     */
17625    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
17626        setFrame(left, top, right, bottom);
17627    }
17628
17629    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
17630        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
17631        if (mOverlay != null) {
17632            mOverlay.getOverlayView().setRight(newWidth);
17633            mOverlay.getOverlayView().setBottom(newHeight);
17634        }
17635        rebuildOutline();
17636    }
17637
17638    /**
17639     * Finalize inflating a view from XML.  This is called as the last phase
17640     * of inflation, after all child views have been added.
17641     *
17642     * <p>Even if the subclass overrides onFinishInflate, they should always be
17643     * sure to call the super method, so that we get called.
17644     */
17645    @CallSuper
17646    protected void onFinishInflate() {
17647    }
17648
17649    /**
17650     * Returns the resources associated with this view.
17651     *
17652     * @return Resources object.
17653     */
17654    public Resources getResources() {
17655        return mResources;
17656    }
17657
17658    /**
17659     * Invalidates the specified Drawable.
17660     *
17661     * @param drawable the drawable to invalidate
17662     */
17663    @Override
17664    public void invalidateDrawable(@NonNull Drawable drawable) {
17665        if (verifyDrawable(drawable)) {
17666            final Rect dirty = drawable.getDirtyBounds();
17667            final int scrollX = mScrollX;
17668            final int scrollY = mScrollY;
17669
17670            invalidate(dirty.left + scrollX, dirty.top + scrollY,
17671                    dirty.right + scrollX, dirty.bottom + scrollY);
17672            rebuildOutline();
17673        }
17674    }
17675
17676    /**
17677     * Schedules an action on a drawable to occur at a specified time.
17678     *
17679     * @param who the recipient of the action
17680     * @param what the action to run on the drawable
17681     * @param when the time at which the action must occur. Uses the
17682     *        {@link SystemClock#uptimeMillis} timebase.
17683     */
17684    @Override
17685    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
17686        if (verifyDrawable(who) && what != null) {
17687            final long delay = when - SystemClock.uptimeMillis();
17688            if (mAttachInfo != null) {
17689                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
17690                        Choreographer.CALLBACK_ANIMATION, what, who,
17691                        Choreographer.subtractFrameDelay(delay));
17692            } else {
17693                // Postpone the runnable until we know
17694                // on which thread it needs to run.
17695                getRunQueue().postDelayed(what, delay);
17696            }
17697        }
17698    }
17699
17700    /**
17701     * Cancels a scheduled action on a drawable.
17702     *
17703     * @param who the recipient of the action
17704     * @param what the action to cancel
17705     */
17706    @Override
17707    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
17708        if (verifyDrawable(who) && what != null) {
17709            if (mAttachInfo != null) {
17710                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17711                        Choreographer.CALLBACK_ANIMATION, what, who);
17712            }
17713            getRunQueue().removeCallbacks(what);
17714        }
17715    }
17716
17717    /**
17718     * Unschedule any events associated with the given Drawable.  This can be
17719     * used when selecting a new Drawable into a view, so that the previous
17720     * one is completely unscheduled.
17721     *
17722     * @param who The Drawable to unschedule.
17723     *
17724     * @see #drawableStateChanged
17725     */
17726    public void unscheduleDrawable(Drawable who) {
17727        if (mAttachInfo != null && who != null) {
17728            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17729                    Choreographer.CALLBACK_ANIMATION, null, who);
17730        }
17731    }
17732
17733    /**
17734     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
17735     * that the View directionality can and will be resolved before its Drawables.
17736     *
17737     * Will call {@link View#onResolveDrawables} when resolution is done.
17738     *
17739     * @hide
17740     */
17741    protected void resolveDrawables() {
17742        // Drawables resolution may need to happen before resolving the layout direction (which is
17743        // done only during the measure() call).
17744        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
17745        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
17746        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
17747        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
17748        // direction to be resolved as its resolved value will be the same as its raw value.
17749        if (!isLayoutDirectionResolved() &&
17750                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
17751            return;
17752        }
17753
17754        final int layoutDirection = isLayoutDirectionResolved() ?
17755                getLayoutDirection() : getRawLayoutDirection();
17756
17757        if (mBackground != null) {
17758            mBackground.setLayoutDirection(layoutDirection);
17759        }
17760        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17761            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
17762        }
17763        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
17764        onResolveDrawables(layoutDirection);
17765    }
17766
17767    boolean areDrawablesResolved() {
17768        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
17769    }
17770
17771    /**
17772     * Called when layout direction has been resolved.
17773     *
17774     * The default implementation does nothing.
17775     *
17776     * @param layoutDirection The resolved layout direction.
17777     *
17778     * @see #LAYOUT_DIRECTION_LTR
17779     * @see #LAYOUT_DIRECTION_RTL
17780     *
17781     * @hide
17782     */
17783    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
17784    }
17785
17786    /**
17787     * @hide
17788     */
17789    protected void resetResolvedDrawables() {
17790        resetResolvedDrawablesInternal();
17791    }
17792
17793    void resetResolvedDrawablesInternal() {
17794        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
17795    }
17796
17797    /**
17798     * If your view subclass is displaying its own Drawable objects, it should
17799     * override this function and return true for any Drawable it is
17800     * displaying.  This allows animations for those drawables to be
17801     * scheduled.
17802     *
17803     * <p>Be sure to call through to the super class when overriding this
17804     * function.
17805     *
17806     * @param who The Drawable to verify.  Return true if it is one you are
17807     *            displaying, else return the result of calling through to the
17808     *            super class.
17809     *
17810     * @return boolean If true than the Drawable is being displayed in the
17811     *         view; else false and it is not allowed to animate.
17812     *
17813     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
17814     * @see #drawableStateChanged()
17815     */
17816    @CallSuper
17817    protected boolean verifyDrawable(@NonNull Drawable who) {
17818        // Avoid verifying the scroll bar drawable so that we don't end up in
17819        // an invalidation loop. This effectively prevents the scroll bar
17820        // drawable from triggering invalidations and scheduling runnables.
17821        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
17822    }
17823
17824    /**
17825     * This function is called whenever the state of the view changes in such
17826     * a way that it impacts the state of drawables being shown.
17827     * <p>
17828     * If the View has a StateListAnimator, it will also be called to run necessary state
17829     * change animations.
17830     * <p>
17831     * Be sure to call through to the superclass when overriding this function.
17832     *
17833     * @see Drawable#setState(int[])
17834     */
17835    @CallSuper
17836    protected void drawableStateChanged() {
17837        final int[] state = getDrawableState();
17838        boolean changed = false;
17839
17840        final Drawable bg = mBackground;
17841        if (bg != null && bg.isStateful()) {
17842            changed |= bg.setState(state);
17843        }
17844
17845        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17846        if (fg != null && fg.isStateful()) {
17847            changed |= fg.setState(state);
17848        }
17849
17850        if (mScrollCache != null) {
17851            final Drawable scrollBar = mScrollCache.scrollBar;
17852            if (scrollBar != null && scrollBar.isStateful()) {
17853                changed |= scrollBar.setState(state)
17854                        && mScrollCache.state != ScrollabilityCache.OFF;
17855            }
17856        }
17857
17858        if (mStateListAnimator != null) {
17859            mStateListAnimator.setState(state);
17860        }
17861
17862        if (changed) {
17863            invalidate();
17864        }
17865    }
17866
17867    /**
17868     * This function is called whenever the view hotspot changes and needs to
17869     * be propagated to drawables or child views managed by the view.
17870     * <p>
17871     * Dispatching to child views is handled by
17872     * {@link #dispatchDrawableHotspotChanged(float, float)}.
17873     * <p>
17874     * Be sure to call through to the superclass when overriding this function.
17875     *
17876     * @param x hotspot x coordinate
17877     * @param y hotspot y coordinate
17878     */
17879    @CallSuper
17880    public void drawableHotspotChanged(float x, float y) {
17881        if (mBackground != null) {
17882            mBackground.setHotspot(x, y);
17883        }
17884        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17885            mForegroundInfo.mDrawable.setHotspot(x, y);
17886        }
17887
17888        dispatchDrawableHotspotChanged(x, y);
17889    }
17890
17891    /**
17892     * Dispatches drawableHotspotChanged to all of this View's children.
17893     *
17894     * @param x hotspot x coordinate
17895     * @param y hotspot y coordinate
17896     * @see #drawableHotspotChanged(float, float)
17897     */
17898    public void dispatchDrawableHotspotChanged(float x, float y) {
17899    }
17900
17901    /**
17902     * Call this to force a view to update its drawable state. This will cause
17903     * drawableStateChanged to be called on this view. Views that are interested
17904     * in the new state should call getDrawableState.
17905     *
17906     * @see #drawableStateChanged
17907     * @see #getDrawableState
17908     */
17909    public void refreshDrawableState() {
17910        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
17911        drawableStateChanged();
17912
17913        ViewParent parent = mParent;
17914        if (parent != null) {
17915            parent.childDrawableStateChanged(this);
17916        }
17917    }
17918
17919    /**
17920     * Return an array of resource IDs of the drawable states representing the
17921     * current state of the view.
17922     *
17923     * @return The current drawable state
17924     *
17925     * @see Drawable#setState(int[])
17926     * @see #drawableStateChanged()
17927     * @see #onCreateDrawableState(int)
17928     */
17929    public final int[] getDrawableState() {
17930        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
17931            return mDrawableState;
17932        } else {
17933            mDrawableState = onCreateDrawableState(0);
17934            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
17935            return mDrawableState;
17936        }
17937    }
17938
17939    /**
17940     * Generate the new {@link android.graphics.drawable.Drawable} state for
17941     * this view. This is called by the view
17942     * system when the cached Drawable state is determined to be invalid.  To
17943     * retrieve the current state, you should use {@link #getDrawableState}.
17944     *
17945     * @param extraSpace if non-zero, this is the number of extra entries you
17946     * would like in the returned array in which you can place your own
17947     * states.
17948     *
17949     * @return Returns an array holding the current {@link Drawable} state of
17950     * the view.
17951     *
17952     * @see #mergeDrawableStates(int[], int[])
17953     */
17954    protected int[] onCreateDrawableState(int extraSpace) {
17955        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
17956                mParent instanceof View) {
17957            return ((View) mParent).onCreateDrawableState(extraSpace);
17958        }
17959
17960        int[] drawableState;
17961
17962        int privateFlags = mPrivateFlags;
17963
17964        int viewStateIndex = 0;
17965        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
17966        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
17967        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
17968        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
17969        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
17970        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
17971        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
17972                ThreadedRenderer.isAvailable()) {
17973            // This is set if HW acceleration is requested, even if the current
17974            // process doesn't allow it.  This is just to allow app preview
17975            // windows to better match their app.
17976            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
17977        }
17978        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
17979
17980        final int privateFlags2 = mPrivateFlags2;
17981        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
17982            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
17983        }
17984        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
17985            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
17986        }
17987
17988        drawableState = StateSet.get(viewStateIndex);
17989
17990        //noinspection ConstantIfStatement
17991        if (false) {
17992            Log.i("View", "drawableStateIndex=" + viewStateIndex);
17993            Log.i("View", toString()
17994                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
17995                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
17996                    + " fo=" + hasFocus()
17997                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
17998                    + " wf=" + hasWindowFocus()
17999                    + ": " + Arrays.toString(drawableState));
18000        }
18001
18002        if (extraSpace == 0) {
18003            return drawableState;
18004        }
18005
18006        final int[] fullState;
18007        if (drawableState != null) {
18008            fullState = new int[drawableState.length + extraSpace];
18009            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18010        } else {
18011            fullState = new int[extraSpace];
18012        }
18013
18014        return fullState;
18015    }
18016
18017    /**
18018     * Merge your own state values in <var>additionalState</var> into the base
18019     * state values <var>baseState</var> that were returned by
18020     * {@link #onCreateDrawableState(int)}.
18021     *
18022     * @param baseState The base state values returned by
18023     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18024     * own additional state values.
18025     *
18026     * @param additionalState The additional state values you would like
18027     * added to <var>baseState</var>; this array is not modified.
18028     *
18029     * @return As a convenience, the <var>baseState</var> array you originally
18030     * passed into the function is returned.
18031     *
18032     * @see #onCreateDrawableState(int)
18033     */
18034    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18035        final int N = baseState.length;
18036        int i = N - 1;
18037        while (i >= 0 && baseState[i] == 0) {
18038            i--;
18039        }
18040        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18041        return baseState;
18042    }
18043
18044    /**
18045     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18046     * on all Drawable objects associated with this view.
18047     * <p>
18048     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18049     * attached to this view.
18050     */
18051    @CallSuper
18052    public void jumpDrawablesToCurrentState() {
18053        if (mBackground != null) {
18054            mBackground.jumpToCurrentState();
18055        }
18056        if (mStateListAnimator != null) {
18057            mStateListAnimator.jumpToCurrentState();
18058        }
18059        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18060            mForegroundInfo.mDrawable.jumpToCurrentState();
18061        }
18062    }
18063
18064    /**
18065     * Sets the background color for this view.
18066     * @param color the color of the background
18067     */
18068    @RemotableViewMethod
18069    public void setBackgroundColor(@ColorInt int color) {
18070        if (mBackground instanceof ColorDrawable) {
18071            ((ColorDrawable) mBackground.mutate()).setColor(color);
18072            computeOpaqueFlags();
18073            mBackgroundResource = 0;
18074        } else {
18075            setBackground(new ColorDrawable(color));
18076        }
18077    }
18078
18079    /**
18080     * Set the background to a given resource. The resource should refer to
18081     * a Drawable object or 0 to remove the background.
18082     * @param resid The identifier of the resource.
18083     *
18084     * @attr ref android.R.styleable#View_background
18085     */
18086    @RemotableViewMethod
18087    public void setBackgroundResource(@DrawableRes int resid) {
18088        if (resid != 0 && resid == mBackgroundResource) {
18089            return;
18090        }
18091
18092        Drawable d = null;
18093        if (resid != 0) {
18094            d = mContext.getDrawable(resid);
18095        }
18096        setBackground(d);
18097
18098        mBackgroundResource = resid;
18099    }
18100
18101    /**
18102     * Set the background to a given Drawable, or remove the background. If the
18103     * background has padding, this View's padding is set to the background's
18104     * padding. However, when a background is removed, this View's padding isn't
18105     * touched. If setting the padding is desired, please use
18106     * {@link #setPadding(int, int, int, int)}.
18107     *
18108     * @param background The Drawable to use as the background, or null to remove the
18109     *        background
18110     */
18111    public void setBackground(Drawable background) {
18112        //noinspection deprecation
18113        setBackgroundDrawable(background);
18114    }
18115
18116    /**
18117     * @deprecated use {@link #setBackground(Drawable)} instead
18118     */
18119    @Deprecated
18120    public void setBackgroundDrawable(Drawable background) {
18121        computeOpaqueFlags();
18122
18123        if (background == mBackground) {
18124            return;
18125        }
18126
18127        boolean requestLayout = false;
18128
18129        mBackgroundResource = 0;
18130
18131        /*
18132         * Regardless of whether we're setting a new background or not, we want
18133         * to clear the previous drawable. setVisible first while we still have the callback set.
18134         */
18135        if (mBackground != null) {
18136            if (isAttachedToWindow()) {
18137                mBackground.setVisible(false, false);
18138            }
18139            mBackground.setCallback(null);
18140            unscheduleDrawable(mBackground);
18141        }
18142
18143        if (background != null) {
18144            Rect padding = sThreadLocal.get();
18145            if (padding == null) {
18146                padding = new Rect();
18147                sThreadLocal.set(padding);
18148            }
18149            resetResolvedDrawablesInternal();
18150            background.setLayoutDirection(getLayoutDirection());
18151            if (background.getPadding(padding)) {
18152                resetResolvedPaddingInternal();
18153                switch (background.getLayoutDirection()) {
18154                    case LAYOUT_DIRECTION_RTL:
18155                        mUserPaddingLeftInitial = padding.right;
18156                        mUserPaddingRightInitial = padding.left;
18157                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18158                        break;
18159                    case LAYOUT_DIRECTION_LTR:
18160                    default:
18161                        mUserPaddingLeftInitial = padding.left;
18162                        mUserPaddingRightInitial = padding.right;
18163                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18164                }
18165                mLeftPaddingDefined = false;
18166                mRightPaddingDefined = false;
18167            }
18168
18169            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18170            // if it has a different minimum size, we should layout again
18171            if (mBackground == null
18172                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18173                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18174                requestLayout = true;
18175            }
18176
18177            // Set mBackground before we set this as the callback and start making other
18178            // background drawable state change calls. In particular, the setVisible call below
18179            // can result in drawables attempting to start animations or otherwise invalidate,
18180            // which requires the view set as the callback (us) to recognize the drawable as
18181            // belonging to it as per verifyDrawable.
18182            mBackground = background;
18183            if (background.isStateful()) {
18184                background.setState(getDrawableState());
18185            }
18186            if (isAttachedToWindow()) {
18187                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18188            }
18189
18190            applyBackgroundTint();
18191
18192            // Set callback last, since the view may still be initializing.
18193            background.setCallback(this);
18194
18195            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18196                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18197                requestLayout = true;
18198            }
18199        } else {
18200            /* Remove the background */
18201            mBackground = null;
18202            if ((mViewFlags & WILL_NOT_DRAW) != 0
18203                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18204                mPrivateFlags |= PFLAG_SKIP_DRAW;
18205            }
18206
18207            /*
18208             * When the background is set, we try to apply its padding to this
18209             * View. When the background is removed, we don't touch this View's
18210             * padding. This is noted in the Javadocs. Hence, we don't need to
18211             * requestLayout(), the invalidate() below is sufficient.
18212             */
18213
18214            // The old background's minimum size could have affected this
18215            // View's layout, so let's requestLayout
18216            requestLayout = true;
18217        }
18218
18219        computeOpaqueFlags();
18220
18221        if (requestLayout) {
18222            requestLayout();
18223        }
18224
18225        mBackgroundSizeChanged = true;
18226        invalidate(true);
18227        invalidateOutline();
18228    }
18229
18230    /**
18231     * Gets the background drawable
18232     *
18233     * @return The drawable used as the background for this view, if any.
18234     *
18235     * @see #setBackground(Drawable)
18236     *
18237     * @attr ref android.R.styleable#View_background
18238     */
18239    public Drawable getBackground() {
18240        return mBackground;
18241    }
18242
18243    /**
18244     * Applies a tint to the background drawable. Does not modify the current tint
18245     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18246     * <p>
18247     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18248     * mutate the drawable and apply the specified tint and tint mode using
18249     * {@link Drawable#setTintList(ColorStateList)}.
18250     *
18251     * @param tint the tint to apply, may be {@code null} to clear tint
18252     *
18253     * @attr ref android.R.styleable#View_backgroundTint
18254     * @see #getBackgroundTintList()
18255     * @see Drawable#setTintList(ColorStateList)
18256     */
18257    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18258        if (mBackgroundTint == null) {
18259            mBackgroundTint = new TintInfo();
18260        }
18261        mBackgroundTint.mTintList = tint;
18262        mBackgroundTint.mHasTintList = true;
18263
18264        applyBackgroundTint();
18265    }
18266
18267    /**
18268     * Return the tint applied to the background drawable, if specified.
18269     *
18270     * @return the tint applied to the background drawable
18271     * @attr ref android.R.styleable#View_backgroundTint
18272     * @see #setBackgroundTintList(ColorStateList)
18273     */
18274    @Nullable
18275    public ColorStateList getBackgroundTintList() {
18276        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18277    }
18278
18279    /**
18280     * Specifies the blending mode used to apply the tint specified by
18281     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18282     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18283     *
18284     * @param tintMode the blending mode used to apply the tint, may be
18285     *                 {@code null} to clear tint
18286     * @attr ref android.R.styleable#View_backgroundTintMode
18287     * @see #getBackgroundTintMode()
18288     * @see Drawable#setTintMode(PorterDuff.Mode)
18289     */
18290    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18291        if (mBackgroundTint == null) {
18292            mBackgroundTint = new TintInfo();
18293        }
18294        mBackgroundTint.mTintMode = tintMode;
18295        mBackgroundTint.mHasTintMode = true;
18296
18297        applyBackgroundTint();
18298    }
18299
18300    /**
18301     * Return the blending mode used to apply the tint to the background
18302     * drawable, if specified.
18303     *
18304     * @return the blending mode used to apply the tint to the background
18305     *         drawable
18306     * @attr ref android.R.styleable#View_backgroundTintMode
18307     * @see #setBackgroundTintMode(PorterDuff.Mode)
18308     */
18309    @Nullable
18310    public PorterDuff.Mode getBackgroundTintMode() {
18311        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18312    }
18313
18314    private void applyBackgroundTint() {
18315        if (mBackground != null && mBackgroundTint != null) {
18316            final TintInfo tintInfo = mBackgroundTint;
18317            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18318                mBackground = mBackground.mutate();
18319
18320                if (tintInfo.mHasTintList) {
18321                    mBackground.setTintList(tintInfo.mTintList);
18322                }
18323
18324                if (tintInfo.mHasTintMode) {
18325                    mBackground.setTintMode(tintInfo.mTintMode);
18326                }
18327
18328                // The drawable (or one of its children) may not have been
18329                // stateful before applying the tint, so let's try again.
18330                if (mBackground.isStateful()) {
18331                    mBackground.setState(getDrawableState());
18332                }
18333            }
18334        }
18335    }
18336
18337    /**
18338     * Returns the drawable used as the foreground of this View. The
18339     * foreground drawable, if non-null, is always drawn on top of the view's content.
18340     *
18341     * @return a Drawable or null if no foreground was set
18342     *
18343     * @see #onDrawForeground(Canvas)
18344     */
18345    public Drawable getForeground() {
18346        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18347    }
18348
18349    /**
18350     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18351     *
18352     * @param foreground the Drawable to be drawn on top of the children
18353     *
18354     * @attr ref android.R.styleable#View_foreground
18355     */
18356    public void setForeground(Drawable foreground) {
18357        if (mForegroundInfo == null) {
18358            if (foreground == null) {
18359                // Nothing to do.
18360                return;
18361            }
18362            mForegroundInfo = new ForegroundInfo();
18363        }
18364
18365        if (foreground == mForegroundInfo.mDrawable) {
18366            // Nothing to do
18367            return;
18368        }
18369
18370        if (mForegroundInfo.mDrawable != null) {
18371            if (isAttachedToWindow()) {
18372                mForegroundInfo.mDrawable.setVisible(false, false);
18373            }
18374            mForegroundInfo.mDrawable.setCallback(null);
18375            unscheduleDrawable(mForegroundInfo.mDrawable);
18376        }
18377
18378        mForegroundInfo.mDrawable = foreground;
18379        mForegroundInfo.mBoundsChanged = true;
18380        if (foreground != null) {
18381            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18382                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18383            }
18384            foreground.setLayoutDirection(getLayoutDirection());
18385            if (foreground.isStateful()) {
18386                foreground.setState(getDrawableState());
18387            }
18388            applyForegroundTint();
18389            if (isAttachedToWindow()) {
18390                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18391            }
18392            // Set callback last, since the view may still be initializing.
18393            foreground.setCallback(this);
18394        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18395            mPrivateFlags |= PFLAG_SKIP_DRAW;
18396        }
18397        requestLayout();
18398        invalidate();
18399    }
18400
18401    /**
18402     * Magic bit used to support features of framework-internal window decor implementation details.
18403     * This used to live exclusively in FrameLayout.
18404     *
18405     * @return true if the foreground should draw inside the padding region or false
18406     *         if it should draw inset by the view's padding
18407     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18408     */
18409    public boolean isForegroundInsidePadding() {
18410        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18411    }
18412
18413    /**
18414     * Describes how the foreground is positioned.
18415     *
18416     * @return foreground gravity.
18417     *
18418     * @see #setForegroundGravity(int)
18419     *
18420     * @attr ref android.R.styleable#View_foregroundGravity
18421     */
18422    public int getForegroundGravity() {
18423        return mForegroundInfo != null ? mForegroundInfo.mGravity
18424                : Gravity.START | Gravity.TOP;
18425    }
18426
18427    /**
18428     * Describes how the foreground is positioned. Defaults to START and TOP.
18429     *
18430     * @param gravity see {@link android.view.Gravity}
18431     *
18432     * @see #getForegroundGravity()
18433     *
18434     * @attr ref android.R.styleable#View_foregroundGravity
18435     */
18436    public void setForegroundGravity(int gravity) {
18437        if (mForegroundInfo == null) {
18438            mForegroundInfo = new ForegroundInfo();
18439        }
18440
18441        if (mForegroundInfo.mGravity != gravity) {
18442            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
18443                gravity |= Gravity.START;
18444            }
18445
18446            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
18447                gravity |= Gravity.TOP;
18448            }
18449
18450            mForegroundInfo.mGravity = gravity;
18451            requestLayout();
18452        }
18453    }
18454
18455    /**
18456     * Applies a tint to the foreground drawable. Does not modify the current tint
18457     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18458     * <p>
18459     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
18460     * mutate the drawable and apply the specified tint and tint mode using
18461     * {@link Drawable#setTintList(ColorStateList)}.
18462     *
18463     * @param tint the tint to apply, may be {@code null} to clear tint
18464     *
18465     * @attr ref android.R.styleable#View_foregroundTint
18466     * @see #getForegroundTintList()
18467     * @see Drawable#setTintList(ColorStateList)
18468     */
18469    public void setForegroundTintList(@Nullable ColorStateList tint) {
18470        if (mForegroundInfo == null) {
18471            mForegroundInfo = new ForegroundInfo();
18472        }
18473        if (mForegroundInfo.mTintInfo == null) {
18474            mForegroundInfo.mTintInfo = new TintInfo();
18475        }
18476        mForegroundInfo.mTintInfo.mTintList = tint;
18477        mForegroundInfo.mTintInfo.mHasTintList = true;
18478
18479        applyForegroundTint();
18480    }
18481
18482    /**
18483     * Return the tint applied to the foreground drawable, if specified.
18484     *
18485     * @return the tint applied to the foreground drawable
18486     * @attr ref android.R.styleable#View_foregroundTint
18487     * @see #setForegroundTintList(ColorStateList)
18488     */
18489    @Nullable
18490    public ColorStateList getForegroundTintList() {
18491        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18492                ? mForegroundInfo.mTintInfo.mTintList : null;
18493    }
18494
18495    /**
18496     * Specifies the blending mode used to apply the tint specified by
18497     * {@link #setForegroundTintList(ColorStateList)}} to the background
18498     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18499     *
18500     * @param tintMode the blending mode used to apply the tint, may be
18501     *                 {@code null} to clear tint
18502     * @attr ref android.R.styleable#View_foregroundTintMode
18503     * @see #getForegroundTintMode()
18504     * @see Drawable#setTintMode(PorterDuff.Mode)
18505     */
18506    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18507        if (mForegroundInfo == null) {
18508            mForegroundInfo = new ForegroundInfo();
18509        }
18510        if (mForegroundInfo.mTintInfo == null) {
18511            mForegroundInfo.mTintInfo = new TintInfo();
18512        }
18513        mForegroundInfo.mTintInfo.mTintMode = tintMode;
18514        mForegroundInfo.mTintInfo.mHasTintMode = true;
18515
18516        applyForegroundTint();
18517    }
18518
18519    /**
18520     * Return the blending mode used to apply the tint to the foreground
18521     * drawable, if specified.
18522     *
18523     * @return the blending mode used to apply the tint to the foreground
18524     *         drawable
18525     * @attr ref android.R.styleable#View_foregroundTintMode
18526     * @see #setForegroundTintMode(PorterDuff.Mode)
18527     */
18528    @Nullable
18529    public PorterDuff.Mode getForegroundTintMode() {
18530        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18531                ? mForegroundInfo.mTintInfo.mTintMode : null;
18532    }
18533
18534    private void applyForegroundTint() {
18535        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
18536                && mForegroundInfo.mTintInfo != null) {
18537            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
18538            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18539                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
18540
18541                if (tintInfo.mHasTintList) {
18542                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
18543                }
18544
18545                if (tintInfo.mHasTintMode) {
18546                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
18547                }
18548
18549                // The drawable (or one of its children) may not have been
18550                // stateful before applying the tint, so let's try again.
18551                if (mForegroundInfo.mDrawable.isStateful()) {
18552                    mForegroundInfo.mDrawable.setState(getDrawableState());
18553                }
18554            }
18555        }
18556    }
18557
18558    /**
18559     * Draw any foreground content for this view.
18560     *
18561     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
18562     * drawable or other view-specific decorations. The foreground is drawn on top of the
18563     * primary view content.</p>
18564     *
18565     * @param canvas canvas to draw into
18566     */
18567    public void onDrawForeground(Canvas canvas) {
18568        onDrawScrollIndicators(canvas);
18569        onDrawScrollBars(canvas);
18570
18571        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18572        if (foreground != null) {
18573            if (mForegroundInfo.mBoundsChanged) {
18574                mForegroundInfo.mBoundsChanged = false;
18575                final Rect selfBounds = mForegroundInfo.mSelfBounds;
18576                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
18577
18578                if (mForegroundInfo.mInsidePadding) {
18579                    selfBounds.set(0, 0, getWidth(), getHeight());
18580                } else {
18581                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
18582                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
18583                }
18584
18585                final int ld = getLayoutDirection();
18586                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
18587                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
18588                foreground.setBounds(overlayBounds);
18589            }
18590
18591            foreground.draw(canvas);
18592        }
18593    }
18594
18595    /**
18596     * Sets the padding. The view may add on the space required to display
18597     * the scrollbars, depending on the style and visibility of the scrollbars.
18598     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
18599     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
18600     * from the values set in this call.
18601     *
18602     * @attr ref android.R.styleable#View_padding
18603     * @attr ref android.R.styleable#View_paddingBottom
18604     * @attr ref android.R.styleable#View_paddingLeft
18605     * @attr ref android.R.styleable#View_paddingRight
18606     * @attr ref android.R.styleable#View_paddingTop
18607     * @param left the left padding in pixels
18608     * @param top the top padding in pixels
18609     * @param right the right padding in pixels
18610     * @param bottom the bottom padding in pixels
18611     */
18612    public void setPadding(int left, int top, int right, int bottom) {
18613        resetResolvedPaddingInternal();
18614
18615        mUserPaddingStart = UNDEFINED_PADDING;
18616        mUserPaddingEnd = UNDEFINED_PADDING;
18617
18618        mUserPaddingLeftInitial = left;
18619        mUserPaddingRightInitial = right;
18620
18621        mLeftPaddingDefined = true;
18622        mRightPaddingDefined = true;
18623
18624        internalSetPadding(left, top, right, bottom);
18625    }
18626
18627    /**
18628     * @hide
18629     */
18630    protected void internalSetPadding(int left, int top, int right, int bottom) {
18631        mUserPaddingLeft = left;
18632        mUserPaddingRight = right;
18633        mUserPaddingBottom = bottom;
18634
18635        final int viewFlags = mViewFlags;
18636        boolean changed = false;
18637
18638        // Common case is there are no scroll bars.
18639        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
18640            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
18641                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
18642                        ? 0 : getVerticalScrollbarWidth();
18643                switch (mVerticalScrollbarPosition) {
18644                    case SCROLLBAR_POSITION_DEFAULT:
18645                        if (isLayoutRtl()) {
18646                            left += offset;
18647                        } else {
18648                            right += offset;
18649                        }
18650                        break;
18651                    case SCROLLBAR_POSITION_RIGHT:
18652                        right += offset;
18653                        break;
18654                    case SCROLLBAR_POSITION_LEFT:
18655                        left += offset;
18656                        break;
18657                }
18658            }
18659            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
18660                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
18661                        ? 0 : getHorizontalScrollbarHeight();
18662            }
18663        }
18664
18665        if (mPaddingLeft != left) {
18666            changed = true;
18667            mPaddingLeft = left;
18668        }
18669        if (mPaddingTop != top) {
18670            changed = true;
18671            mPaddingTop = top;
18672        }
18673        if (mPaddingRight != right) {
18674            changed = true;
18675            mPaddingRight = right;
18676        }
18677        if (mPaddingBottom != bottom) {
18678            changed = true;
18679            mPaddingBottom = bottom;
18680        }
18681
18682        if (changed) {
18683            requestLayout();
18684            invalidateOutline();
18685        }
18686    }
18687
18688    /**
18689     * Sets the relative padding. The view may add on the space required to display
18690     * the scrollbars, depending on the style and visibility of the scrollbars.
18691     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
18692     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
18693     * from the values set in this call.
18694     *
18695     * @attr ref android.R.styleable#View_padding
18696     * @attr ref android.R.styleable#View_paddingBottom
18697     * @attr ref android.R.styleable#View_paddingStart
18698     * @attr ref android.R.styleable#View_paddingEnd
18699     * @attr ref android.R.styleable#View_paddingTop
18700     * @param start the start padding in pixels
18701     * @param top the top padding in pixels
18702     * @param end the end padding in pixels
18703     * @param bottom the bottom padding in pixels
18704     */
18705    public void setPaddingRelative(int start, int top, int end, int bottom) {
18706        resetResolvedPaddingInternal();
18707
18708        mUserPaddingStart = start;
18709        mUserPaddingEnd = end;
18710        mLeftPaddingDefined = true;
18711        mRightPaddingDefined = true;
18712
18713        switch(getLayoutDirection()) {
18714            case LAYOUT_DIRECTION_RTL:
18715                mUserPaddingLeftInitial = end;
18716                mUserPaddingRightInitial = start;
18717                internalSetPadding(end, top, start, bottom);
18718                break;
18719            case LAYOUT_DIRECTION_LTR:
18720            default:
18721                mUserPaddingLeftInitial = start;
18722                mUserPaddingRightInitial = end;
18723                internalSetPadding(start, top, end, bottom);
18724        }
18725    }
18726
18727    /**
18728     * Returns the top padding of this view.
18729     *
18730     * @return the top padding in pixels
18731     */
18732    public int getPaddingTop() {
18733        return mPaddingTop;
18734    }
18735
18736    /**
18737     * Returns the bottom padding of this view. If there are inset and enabled
18738     * scrollbars, this value may include the space required to display the
18739     * scrollbars as well.
18740     *
18741     * @return the bottom padding in pixels
18742     */
18743    public int getPaddingBottom() {
18744        return mPaddingBottom;
18745    }
18746
18747    /**
18748     * Returns the left padding of this view. If there are inset and enabled
18749     * scrollbars, this value may include the space required to display the
18750     * scrollbars as well.
18751     *
18752     * @return the left padding in pixels
18753     */
18754    public int getPaddingLeft() {
18755        if (!isPaddingResolved()) {
18756            resolvePadding();
18757        }
18758        return mPaddingLeft;
18759    }
18760
18761    /**
18762     * Returns the start padding of this view depending on its resolved layout direction.
18763     * If there are inset and enabled scrollbars, this value may include the space
18764     * required to display the scrollbars as well.
18765     *
18766     * @return the start padding in pixels
18767     */
18768    public int getPaddingStart() {
18769        if (!isPaddingResolved()) {
18770            resolvePadding();
18771        }
18772        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18773                mPaddingRight : mPaddingLeft;
18774    }
18775
18776    /**
18777     * Returns the right padding of this view. If there are inset and enabled
18778     * scrollbars, this value may include the space required to display the
18779     * scrollbars as well.
18780     *
18781     * @return the right padding in pixels
18782     */
18783    public int getPaddingRight() {
18784        if (!isPaddingResolved()) {
18785            resolvePadding();
18786        }
18787        return mPaddingRight;
18788    }
18789
18790    /**
18791     * Returns the end padding of this view depending on its resolved layout direction.
18792     * If there are inset and enabled scrollbars, this value may include the space
18793     * required to display the scrollbars as well.
18794     *
18795     * @return the end padding in pixels
18796     */
18797    public int getPaddingEnd() {
18798        if (!isPaddingResolved()) {
18799            resolvePadding();
18800        }
18801        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18802                mPaddingLeft : mPaddingRight;
18803    }
18804
18805    /**
18806     * Return if the padding has been set through relative values
18807     * {@link #setPaddingRelative(int, int, int, int)} or through
18808     * @attr ref android.R.styleable#View_paddingStart or
18809     * @attr ref android.R.styleable#View_paddingEnd
18810     *
18811     * @return true if the padding is relative or false if it is not.
18812     */
18813    public boolean isPaddingRelative() {
18814        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
18815    }
18816
18817    Insets computeOpticalInsets() {
18818        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
18819    }
18820
18821    /**
18822     * @hide
18823     */
18824    public void resetPaddingToInitialValues() {
18825        if (isRtlCompatibilityMode()) {
18826            mPaddingLeft = mUserPaddingLeftInitial;
18827            mPaddingRight = mUserPaddingRightInitial;
18828            return;
18829        }
18830        if (isLayoutRtl()) {
18831            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
18832            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
18833        } else {
18834            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
18835            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
18836        }
18837    }
18838
18839    /**
18840     * @hide
18841     */
18842    public Insets getOpticalInsets() {
18843        if (mLayoutInsets == null) {
18844            mLayoutInsets = computeOpticalInsets();
18845        }
18846        return mLayoutInsets;
18847    }
18848
18849    /**
18850     * Set this view's optical insets.
18851     *
18852     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
18853     * property. Views that compute their own optical insets should call it as part of measurement.
18854     * This method does not request layout. If you are setting optical insets outside of
18855     * measure/layout itself you will want to call requestLayout() yourself.
18856     * </p>
18857     * @hide
18858     */
18859    public void setOpticalInsets(Insets insets) {
18860        mLayoutInsets = insets;
18861    }
18862
18863    /**
18864     * Changes the selection state of this view. A view can be selected or not.
18865     * Note that selection is not the same as focus. Views are typically
18866     * selected in the context of an AdapterView like ListView or GridView;
18867     * the selected view is the view that is highlighted.
18868     *
18869     * @param selected true if the view must be selected, false otherwise
18870     */
18871    public void setSelected(boolean selected) {
18872        //noinspection DoubleNegation
18873        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
18874            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
18875            if (!selected) resetPressedState();
18876            invalidate(true);
18877            refreshDrawableState();
18878            dispatchSetSelected(selected);
18879            if (selected) {
18880                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
18881            } else {
18882                notifyViewAccessibilityStateChangedIfNeeded(
18883                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
18884            }
18885        }
18886    }
18887
18888    /**
18889     * Dispatch setSelected to all of this View's children.
18890     *
18891     * @see #setSelected(boolean)
18892     *
18893     * @param selected The new selected state
18894     */
18895    protected void dispatchSetSelected(boolean selected) {
18896    }
18897
18898    /**
18899     * Indicates the selection state of this view.
18900     *
18901     * @return true if the view is selected, false otherwise
18902     */
18903    @ViewDebug.ExportedProperty
18904    public boolean isSelected() {
18905        return (mPrivateFlags & PFLAG_SELECTED) != 0;
18906    }
18907
18908    /**
18909     * Changes the activated state of this view. A view can be activated or not.
18910     * Note that activation is not the same as selection.  Selection is
18911     * a transient property, representing the view (hierarchy) the user is
18912     * currently interacting with.  Activation is a longer-term state that the
18913     * user can move views in and out of.  For example, in a list view with
18914     * single or multiple selection enabled, the views in the current selection
18915     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
18916     * here.)  The activated state is propagated down to children of the view it
18917     * is set on.
18918     *
18919     * @param activated true if the view must be activated, false otherwise
18920     */
18921    public void setActivated(boolean activated) {
18922        //noinspection DoubleNegation
18923        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
18924            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
18925            invalidate(true);
18926            refreshDrawableState();
18927            dispatchSetActivated(activated);
18928        }
18929    }
18930
18931    /**
18932     * Dispatch setActivated to all of this View's children.
18933     *
18934     * @see #setActivated(boolean)
18935     *
18936     * @param activated The new activated state
18937     */
18938    protected void dispatchSetActivated(boolean activated) {
18939    }
18940
18941    /**
18942     * Indicates the activation state of this view.
18943     *
18944     * @return true if the view is activated, false otherwise
18945     */
18946    @ViewDebug.ExportedProperty
18947    public boolean isActivated() {
18948        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
18949    }
18950
18951    /**
18952     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
18953     * observer can be used to get notifications when global events, like
18954     * layout, happen.
18955     *
18956     * The returned ViewTreeObserver observer is not guaranteed to remain
18957     * valid for the lifetime of this View. If the caller of this method keeps
18958     * a long-lived reference to ViewTreeObserver, it should always check for
18959     * the return value of {@link ViewTreeObserver#isAlive()}.
18960     *
18961     * @return The ViewTreeObserver for this view's hierarchy.
18962     */
18963    public ViewTreeObserver getViewTreeObserver() {
18964        if (mAttachInfo != null) {
18965            return mAttachInfo.mTreeObserver;
18966        }
18967        if (mFloatingTreeObserver == null) {
18968            mFloatingTreeObserver = new ViewTreeObserver();
18969        }
18970        return mFloatingTreeObserver;
18971    }
18972
18973    /**
18974     * <p>Finds the topmost view in the current view hierarchy.</p>
18975     *
18976     * @return the topmost view containing this view
18977     */
18978    public View getRootView() {
18979        if (mAttachInfo != null) {
18980            final View v = mAttachInfo.mRootView;
18981            if (v != null) {
18982                return v;
18983            }
18984        }
18985
18986        View parent = this;
18987
18988        while (parent.mParent != null && parent.mParent instanceof View) {
18989            parent = (View) parent.mParent;
18990        }
18991
18992        return parent;
18993    }
18994
18995    /**
18996     * Transforms a motion event from view-local coordinates to on-screen
18997     * coordinates.
18998     *
18999     * @param ev the view-local motion event
19000     * @return false if the transformation could not be applied
19001     * @hide
19002     */
19003    public boolean toGlobalMotionEvent(MotionEvent ev) {
19004        final AttachInfo info = mAttachInfo;
19005        if (info == null) {
19006            return false;
19007        }
19008
19009        final Matrix m = info.mTmpMatrix;
19010        m.set(Matrix.IDENTITY_MATRIX);
19011        transformMatrixToGlobal(m);
19012        ev.transform(m);
19013        return true;
19014    }
19015
19016    /**
19017     * Transforms a motion event from on-screen coordinates to view-local
19018     * coordinates.
19019     *
19020     * @param ev the on-screen motion event
19021     * @return false if the transformation could not be applied
19022     * @hide
19023     */
19024    public boolean toLocalMotionEvent(MotionEvent ev) {
19025        final AttachInfo info = mAttachInfo;
19026        if (info == null) {
19027            return false;
19028        }
19029
19030        final Matrix m = info.mTmpMatrix;
19031        m.set(Matrix.IDENTITY_MATRIX);
19032        transformMatrixToLocal(m);
19033        ev.transform(m);
19034        return true;
19035    }
19036
19037    /**
19038     * Modifies the input matrix such that it maps view-local coordinates to
19039     * on-screen coordinates.
19040     *
19041     * @param m input matrix to modify
19042     * @hide
19043     */
19044    public void transformMatrixToGlobal(Matrix m) {
19045        final ViewParent parent = mParent;
19046        if (parent instanceof View) {
19047            final View vp = (View) parent;
19048            vp.transformMatrixToGlobal(m);
19049            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19050        } else if (parent instanceof ViewRootImpl) {
19051            final ViewRootImpl vr = (ViewRootImpl) parent;
19052            vr.transformMatrixToGlobal(m);
19053            m.preTranslate(0, -vr.mCurScrollY);
19054        }
19055
19056        m.preTranslate(mLeft, mTop);
19057
19058        if (!hasIdentityMatrix()) {
19059            m.preConcat(getMatrix());
19060        }
19061    }
19062
19063    /**
19064     * Modifies the input matrix such that it maps on-screen coordinates to
19065     * view-local coordinates.
19066     *
19067     * @param m input matrix to modify
19068     * @hide
19069     */
19070    public void transformMatrixToLocal(Matrix m) {
19071        final ViewParent parent = mParent;
19072        if (parent instanceof View) {
19073            final View vp = (View) parent;
19074            vp.transformMatrixToLocal(m);
19075            m.postTranslate(vp.mScrollX, vp.mScrollY);
19076        } else if (parent instanceof ViewRootImpl) {
19077            final ViewRootImpl vr = (ViewRootImpl) parent;
19078            vr.transformMatrixToLocal(m);
19079            m.postTranslate(0, vr.mCurScrollY);
19080        }
19081
19082        m.postTranslate(-mLeft, -mTop);
19083
19084        if (!hasIdentityMatrix()) {
19085            m.postConcat(getInverseMatrix());
19086        }
19087    }
19088
19089    /**
19090     * @hide
19091     */
19092    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19093            @ViewDebug.IntToString(from = 0, to = "x"),
19094            @ViewDebug.IntToString(from = 1, to = "y")
19095    })
19096    public int[] getLocationOnScreen() {
19097        int[] location = new int[2];
19098        getLocationOnScreen(location);
19099        return location;
19100    }
19101
19102    /**
19103     * <p>Computes the coordinates of this view on the screen. The argument
19104     * must be an array of two integers. After the method returns, the array
19105     * contains the x and y location in that order.</p>
19106     *
19107     * @param outLocation an array of two integers in which to hold the coordinates
19108     */
19109    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19110        getLocationInWindow(outLocation);
19111
19112        final AttachInfo info = mAttachInfo;
19113        if (info != null) {
19114            outLocation[0] += info.mWindowLeft;
19115            outLocation[1] += info.mWindowTop;
19116        }
19117    }
19118
19119    /**
19120     * <p>Computes the coordinates of this view in its window. The argument
19121     * must be an array of two integers. After the method returns, the array
19122     * contains the x and y location in that order.</p>
19123     *
19124     * @param outLocation an array of two integers in which to hold the coordinates
19125     */
19126    public void getLocationInWindow(@Size(2) int[] outLocation) {
19127        if (outLocation == null || outLocation.length < 2) {
19128            throw new IllegalArgumentException("outLocation must be an array of two integers");
19129        }
19130
19131        outLocation[0] = 0;
19132        outLocation[1] = 0;
19133
19134        transformFromViewToWindowSpace(outLocation);
19135    }
19136
19137    /** @hide */
19138    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19139        if (inOutLocation == null || inOutLocation.length < 2) {
19140            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19141        }
19142
19143        if (mAttachInfo == null) {
19144            // When the view is not attached to a window, this method does not make sense
19145            inOutLocation[0] = inOutLocation[1] = 0;
19146            return;
19147        }
19148
19149        float position[] = mAttachInfo.mTmpTransformLocation;
19150        position[0] = inOutLocation[0];
19151        position[1] = inOutLocation[1];
19152
19153        if (!hasIdentityMatrix()) {
19154            getMatrix().mapPoints(position);
19155        }
19156
19157        position[0] += mLeft;
19158        position[1] += mTop;
19159
19160        ViewParent viewParent = mParent;
19161        while (viewParent instanceof View) {
19162            final View view = (View) viewParent;
19163
19164            position[0] -= view.mScrollX;
19165            position[1] -= view.mScrollY;
19166
19167            if (!view.hasIdentityMatrix()) {
19168                view.getMatrix().mapPoints(position);
19169            }
19170
19171            position[0] += view.mLeft;
19172            position[1] += view.mTop;
19173
19174            viewParent = view.mParent;
19175         }
19176
19177        if (viewParent instanceof ViewRootImpl) {
19178            // *cough*
19179            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19180            position[1] -= vr.mCurScrollY;
19181        }
19182
19183        inOutLocation[0] = Math.round(position[0]);
19184        inOutLocation[1] = Math.round(position[1]);
19185    }
19186
19187    /**
19188     * {@hide}
19189     * @param id the id of the view to be found
19190     * @return the view of the specified id, null if cannot be found
19191     */
19192    protected View findViewTraversal(@IdRes int id) {
19193        if (id == mID) {
19194            return this;
19195        }
19196        return null;
19197    }
19198
19199    /**
19200     * {@hide}
19201     * @param tag the tag of the view to be found
19202     * @return the view of specified tag, null if cannot be found
19203     */
19204    protected View findViewWithTagTraversal(Object tag) {
19205        if (tag != null && tag.equals(mTag)) {
19206            return this;
19207        }
19208        return null;
19209    }
19210
19211    /**
19212     * {@hide}
19213     * @param predicate The predicate to evaluate.
19214     * @param childToSkip If not null, ignores this child during the recursive traversal.
19215     * @return The first view that matches the predicate or null.
19216     */
19217    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19218        if (predicate.apply(this)) {
19219            return this;
19220        }
19221        return null;
19222    }
19223
19224    /**
19225     * Look for a child view with the given id.  If this view has the given
19226     * id, return this view.
19227     *
19228     * @param id The id to search for.
19229     * @return The view that has the given id in the hierarchy or null
19230     */
19231    @Nullable
19232    public final View findViewById(@IdRes int id) {
19233        if (id < 0) {
19234            return null;
19235        }
19236        return findViewTraversal(id);
19237    }
19238
19239    /**
19240     * Finds a view by its unuque and stable accessibility id.
19241     *
19242     * @param accessibilityId The searched accessibility id.
19243     * @return The found view.
19244     */
19245    final View findViewByAccessibilityId(int accessibilityId) {
19246        if (accessibilityId < 0) {
19247            return null;
19248        }
19249        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19250        if (view != null) {
19251            return view.includeForAccessibility() ? view : null;
19252        }
19253        return null;
19254    }
19255
19256    /**
19257     * Performs the traversal to find a view by its unuque and stable accessibility id.
19258     *
19259     * <strong>Note:</strong>This method does not stop at the root namespace
19260     * boundary since the user can touch the screen at an arbitrary location
19261     * potentially crossing the root namespace bounday which will send an
19262     * accessibility event to accessibility services and they should be able
19263     * to obtain the event source. Also accessibility ids are guaranteed to be
19264     * unique in the window.
19265     *
19266     * @param accessibilityId The accessibility id.
19267     * @return The found view.
19268     *
19269     * @hide
19270     */
19271    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19272        if (getAccessibilityViewId() == accessibilityId) {
19273            return this;
19274        }
19275        return null;
19276    }
19277
19278    /**
19279     * Look for a child view with the given tag.  If this view has the given
19280     * tag, return this view.
19281     *
19282     * @param tag The tag to search for, using "tag.equals(getTag())".
19283     * @return The View that has the given tag in the hierarchy or null
19284     */
19285    public final View findViewWithTag(Object tag) {
19286        if (tag == null) {
19287            return null;
19288        }
19289        return findViewWithTagTraversal(tag);
19290    }
19291
19292    /**
19293     * {@hide}
19294     * Look for a child view that matches the specified predicate.
19295     * If this view matches the predicate, return this view.
19296     *
19297     * @param predicate The predicate to evaluate.
19298     * @return The first view that matches the predicate or null.
19299     */
19300    public final View findViewByPredicate(Predicate<View> predicate) {
19301        return findViewByPredicateTraversal(predicate, null);
19302    }
19303
19304    /**
19305     * {@hide}
19306     * Look for a child view that matches the specified predicate,
19307     * starting with the specified view and its descendents and then
19308     * recusively searching the ancestors and siblings of that view
19309     * until this view is reached.
19310     *
19311     * This method is useful in cases where the predicate does not match
19312     * a single unique view (perhaps multiple views use the same id)
19313     * and we are trying to find the view that is "closest" in scope to the
19314     * starting view.
19315     *
19316     * @param start The view to start from.
19317     * @param predicate The predicate to evaluate.
19318     * @return The first view that matches the predicate or null.
19319     */
19320    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19321        View childToSkip = null;
19322        for (;;) {
19323            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19324            if (view != null || start == this) {
19325                return view;
19326            }
19327
19328            ViewParent parent = start.getParent();
19329            if (parent == null || !(parent instanceof View)) {
19330                return null;
19331            }
19332
19333            childToSkip = start;
19334            start = (View) parent;
19335        }
19336    }
19337
19338    /**
19339     * Sets the identifier for this view. The identifier does not have to be
19340     * unique in this view's hierarchy. The identifier should be a positive
19341     * number.
19342     *
19343     * @see #NO_ID
19344     * @see #getId()
19345     * @see #findViewById(int)
19346     *
19347     * @param id a number used to identify the view
19348     *
19349     * @attr ref android.R.styleable#View_id
19350     */
19351    public void setId(@IdRes int id) {
19352        mID = id;
19353        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19354            mID = generateViewId();
19355        }
19356    }
19357
19358    /**
19359     * {@hide}
19360     *
19361     * @param isRoot true if the view belongs to the root namespace, false
19362     *        otherwise
19363     */
19364    public void setIsRootNamespace(boolean isRoot) {
19365        if (isRoot) {
19366            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19367        } else {
19368            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19369        }
19370    }
19371
19372    /**
19373     * {@hide}
19374     *
19375     * @return true if the view belongs to the root namespace, false otherwise
19376     */
19377    public boolean isRootNamespace() {
19378        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19379    }
19380
19381    /**
19382     * Returns this view's identifier.
19383     *
19384     * @return a positive integer used to identify the view or {@link #NO_ID}
19385     *         if the view has no ID
19386     *
19387     * @see #setId(int)
19388     * @see #findViewById(int)
19389     * @attr ref android.R.styleable#View_id
19390     */
19391    @IdRes
19392    @ViewDebug.CapturedViewProperty
19393    public int getId() {
19394        return mID;
19395    }
19396
19397    /**
19398     * Returns this view's tag.
19399     *
19400     * @return the Object stored in this view as a tag, or {@code null} if not
19401     *         set
19402     *
19403     * @see #setTag(Object)
19404     * @see #getTag(int)
19405     */
19406    @ViewDebug.ExportedProperty
19407    public Object getTag() {
19408        return mTag;
19409    }
19410
19411    /**
19412     * Sets the tag associated with this view. A tag can be used to mark
19413     * a view in its hierarchy and does not have to be unique within the
19414     * hierarchy. Tags can also be used to store data within a view without
19415     * resorting to another data structure.
19416     *
19417     * @param tag an Object to tag the view with
19418     *
19419     * @see #getTag()
19420     * @see #setTag(int, Object)
19421     */
19422    public void setTag(final Object tag) {
19423        mTag = tag;
19424    }
19425
19426    /**
19427     * Returns the tag associated with this view and the specified key.
19428     *
19429     * @param key The key identifying the tag
19430     *
19431     * @return the Object stored in this view as a tag, or {@code null} if not
19432     *         set
19433     *
19434     * @see #setTag(int, Object)
19435     * @see #getTag()
19436     */
19437    public Object getTag(int key) {
19438        if (mKeyedTags != null) return mKeyedTags.get(key);
19439        return null;
19440    }
19441
19442    /**
19443     * Sets a tag associated with this view and a key. A tag can be used
19444     * to mark a view in its hierarchy and does not have to be unique within
19445     * the hierarchy. Tags can also be used to store data within a view
19446     * without resorting to another data structure.
19447     *
19448     * The specified key should be an id declared in the resources of the
19449     * application to ensure it is unique (see the <a
19450     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
19451     * Keys identified as belonging to
19452     * the Android framework or not associated with any package will cause
19453     * an {@link IllegalArgumentException} to be thrown.
19454     *
19455     * @param key The key identifying the tag
19456     * @param tag An Object to tag the view with
19457     *
19458     * @throws IllegalArgumentException If they specified key is not valid
19459     *
19460     * @see #setTag(Object)
19461     * @see #getTag(int)
19462     */
19463    public void setTag(int key, final Object tag) {
19464        // If the package id is 0x00 or 0x01, it's either an undefined package
19465        // or a framework id
19466        if ((key >>> 24) < 2) {
19467            throw new IllegalArgumentException("The key must be an application-specific "
19468                    + "resource id.");
19469        }
19470
19471        setKeyedTag(key, tag);
19472    }
19473
19474    /**
19475     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
19476     * framework id.
19477     *
19478     * @hide
19479     */
19480    public void setTagInternal(int key, Object tag) {
19481        if ((key >>> 24) != 0x1) {
19482            throw new IllegalArgumentException("The key must be a framework-specific "
19483                    + "resource id.");
19484        }
19485
19486        setKeyedTag(key, tag);
19487    }
19488
19489    private void setKeyedTag(int key, Object tag) {
19490        if (mKeyedTags == null) {
19491            mKeyedTags = new SparseArray<Object>(2);
19492        }
19493
19494        mKeyedTags.put(key, tag);
19495    }
19496
19497    /**
19498     * Prints information about this view in the log output, with the tag
19499     * {@link #VIEW_LOG_TAG}.
19500     *
19501     * @hide
19502     */
19503    public void debug() {
19504        debug(0);
19505    }
19506
19507    /**
19508     * Prints information about this view in the log output, with the tag
19509     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
19510     * indentation defined by the <code>depth</code>.
19511     *
19512     * @param depth the indentation level
19513     *
19514     * @hide
19515     */
19516    protected void debug(int depth) {
19517        String output = debugIndent(depth - 1);
19518
19519        output += "+ " + this;
19520        int id = getId();
19521        if (id != -1) {
19522            output += " (id=" + id + ")";
19523        }
19524        Object tag = getTag();
19525        if (tag != null) {
19526            output += " (tag=" + tag + ")";
19527        }
19528        Log.d(VIEW_LOG_TAG, output);
19529
19530        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
19531            output = debugIndent(depth) + " FOCUSED";
19532            Log.d(VIEW_LOG_TAG, output);
19533        }
19534
19535        output = debugIndent(depth);
19536        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
19537                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
19538                + "} ";
19539        Log.d(VIEW_LOG_TAG, output);
19540
19541        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
19542                || mPaddingBottom != 0) {
19543            output = debugIndent(depth);
19544            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
19545                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
19546            Log.d(VIEW_LOG_TAG, output);
19547        }
19548
19549        output = debugIndent(depth);
19550        output += "mMeasureWidth=" + mMeasuredWidth +
19551                " mMeasureHeight=" + mMeasuredHeight;
19552        Log.d(VIEW_LOG_TAG, output);
19553
19554        output = debugIndent(depth);
19555        if (mLayoutParams == null) {
19556            output += "BAD! no layout params";
19557        } else {
19558            output = mLayoutParams.debug(output);
19559        }
19560        Log.d(VIEW_LOG_TAG, output);
19561
19562        output = debugIndent(depth);
19563        output += "flags={";
19564        output += View.printFlags(mViewFlags);
19565        output += "}";
19566        Log.d(VIEW_LOG_TAG, output);
19567
19568        output = debugIndent(depth);
19569        output += "privateFlags={";
19570        output += View.printPrivateFlags(mPrivateFlags);
19571        output += "}";
19572        Log.d(VIEW_LOG_TAG, output);
19573    }
19574
19575    /**
19576     * Creates a string of whitespaces used for indentation.
19577     *
19578     * @param depth the indentation level
19579     * @return a String containing (depth * 2 + 3) * 2 white spaces
19580     *
19581     * @hide
19582     */
19583    protected static String debugIndent(int depth) {
19584        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
19585        for (int i = 0; i < (depth * 2) + 3; i++) {
19586            spaces.append(' ').append(' ');
19587        }
19588        return spaces.toString();
19589    }
19590
19591    /**
19592     * <p>Return the offset of the widget's text baseline from the widget's top
19593     * boundary. If this widget does not support baseline alignment, this
19594     * method returns -1. </p>
19595     *
19596     * @return the offset of the baseline within the widget's bounds or -1
19597     *         if baseline alignment is not supported
19598     */
19599    @ViewDebug.ExportedProperty(category = "layout")
19600    public int getBaseline() {
19601        return -1;
19602    }
19603
19604    /**
19605     * Returns whether the view hierarchy is currently undergoing a layout pass. This
19606     * information is useful to avoid situations such as calling {@link #requestLayout()} during
19607     * a layout pass.
19608     *
19609     * @return whether the view hierarchy is currently undergoing a layout pass
19610     */
19611    public boolean isInLayout() {
19612        ViewRootImpl viewRoot = getViewRootImpl();
19613        return (viewRoot != null && viewRoot.isInLayout());
19614    }
19615
19616    /**
19617     * Call this when something has changed which has invalidated the
19618     * layout of this view. This will schedule a layout pass of the view
19619     * tree. This should not be called while the view hierarchy is currently in a layout
19620     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
19621     * end of the current layout pass (and then layout will run again) or after the current
19622     * frame is drawn and the next layout occurs.
19623     *
19624     * <p>Subclasses which override this method should call the superclass method to
19625     * handle possible request-during-layout errors correctly.</p>
19626     */
19627    @CallSuper
19628    public void requestLayout() {
19629        if (mMeasureCache != null) mMeasureCache.clear();
19630
19631        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
19632            // Only trigger request-during-layout logic if this is the view requesting it,
19633            // not the views in its parent hierarchy
19634            ViewRootImpl viewRoot = getViewRootImpl();
19635            if (viewRoot != null && viewRoot.isInLayout()) {
19636                if (!viewRoot.requestLayoutDuringLayout(this)) {
19637                    return;
19638                }
19639            }
19640            mAttachInfo.mViewRequestingLayout = this;
19641        }
19642
19643        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19644        mPrivateFlags |= PFLAG_INVALIDATED;
19645
19646        if (mParent != null && !mParent.isLayoutRequested()) {
19647            mParent.requestLayout();
19648        }
19649        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
19650            mAttachInfo.mViewRequestingLayout = null;
19651        }
19652    }
19653
19654    /**
19655     * Forces this view to be laid out during the next layout pass.
19656     * This method does not call requestLayout() or forceLayout()
19657     * on the parent.
19658     */
19659    public void forceLayout() {
19660        if (mMeasureCache != null) mMeasureCache.clear();
19661
19662        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19663        mPrivateFlags |= PFLAG_INVALIDATED;
19664    }
19665
19666    /**
19667     * <p>
19668     * This is called to find out how big a view should be. The parent
19669     * supplies constraint information in the width and height parameters.
19670     * </p>
19671     *
19672     * <p>
19673     * The actual measurement work of a view is performed in
19674     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
19675     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
19676     * </p>
19677     *
19678     *
19679     * @param widthMeasureSpec Horizontal space requirements as imposed by the
19680     *        parent
19681     * @param heightMeasureSpec Vertical space requirements as imposed by the
19682     *        parent
19683     *
19684     * @see #onMeasure(int, int)
19685     */
19686    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
19687        boolean optical = isLayoutModeOptical(this);
19688        if (optical != isLayoutModeOptical(mParent)) {
19689            Insets insets = getOpticalInsets();
19690            int oWidth  = insets.left + insets.right;
19691            int oHeight = insets.top  + insets.bottom;
19692            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
19693            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
19694        }
19695
19696        // Suppress sign extension for the low bytes
19697        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
19698        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
19699
19700        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19701
19702        // Optimize layout by avoiding an extra EXACTLY pass when the view is
19703        // already measured as the correct size. In API 23 and below, this
19704        // extra pass is required to make LinearLayout re-distribute weight.
19705        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
19706                || heightMeasureSpec != mOldHeightMeasureSpec;
19707        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
19708                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
19709        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
19710                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
19711        final boolean needsLayout = specChanged
19712                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
19713
19714        if (forceLayout || needsLayout) {
19715            // first clears the measured dimension flag
19716            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
19717
19718            resolveRtlPropertiesIfNeeded();
19719
19720            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
19721            if (cacheIndex < 0 || sIgnoreMeasureCache) {
19722                // measure ourselves, this should set the measured dimension flag back
19723                onMeasure(widthMeasureSpec, heightMeasureSpec);
19724                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19725            } else {
19726                long value = mMeasureCache.valueAt(cacheIndex);
19727                // Casting a long to int drops the high 32 bits, no mask needed
19728                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
19729                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19730            }
19731
19732            // flag not set, setMeasuredDimension() was not invoked, we raise
19733            // an exception to warn the developer
19734            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
19735                throw new IllegalStateException("View with id " + getId() + ": "
19736                        + getClass().getName() + "#onMeasure() did not set the"
19737                        + " measured dimension by calling"
19738                        + " setMeasuredDimension()");
19739            }
19740
19741            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
19742        }
19743
19744        mOldWidthMeasureSpec = widthMeasureSpec;
19745        mOldHeightMeasureSpec = heightMeasureSpec;
19746
19747        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
19748                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
19749    }
19750
19751    /**
19752     * <p>
19753     * Measure the view and its content to determine the measured width and the
19754     * measured height. This method is invoked by {@link #measure(int, int)} and
19755     * should be overridden by subclasses to provide accurate and efficient
19756     * measurement of their contents.
19757     * </p>
19758     *
19759     * <p>
19760     * <strong>CONTRACT:</strong> When overriding this method, you
19761     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
19762     * measured width and height of this view. Failure to do so will trigger an
19763     * <code>IllegalStateException</code>, thrown by
19764     * {@link #measure(int, int)}. Calling the superclass'
19765     * {@link #onMeasure(int, int)} is a valid use.
19766     * </p>
19767     *
19768     * <p>
19769     * The base class implementation of measure defaults to the background size,
19770     * unless a larger size is allowed by the MeasureSpec. Subclasses should
19771     * override {@link #onMeasure(int, int)} to provide better measurements of
19772     * their content.
19773     * </p>
19774     *
19775     * <p>
19776     * If this method is overridden, it is the subclass's responsibility to make
19777     * sure the measured height and width are at least the view's minimum height
19778     * and width ({@link #getSuggestedMinimumHeight()} and
19779     * {@link #getSuggestedMinimumWidth()}).
19780     * </p>
19781     *
19782     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
19783     *                         The requirements are encoded with
19784     *                         {@link android.view.View.MeasureSpec}.
19785     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
19786     *                         The requirements are encoded with
19787     *                         {@link android.view.View.MeasureSpec}.
19788     *
19789     * @see #getMeasuredWidth()
19790     * @see #getMeasuredHeight()
19791     * @see #setMeasuredDimension(int, int)
19792     * @see #getSuggestedMinimumHeight()
19793     * @see #getSuggestedMinimumWidth()
19794     * @see android.view.View.MeasureSpec#getMode(int)
19795     * @see android.view.View.MeasureSpec#getSize(int)
19796     */
19797    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
19798        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
19799                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
19800    }
19801
19802    /**
19803     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
19804     * measured width and measured height. Failing to do so will trigger an
19805     * exception at measurement time.</p>
19806     *
19807     * @param measuredWidth The measured width of this view.  May be a complex
19808     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19809     * {@link #MEASURED_STATE_TOO_SMALL}.
19810     * @param measuredHeight The measured height of this view.  May be a complex
19811     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19812     * {@link #MEASURED_STATE_TOO_SMALL}.
19813     */
19814    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
19815        boolean optical = isLayoutModeOptical(this);
19816        if (optical != isLayoutModeOptical(mParent)) {
19817            Insets insets = getOpticalInsets();
19818            int opticalWidth  = insets.left + insets.right;
19819            int opticalHeight = insets.top  + insets.bottom;
19820
19821            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
19822            measuredHeight += optical ? opticalHeight : -opticalHeight;
19823        }
19824        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
19825    }
19826
19827    /**
19828     * Sets the measured dimension without extra processing for things like optical bounds.
19829     * Useful for reapplying consistent values that have already been cooked with adjustments
19830     * for optical bounds, etc. such as those from the measurement cache.
19831     *
19832     * @param measuredWidth The measured width of this view.  May be a complex
19833     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19834     * {@link #MEASURED_STATE_TOO_SMALL}.
19835     * @param measuredHeight The measured height of this view.  May be a complex
19836     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19837     * {@link #MEASURED_STATE_TOO_SMALL}.
19838     */
19839    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
19840        mMeasuredWidth = measuredWidth;
19841        mMeasuredHeight = measuredHeight;
19842
19843        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
19844    }
19845
19846    /**
19847     * Merge two states as returned by {@link #getMeasuredState()}.
19848     * @param curState The current state as returned from a view or the result
19849     * of combining multiple views.
19850     * @param newState The new view state to combine.
19851     * @return Returns a new integer reflecting the combination of the two
19852     * states.
19853     */
19854    public static int combineMeasuredStates(int curState, int newState) {
19855        return curState | newState;
19856    }
19857
19858    /**
19859     * Version of {@link #resolveSizeAndState(int, int, int)}
19860     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
19861     */
19862    public static int resolveSize(int size, int measureSpec) {
19863        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
19864    }
19865
19866    /**
19867     * Utility to reconcile a desired size and state, with constraints imposed
19868     * by a MeasureSpec. Will take the desired size, unless a different size
19869     * is imposed by the constraints. The returned value is a compound integer,
19870     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
19871     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
19872     * resulting size is smaller than the size the view wants to be.
19873     *
19874     * @param size How big the view wants to be.
19875     * @param measureSpec Constraints imposed by the parent.
19876     * @param childMeasuredState Size information bit mask for the view's
19877     *                           children.
19878     * @return Size information bit mask as defined by
19879     *         {@link #MEASURED_SIZE_MASK} and
19880     *         {@link #MEASURED_STATE_TOO_SMALL}.
19881     */
19882    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
19883        final int specMode = MeasureSpec.getMode(measureSpec);
19884        final int specSize = MeasureSpec.getSize(measureSpec);
19885        final int result;
19886        switch (specMode) {
19887            case MeasureSpec.AT_MOST:
19888                if (specSize < size) {
19889                    result = specSize | MEASURED_STATE_TOO_SMALL;
19890                } else {
19891                    result = size;
19892                }
19893                break;
19894            case MeasureSpec.EXACTLY:
19895                result = specSize;
19896                break;
19897            case MeasureSpec.UNSPECIFIED:
19898            default:
19899                result = size;
19900        }
19901        return result | (childMeasuredState & MEASURED_STATE_MASK);
19902    }
19903
19904    /**
19905     * Utility to return a default size. Uses the supplied size if the
19906     * MeasureSpec imposed no constraints. Will get larger if allowed
19907     * by the MeasureSpec.
19908     *
19909     * @param size Default size for this view
19910     * @param measureSpec Constraints imposed by the parent
19911     * @return The size this view should be.
19912     */
19913    public static int getDefaultSize(int size, int measureSpec) {
19914        int result = size;
19915        int specMode = MeasureSpec.getMode(measureSpec);
19916        int specSize = MeasureSpec.getSize(measureSpec);
19917
19918        switch (specMode) {
19919        case MeasureSpec.UNSPECIFIED:
19920            result = size;
19921            break;
19922        case MeasureSpec.AT_MOST:
19923        case MeasureSpec.EXACTLY:
19924            result = specSize;
19925            break;
19926        }
19927        return result;
19928    }
19929
19930    /**
19931     * Returns the suggested minimum height that the view should use. This
19932     * returns the maximum of the view's minimum height
19933     * and the background's minimum height
19934     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
19935     * <p>
19936     * When being used in {@link #onMeasure(int, int)}, the caller should still
19937     * ensure the returned height is within the requirements of the parent.
19938     *
19939     * @return The suggested minimum height of the view.
19940     */
19941    protected int getSuggestedMinimumHeight() {
19942        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
19943
19944    }
19945
19946    /**
19947     * Returns the suggested minimum width that the view should use. This
19948     * returns the maximum of the view's minimum width
19949     * and the background's minimum width
19950     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
19951     * <p>
19952     * When being used in {@link #onMeasure(int, int)}, the caller should still
19953     * ensure the returned width is within the requirements of the parent.
19954     *
19955     * @return The suggested minimum width of the view.
19956     */
19957    protected int getSuggestedMinimumWidth() {
19958        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
19959    }
19960
19961    /**
19962     * Returns the minimum height of the view.
19963     *
19964     * @return the minimum height the view will try to be.
19965     *
19966     * @see #setMinimumHeight(int)
19967     *
19968     * @attr ref android.R.styleable#View_minHeight
19969     */
19970    public int getMinimumHeight() {
19971        return mMinHeight;
19972    }
19973
19974    /**
19975     * Sets the minimum height of the view. It is not guaranteed the view will
19976     * be able to achieve this minimum height (for example, if its parent layout
19977     * constrains it with less available height).
19978     *
19979     * @param minHeight The minimum height the view will try to be.
19980     *
19981     * @see #getMinimumHeight()
19982     *
19983     * @attr ref android.R.styleable#View_minHeight
19984     */
19985    @RemotableViewMethod
19986    public void setMinimumHeight(int minHeight) {
19987        mMinHeight = minHeight;
19988        requestLayout();
19989    }
19990
19991    /**
19992     * Returns the minimum width of the view.
19993     *
19994     * @return the minimum width the view will try to be.
19995     *
19996     * @see #setMinimumWidth(int)
19997     *
19998     * @attr ref android.R.styleable#View_minWidth
19999     */
20000    public int getMinimumWidth() {
20001        return mMinWidth;
20002    }
20003
20004    /**
20005     * Sets the minimum width of the view. It is not guaranteed the view will
20006     * be able to achieve this minimum width (for example, if its parent layout
20007     * constrains it with less available width).
20008     *
20009     * @param minWidth The minimum width the view will try to be.
20010     *
20011     * @see #getMinimumWidth()
20012     *
20013     * @attr ref android.R.styleable#View_minWidth
20014     */
20015    public void setMinimumWidth(int minWidth) {
20016        mMinWidth = minWidth;
20017        requestLayout();
20018
20019    }
20020
20021    /**
20022     * Get the animation currently associated with this view.
20023     *
20024     * @return The animation that is currently playing or
20025     *         scheduled to play for this view.
20026     */
20027    public Animation getAnimation() {
20028        return mCurrentAnimation;
20029    }
20030
20031    /**
20032     * Start the specified animation now.
20033     *
20034     * @param animation the animation to start now
20035     */
20036    public void startAnimation(Animation animation) {
20037        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20038        setAnimation(animation);
20039        invalidateParentCaches();
20040        invalidate(true);
20041    }
20042
20043    /**
20044     * Cancels any animations for this view.
20045     */
20046    public void clearAnimation() {
20047        if (mCurrentAnimation != null) {
20048            mCurrentAnimation.detach();
20049        }
20050        mCurrentAnimation = null;
20051        invalidateParentIfNeeded();
20052    }
20053
20054    /**
20055     * Sets the next animation to play for this view.
20056     * If you want the animation to play immediately, use
20057     * {@link #startAnimation(android.view.animation.Animation)} instead.
20058     * This method provides allows fine-grained
20059     * control over the start time and invalidation, but you
20060     * must make sure that 1) the animation has a start time set, and
20061     * 2) the view's parent (which controls animations on its children)
20062     * will be invalidated when the animation is supposed to
20063     * start.
20064     *
20065     * @param animation The next animation, or null.
20066     */
20067    public void setAnimation(Animation animation) {
20068        mCurrentAnimation = animation;
20069
20070        if (animation != null) {
20071            // If the screen is off assume the animation start time is now instead of
20072            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20073            // would cause the animation to start when the screen turns back on
20074            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20075                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20076                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20077            }
20078            animation.reset();
20079        }
20080    }
20081
20082    /**
20083     * Invoked by a parent ViewGroup to notify the start of the animation
20084     * currently associated with this view. If you override this method,
20085     * always call super.onAnimationStart();
20086     *
20087     * @see #setAnimation(android.view.animation.Animation)
20088     * @see #getAnimation()
20089     */
20090    @CallSuper
20091    protected void onAnimationStart() {
20092        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20093    }
20094
20095    /**
20096     * Invoked by a parent ViewGroup to notify the end of the animation
20097     * currently associated with this view. If you override this method,
20098     * always call super.onAnimationEnd();
20099     *
20100     * @see #setAnimation(android.view.animation.Animation)
20101     * @see #getAnimation()
20102     */
20103    @CallSuper
20104    protected void onAnimationEnd() {
20105        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20106    }
20107
20108    /**
20109     * Invoked if there is a Transform that involves alpha. Subclass that can
20110     * draw themselves with the specified alpha should return true, and then
20111     * respect that alpha when their onDraw() is called. If this returns false
20112     * then the view may be redirected to draw into an offscreen buffer to
20113     * fulfill the request, which will look fine, but may be slower than if the
20114     * subclass handles it internally. The default implementation returns false.
20115     *
20116     * @param alpha The alpha (0..255) to apply to the view's drawing
20117     * @return true if the view can draw with the specified alpha.
20118     */
20119    protected boolean onSetAlpha(int alpha) {
20120        return false;
20121    }
20122
20123    /**
20124     * This is used by the RootView to perform an optimization when
20125     * the view hierarchy contains one or several SurfaceView.
20126     * SurfaceView is always considered transparent, but its children are not,
20127     * therefore all View objects remove themselves from the global transparent
20128     * region (passed as a parameter to this function).
20129     *
20130     * @param region The transparent region for this ViewAncestor (window).
20131     *
20132     * @return Returns true if the effective visibility of the view at this
20133     * point is opaque, regardless of the transparent region; returns false
20134     * if it is possible for underlying windows to be seen behind the view.
20135     *
20136     * {@hide}
20137     */
20138    public boolean gatherTransparentRegion(Region region) {
20139        final AttachInfo attachInfo = mAttachInfo;
20140        if (region != null && attachInfo != null) {
20141            final int pflags = mPrivateFlags;
20142            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20143                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20144                // remove it from the transparent region.
20145                final int[] location = attachInfo.mTransparentLocation;
20146                getLocationInWindow(location);
20147                region.op(location[0], location[1], location[0] + mRight - mLeft,
20148                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
20149            } else {
20150                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20151                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20152                    // the background drawable's non-transparent parts from this transparent region.
20153                    applyDrawableToTransparentRegion(mBackground, region);
20154                }
20155                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20156                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20157                    // Similarly, we remove the foreground drawable's non-transparent parts.
20158                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20159                }
20160            }
20161        }
20162        return true;
20163    }
20164
20165    /**
20166     * Play a sound effect for this view.
20167     *
20168     * <p>The framework will play sound effects for some built in actions, such as
20169     * clicking, but you may wish to play these effects in your widget,
20170     * for instance, for internal navigation.
20171     *
20172     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20173     * {@link #isSoundEffectsEnabled()} is true.
20174     *
20175     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20176     */
20177    public void playSoundEffect(int soundConstant) {
20178        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20179            return;
20180        }
20181        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20182    }
20183
20184    /**
20185     * BZZZTT!!1!
20186     *
20187     * <p>Provide haptic feedback to the user for this view.
20188     *
20189     * <p>The framework will provide haptic feedback for some built in actions,
20190     * such as long presses, but you may wish to provide feedback for your
20191     * own widget.
20192     *
20193     * <p>The feedback will only be performed if
20194     * {@link #isHapticFeedbackEnabled()} is true.
20195     *
20196     * @param feedbackConstant One of the constants defined in
20197     * {@link HapticFeedbackConstants}
20198     */
20199    public boolean performHapticFeedback(int feedbackConstant) {
20200        return performHapticFeedback(feedbackConstant, 0);
20201    }
20202
20203    /**
20204     * BZZZTT!!1!
20205     *
20206     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20207     *
20208     * @param feedbackConstant One of the constants defined in
20209     * {@link HapticFeedbackConstants}
20210     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20211     */
20212    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20213        if (mAttachInfo == null) {
20214            return false;
20215        }
20216        //noinspection SimplifiableIfStatement
20217        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20218                && !isHapticFeedbackEnabled()) {
20219            return false;
20220        }
20221        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20222                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20223    }
20224
20225    /**
20226     * Request that the visibility of the status bar or other screen/window
20227     * decorations be changed.
20228     *
20229     * <p>This method is used to put the over device UI into temporary modes
20230     * where the user's attention is focused more on the application content,
20231     * by dimming or hiding surrounding system affordances.  This is typically
20232     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20233     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20234     * to be placed behind the action bar (and with these flags other system
20235     * affordances) so that smooth transitions between hiding and showing them
20236     * can be done.
20237     *
20238     * <p>Two representative examples of the use of system UI visibility is
20239     * implementing a content browsing application (like a magazine reader)
20240     * and a video playing application.
20241     *
20242     * <p>The first code shows a typical implementation of a View in a content
20243     * browsing application.  In this implementation, the application goes
20244     * into a content-oriented mode by hiding the status bar and action bar,
20245     * and putting the navigation elements into lights out mode.  The user can
20246     * then interact with content while in this mode.  Such an application should
20247     * provide an easy way for the user to toggle out of the mode (such as to
20248     * check information in the status bar or access notifications).  In the
20249     * implementation here, this is done simply by tapping on the content.
20250     *
20251     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20252     *      content}
20253     *
20254     * <p>This second code sample shows a typical implementation of a View
20255     * in a video playing application.  In this situation, while the video is
20256     * playing the application would like to go into a complete full-screen mode,
20257     * to use as much of the display as possible for the video.  When in this state
20258     * the user can not interact with the application; the system intercepts
20259     * touching on the screen to pop the UI out of full screen mode.  See
20260     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20261     *
20262     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20263     *      content}
20264     *
20265     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20266     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20267     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20268     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20269     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20270     */
20271    public void setSystemUiVisibility(int visibility) {
20272        if (visibility != mSystemUiVisibility) {
20273            mSystemUiVisibility = visibility;
20274            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20275                mParent.recomputeViewAttributes(this);
20276            }
20277        }
20278    }
20279
20280    /**
20281     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20282     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20283     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20284     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20285     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20286     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20287     */
20288    public int getSystemUiVisibility() {
20289        return mSystemUiVisibility;
20290    }
20291
20292    /**
20293     * Returns the current system UI visibility that is currently set for
20294     * the entire window.  This is the combination of the
20295     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20296     * views in the window.
20297     */
20298    public int getWindowSystemUiVisibility() {
20299        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20300    }
20301
20302    /**
20303     * Override to find out when the window's requested system UI visibility
20304     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20305     * This is different from the callbacks received through
20306     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20307     * in that this is only telling you about the local request of the window,
20308     * not the actual values applied by the system.
20309     */
20310    public void onWindowSystemUiVisibilityChanged(int visible) {
20311    }
20312
20313    /**
20314     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20315     * the view hierarchy.
20316     */
20317    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20318        onWindowSystemUiVisibilityChanged(visible);
20319    }
20320
20321    /**
20322     * Set a listener to receive callbacks when the visibility of the system bar changes.
20323     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20324     */
20325    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20326        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20327        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20328            mParent.recomputeViewAttributes(this);
20329        }
20330    }
20331
20332    /**
20333     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20334     * the view hierarchy.
20335     */
20336    public void dispatchSystemUiVisibilityChanged(int visibility) {
20337        ListenerInfo li = mListenerInfo;
20338        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20339            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20340                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20341        }
20342    }
20343
20344    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20345        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20346        if (val != mSystemUiVisibility) {
20347            setSystemUiVisibility(val);
20348            return true;
20349        }
20350        return false;
20351    }
20352
20353    /** @hide */
20354    public void setDisabledSystemUiVisibility(int flags) {
20355        if (mAttachInfo != null) {
20356            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20357                mAttachInfo.mDisabledSystemUiVisibility = flags;
20358                if (mParent != null) {
20359                    mParent.recomputeViewAttributes(this);
20360                }
20361            }
20362        }
20363    }
20364
20365    /**
20366     * Creates an image that the system displays during the drag and drop
20367     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20368     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20369     * appearance as the given View. The default also positions the center of the drag shadow
20370     * directly under the touch point. If no View is provided (the constructor with no parameters
20371     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20372     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20373     * default is an invisible drag shadow.
20374     * <p>
20375     * You are not required to use the View you provide to the constructor as the basis of the
20376     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20377     * anything you want as the drag shadow.
20378     * </p>
20379     * <p>
20380     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20381     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20382     *  size and position of the drag shadow. It uses this data to construct a
20383     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20384     *  so that your application can draw the shadow image in the Canvas.
20385     * </p>
20386     *
20387     * <div class="special reference">
20388     * <h3>Developer Guides</h3>
20389     * <p>For a guide to implementing drag and drop features, read the
20390     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20391     * </div>
20392     */
20393    public static class DragShadowBuilder {
20394        private final WeakReference<View> mView;
20395
20396        /**
20397         * Constructs a shadow image builder based on a View. By default, the resulting drag
20398         * shadow will have the same appearance and dimensions as the View, with the touch point
20399         * over the center of the View.
20400         * @param view A View. Any View in scope can be used.
20401         */
20402        public DragShadowBuilder(View view) {
20403            mView = new WeakReference<View>(view);
20404        }
20405
20406        /**
20407         * Construct a shadow builder object with no associated View.  This
20408         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20409         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20410         * to supply the drag shadow's dimensions and appearance without
20411         * reference to any View object. If they are not overridden, then the result is an
20412         * invisible drag shadow.
20413         */
20414        public DragShadowBuilder() {
20415            mView = new WeakReference<View>(null);
20416        }
20417
20418        /**
20419         * Returns the View object that had been passed to the
20420         * {@link #View.DragShadowBuilder(View)}
20421         * constructor.  If that View parameter was {@code null} or if the
20422         * {@link #View.DragShadowBuilder()}
20423         * constructor was used to instantiate the builder object, this method will return
20424         * null.
20425         *
20426         * @return The View object associate with this builder object.
20427         */
20428        @SuppressWarnings({"JavadocReference"})
20429        final public View getView() {
20430            return mView.get();
20431        }
20432
20433        /**
20434         * Provides the metrics for the shadow image. These include the dimensions of
20435         * the shadow image, and the point within that shadow that should
20436         * be centered under the touch location while dragging.
20437         * <p>
20438         * The default implementation sets the dimensions of the shadow to be the
20439         * same as the dimensions of the View itself and centers the shadow under
20440         * the touch point.
20441         * </p>
20442         *
20443         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
20444         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
20445         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
20446         * image.
20447         *
20448         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
20449         * shadow image that should be underneath the touch point during the drag and drop
20450         * operation. Your application must set {@link android.graphics.Point#x} to the
20451         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
20452         */
20453        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
20454            final View view = mView.get();
20455            if (view != null) {
20456                outShadowSize.set(view.getWidth(), view.getHeight());
20457                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
20458            } else {
20459                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
20460            }
20461        }
20462
20463        /**
20464         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
20465         * based on the dimensions it received from the
20466         * {@link #onProvideShadowMetrics(Point, Point)} callback.
20467         *
20468         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
20469         */
20470        public void onDrawShadow(Canvas canvas) {
20471            final View view = mView.get();
20472            if (view != null) {
20473                view.draw(canvas);
20474            } else {
20475                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
20476            }
20477        }
20478    }
20479
20480    /**
20481     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
20482     * startDragAndDrop()} for newer platform versions.
20483     */
20484    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
20485                                   Object myLocalState, int flags) {
20486        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
20487    }
20488
20489    /**
20490     * Starts a drag and drop operation. When your application calls this method, it passes a
20491     * {@link android.view.View.DragShadowBuilder} object to the system. The
20492     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
20493     * to get metrics for the drag shadow, and then calls the object's
20494     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
20495     * <p>
20496     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
20497     *  drag events to all the View objects in your application that are currently visible. It does
20498     *  this either by calling the View object's drag listener (an implementation of
20499     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
20500     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
20501     *  Both are passed a {@link android.view.DragEvent} object that has a
20502     *  {@link android.view.DragEvent#getAction()} value of
20503     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
20504     * </p>
20505     * <p>
20506     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
20507     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
20508     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
20509     * to the View the user selected for dragging.
20510     * </p>
20511     * @param data A {@link android.content.ClipData} object pointing to the data to be
20512     * transferred by the drag and drop operation.
20513     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20514     * drag shadow.
20515     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
20516     * drop operation. This Object is put into every DragEvent object sent by the system during the
20517     * current drag.
20518     * <p>
20519     * myLocalState is a lightweight mechanism for the sending information from the dragged View
20520     * to the target Views. For example, it can contain flags that differentiate between a
20521     * a copy operation and a move operation.
20522     * </p>
20523     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
20524     * so the parameter should be set to 0.
20525     * @return {@code true} if the method completes successfully, or
20526     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
20527     * do a drag, and so no drag operation is in progress.
20528     */
20529    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
20530            Object myLocalState, int flags) {
20531        if (ViewDebug.DEBUG_DRAG) {
20532            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
20533        }
20534        boolean okay = false;
20535
20536        Point shadowSize = new Point();
20537        Point shadowTouchPoint = new Point();
20538        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
20539
20540        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
20541                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
20542            throw new IllegalStateException("Drag shadow dimensions must not be negative");
20543        }
20544
20545        if (ViewDebug.DEBUG_DRAG) {
20546            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
20547                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
20548        }
20549        if (mAttachInfo.mDragSurface != null) {
20550            mAttachInfo.mDragSurface.release();
20551        }
20552        mAttachInfo.mDragSurface = new Surface();
20553        try {
20554            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
20555                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
20556            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
20557                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
20558            if (mAttachInfo.mDragToken != null) {
20559                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20560                try {
20561                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20562                    shadowBuilder.onDrawShadow(canvas);
20563                } finally {
20564                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20565                }
20566
20567                final ViewRootImpl root = getViewRootImpl();
20568
20569                // Cache the local state object for delivery with DragEvents
20570                root.setLocalDragState(myLocalState);
20571
20572                // repurpose 'shadowSize' for the last touch point
20573                root.getLastTouchPoint(shadowSize);
20574
20575                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
20576                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
20577                        shadowTouchPoint.x, shadowTouchPoint.y, data);
20578                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
20579            }
20580        } catch (Exception e) {
20581            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
20582            mAttachInfo.mDragSurface.destroy();
20583            mAttachInfo.mDragSurface = null;
20584        }
20585
20586        return okay;
20587    }
20588
20589    /**
20590     * Cancels an ongoing drag and drop operation.
20591     * <p>
20592     * A {@link android.view.DragEvent} object with
20593     * {@link android.view.DragEvent#getAction()} value of
20594     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
20595     * {@link android.view.DragEvent#getResult()} value of {@code false}
20596     * will be sent to every
20597     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
20598     * even if they are not currently visible.
20599     * </p>
20600     * <p>
20601     * This method can be called on any View in the same window as the View on which
20602     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
20603     * was called.
20604     * </p>
20605     */
20606    public final void cancelDragAndDrop() {
20607        if (ViewDebug.DEBUG_DRAG) {
20608            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
20609        }
20610        if (mAttachInfo.mDragToken != null) {
20611            try {
20612                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
20613            } catch (Exception e) {
20614                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
20615            }
20616            mAttachInfo.mDragToken = null;
20617        } else {
20618            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
20619        }
20620    }
20621
20622    /**
20623     * Updates the drag shadow for the ongoing drag and drop operation.
20624     *
20625     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20626     * new drag shadow.
20627     */
20628    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
20629        if (ViewDebug.DEBUG_DRAG) {
20630            Log.d(VIEW_LOG_TAG, "updateDragShadow");
20631        }
20632        if (mAttachInfo.mDragToken != null) {
20633            try {
20634                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20635                try {
20636                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20637                    shadowBuilder.onDrawShadow(canvas);
20638                } finally {
20639                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20640                }
20641            } catch (Exception e) {
20642                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
20643            }
20644        } else {
20645            Log.e(VIEW_LOG_TAG, "No active drag");
20646        }
20647    }
20648
20649    /**
20650     * Starts a move from {startX, startY}, the amount of the movement will be the offset
20651     * between {startX, startY} and the new cursor positon.
20652     * @param startX horizontal coordinate where the move started.
20653     * @param startY vertical coordinate where the move started.
20654     * @return whether moving was started successfully.
20655     * @hide
20656     */
20657    public final boolean startMovingTask(float startX, float startY) {
20658        if (ViewDebug.DEBUG_POSITIONING) {
20659            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
20660        }
20661        try {
20662            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
20663        } catch (RemoteException e) {
20664            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
20665        }
20666        return false;
20667    }
20668
20669    /**
20670     * Handles drag events sent by the system following a call to
20671     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
20672     * startDragAndDrop()}.
20673     *<p>
20674     * When the system calls this method, it passes a
20675     * {@link android.view.DragEvent} object. A call to
20676     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
20677     * in DragEvent. The method uses these to determine what is happening in the drag and drop
20678     * operation.
20679     * @param event The {@link android.view.DragEvent} sent by the system.
20680     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
20681     * in DragEvent, indicating the type of drag event represented by this object.
20682     * @return {@code true} if the method was successful, otherwise {@code false}.
20683     * <p>
20684     *  The method should return {@code true} in response to an action type of
20685     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
20686     *  operation.
20687     * </p>
20688     * <p>
20689     *  The method should also return {@code true} in response to an action type of
20690     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
20691     *  {@code false} if it didn't.
20692     * </p>
20693     */
20694    public boolean onDragEvent(DragEvent event) {
20695        return false;
20696    }
20697
20698    /**
20699     * Detects if this View is enabled and has a drag event listener.
20700     * If both are true, then it calls the drag event listener with the
20701     * {@link android.view.DragEvent} it received. If the drag event listener returns
20702     * {@code true}, then dispatchDragEvent() returns {@code true}.
20703     * <p>
20704     * For all other cases, the method calls the
20705     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
20706     * method and returns its result.
20707     * </p>
20708     * <p>
20709     * This ensures that a drag event is always consumed, even if the View does not have a drag
20710     * event listener. However, if the View has a listener and the listener returns true, then
20711     * onDragEvent() is not called.
20712     * </p>
20713     */
20714    public boolean dispatchDragEvent(DragEvent event) {
20715        ListenerInfo li = mListenerInfo;
20716        //noinspection SimplifiableIfStatement
20717        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
20718                && li.mOnDragListener.onDrag(this, event)) {
20719            return true;
20720        }
20721        return onDragEvent(event);
20722    }
20723
20724    boolean canAcceptDrag() {
20725        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
20726    }
20727
20728    /**
20729     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
20730     * it is ever exposed at all.
20731     * @hide
20732     */
20733    public void onCloseSystemDialogs(String reason) {
20734    }
20735
20736    /**
20737     * Given a Drawable whose bounds have been set to draw into this view,
20738     * update a Region being computed for
20739     * {@link #gatherTransparentRegion(android.graphics.Region)} so
20740     * that any non-transparent parts of the Drawable are removed from the
20741     * given transparent region.
20742     *
20743     * @param dr The Drawable whose transparency is to be applied to the region.
20744     * @param region A Region holding the current transparency information,
20745     * where any parts of the region that are set are considered to be
20746     * transparent.  On return, this region will be modified to have the
20747     * transparency information reduced by the corresponding parts of the
20748     * Drawable that are not transparent.
20749     * {@hide}
20750     */
20751    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
20752        if (DBG) {
20753            Log.i("View", "Getting transparent region for: " + this);
20754        }
20755        final Region r = dr.getTransparentRegion();
20756        final Rect db = dr.getBounds();
20757        final AttachInfo attachInfo = mAttachInfo;
20758        if (r != null && attachInfo != null) {
20759            final int w = getRight()-getLeft();
20760            final int h = getBottom()-getTop();
20761            if (db.left > 0) {
20762                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
20763                r.op(0, 0, db.left, h, Region.Op.UNION);
20764            }
20765            if (db.right < w) {
20766                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
20767                r.op(db.right, 0, w, h, Region.Op.UNION);
20768            }
20769            if (db.top > 0) {
20770                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
20771                r.op(0, 0, w, db.top, Region.Op.UNION);
20772            }
20773            if (db.bottom < h) {
20774                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
20775                r.op(0, db.bottom, w, h, Region.Op.UNION);
20776            }
20777            final int[] location = attachInfo.mTransparentLocation;
20778            getLocationInWindow(location);
20779            r.translate(location[0], location[1]);
20780            region.op(r, Region.Op.INTERSECT);
20781        } else {
20782            region.op(db, Region.Op.DIFFERENCE);
20783        }
20784    }
20785
20786    private void checkForLongClick(int delayOffset, float x, float y) {
20787        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
20788            mHasPerformedLongPress = false;
20789
20790            if (mPendingCheckForLongPress == null) {
20791                mPendingCheckForLongPress = new CheckForLongPress();
20792            }
20793            mPendingCheckForLongPress.setAnchor(x, y);
20794            mPendingCheckForLongPress.rememberWindowAttachCount();
20795            postDelayed(mPendingCheckForLongPress,
20796                    ViewConfiguration.getLongPressTimeout() - delayOffset);
20797        }
20798    }
20799
20800    /**
20801     * Inflate a view from an XML resource.  This convenience method wraps the {@link
20802     * LayoutInflater} class, which provides a full range of options for view inflation.
20803     *
20804     * @param context The Context object for your activity or application.
20805     * @param resource The resource ID to inflate
20806     * @param root A view group that will be the parent.  Used to properly inflate the
20807     * layout_* parameters.
20808     * @see LayoutInflater
20809     */
20810    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
20811        LayoutInflater factory = LayoutInflater.from(context);
20812        return factory.inflate(resource, root);
20813    }
20814
20815    /**
20816     * Scroll the view with standard behavior for scrolling beyond the normal
20817     * content boundaries. Views that call this method should override
20818     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
20819     * results of an over-scroll operation.
20820     *
20821     * Views can use this method to handle any touch or fling-based scrolling.
20822     *
20823     * @param deltaX Change in X in pixels
20824     * @param deltaY Change in Y in pixels
20825     * @param scrollX Current X scroll value in pixels before applying deltaX
20826     * @param scrollY Current Y scroll value in pixels before applying deltaY
20827     * @param scrollRangeX Maximum content scroll range along the X axis
20828     * @param scrollRangeY Maximum content scroll range along the Y axis
20829     * @param maxOverScrollX Number of pixels to overscroll by in either direction
20830     *          along the X axis.
20831     * @param maxOverScrollY Number of pixels to overscroll by in either direction
20832     *          along the Y axis.
20833     * @param isTouchEvent true if this scroll operation is the result of a touch event.
20834     * @return true if scrolling was clamped to an over-scroll boundary along either
20835     *          axis, false otherwise.
20836     */
20837    @SuppressWarnings({"UnusedParameters"})
20838    protected boolean overScrollBy(int deltaX, int deltaY,
20839            int scrollX, int scrollY,
20840            int scrollRangeX, int scrollRangeY,
20841            int maxOverScrollX, int maxOverScrollY,
20842            boolean isTouchEvent) {
20843        final int overScrollMode = mOverScrollMode;
20844        final boolean canScrollHorizontal =
20845                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
20846        final boolean canScrollVertical =
20847                computeVerticalScrollRange() > computeVerticalScrollExtent();
20848        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
20849                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
20850        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
20851                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
20852
20853        int newScrollX = scrollX + deltaX;
20854        if (!overScrollHorizontal) {
20855            maxOverScrollX = 0;
20856        }
20857
20858        int newScrollY = scrollY + deltaY;
20859        if (!overScrollVertical) {
20860            maxOverScrollY = 0;
20861        }
20862
20863        // Clamp values if at the limits and record
20864        final int left = -maxOverScrollX;
20865        final int right = maxOverScrollX + scrollRangeX;
20866        final int top = -maxOverScrollY;
20867        final int bottom = maxOverScrollY + scrollRangeY;
20868
20869        boolean clampedX = false;
20870        if (newScrollX > right) {
20871            newScrollX = right;
20872            clampedX = true;
20873        } else if (newScrollX < left) {
20874            newScrollX = left;
20875            clampedX = true;
20876        }
20877
20878        boolean clampedY = false;
20879        if (newScrollY > bottom) {
20880            newScrollY = bottom;
20881            clampedY = true;
20882        } else if (newScrollY < top) {
20883            newScrollY = top;
20884            clampedY = true;
20885        }
20886
20887        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
20888
20889        return clampedX || clampedY;
20890    }
20891
20892    /**
20893     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
20894     * respond to the results of an over-scroll operation.
20895     *
20896     * @param scrollX New X scroll value in pixels
20897     * @param scrollY New Y scroll value in pixels
20898     * @param clampedX True if scrollX was clamped to an over-scroll boundary
20899     * @param clampedY True if scrollY was clamped to an over-scroll boundary
20900     */
20901    protected void onOverScrolled(int scrollX, int scrollY,
20902            boolean clampedX, boolean clampedY) {
20903        // Intentionally empty.
20904    }
20905
20906    /**
20907     * Returns the over-scroll mode for this view. The result will be
20908     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20909     * (allow over-scrolling only if the view content is larger than the container),
20910     * or {@link #OVER_SCROLL_NEVER}.
20911     *
20912     * @return This view's over-scroll mode.
20913     */
20914    public int getOverScrollMode() {
20915        return mOverScrollMode;
20916    }
20917
20918    /**
20919     * Set the over-scroll mode for this view. Valid over-scroll modes are
20920     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20921     * (allow over-scrolling only if the view content is larger than the container),
20922     * or {@link #OVER_SCROLL_NEVER}.
20923     *
20924     * Setting the over-scroll mode of a view will have an effect only if the
20925     * view is capable of scrolling.
20926     *
20927     * @param overScrollMode The new over-scroll mode for this view.
20928     */
20929    public void setOverScrollMode(int overScrollMode) {
20930        if (overScrollMode != OVER_SCROLL_ALWAYS &&
20931                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
20932                overScrollMode != OVER_SCROLL_NEVER) {
20933            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
20934        }
20935        mOverScrollMode = overScrollMode;
20936    }
20937
20938    /**
20939     * Enable or disable nested scrolling for this view.
20940     *
20941     * <p>If this property is set to true the view will be permitted to initiate nested
20942     * scrolling operations with a compatible parent view in the current hierarchy. If this
20943     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
20944     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
20945     * the nested scroll.</p>
20946     *
20947     * @param enabled true to enable nested scrolling, false to disable
20948     *
20949     * @see #isNestedScrollingEnabled()
20950     */
20951    public void setNestedScrollingEnabled(boolean enabled) {
20952        if (enabled) {
20953            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
20954        } else {
20955            stopNestedScroll();
20956            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
20957        }
20958    }
20959
20960    /**
20961     * Returns true if nested scrolling is enabled for this view.
20962     *
20963     * <p>If nested scrolling is enabled and this View class implementation supports it,
20964     * this view will act as a nested scrolling child view when applicable, forwarding data
20965     * about the scroll operation in progress to a compatible and cooperating nested scrolling
20966     * parent.</p>
20967     *
20968     * @return true if nested scrolling is enabled
20969     *
20970     * @see #setNestedScrollingEnabled(boolean)
20971     */
20972    public boolean isNestedScrollingEnabled() {
20973        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
20974                PFLAG3_NESTED_SCROLLING_ENABLED;
20975    }
20976
20977    /**
20978     * Begin a nestable scroll operation along the given axes.
20979     *
20980     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
20981     *
20982     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
20983     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
20984     * In the case of touch scrolling the nested scroll will be terminated automatically in
20985     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
20986     * In the event of programmatic scrolling the caller must explicitly call
20987     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
20988     *
20989     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
20990     * If it returns false the caller may ignore the rest of this contract until the next scroll.
20991     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
20992     *
20993     * <p>At each incremental step of the scroll the caller should invoke
20994     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
20995     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
20996     * parent at least partially consumed the scroll and the caller should adjust the amount it
20997     * scrolls by.</p>
20998     *
20999     * <p>After applying the remainder of the scroll delta the caller should invoke
21000     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21001     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21002     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21003     * </p>
21004     *
21005     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21006     *             {@link #SCROLL_AXIS_VERTICAL}.
21007     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21008     *         the current gesture.
21009     *
21010     * @see #stopNestedScroll()
21011     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21012     * @see #dispatchNestedScroll(int, int, int, int, int[])
21013     */
21014    public boolean startNestedScroll(int axes) {
21015        if (hasNestedScrollingParent()) {
21016            // Already in progress
21017            return true;
21018        }
21019        if (isNestedScrollingEnabled()) {
21020            ViewParent p = getParent();
21021            View child = this;
21022            while (p != null) {
21023                try {
21024                    if (p.onStartNestedScroll(child, this, axes)) {
21025                        mNestedScrollingParent = p;
21026                        p.onNestedScrollAccepted(child, this, axes);
21027                        return true;
21028                    }
21029                } catch (AbstractMethodError e) {
21030                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21031                            "method onStartNestedScroll", e);
21032                    // Allow the search upward to continue
21033                }
21034                if (p instanceof View) {
21035                    child = (View) p;
21036                }
21037                p = p.getParent();
21038            }
21039        }
21040        return false;
21041    }
21042
21043    /**
21044     * Stop a nested scroll in progress.
21045     *
21046     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21047     *
21048     * @see #startNestedScroll(int)
21049     */
21050    public void stopNestedScroll() {
21051        if (mNestedScrollingParent != null) {
21052            mNestedScrollingParent.onStopNestedScroll(this);
21053            mNestedScrollingParent = null;
21054        }
21055    }
21056
21057    /**
21058     * Returns true if this view has a nested scrolling parent.
21059     *
21060     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21061     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21062     *
21063     * @return whether this view has a nested scrolling parent
21064     */
21065    public boolean hasNestedScrollingParent() {
21066        return mNestedScrollingParent != null;
21067    }
21068
21069    /**
21070     * Dispatch one step of a nested scroll in progress.
21071     *
21072     * <p>Implementations of views that support nested scrolling should call this to report
21073     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21074     * is not currently in progress or nested scrolling is not
21075     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21076     *
21077     * <p>Compatible View implementations should also call
21078     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21079     * consuming a component of the scroll event themselves.</p>
21080     *
21081     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21082     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21083     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21084     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21085     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21086     *                       in local view coordinates of this view from before this operation
21087     *                       to after it completes. View implementations may use this to adjust
21088     *                       expected input coordinate tracking.
21089     * @return true if the event was dispatched, false if it could not be dispatched.
21090     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21091     */
21092    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21093            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21094        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21095            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21096                int startX = 0;
21097                int startY = 0;
21098                if (offsetInWindow != null) {
21099                    getLocationInWindow(offsetInWindow);
21100                    startX = offsetInWindow[0];
21101                    startY = offsetInWindow[1];
21102                }
21103
21104                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21105                        dxUnconsumed, dyUnconsumed);
21106
21107                if (offsetInWindow != null) {
21108                    getLocationInWindow(offsetInWindow);
21109                    offsetInWindow[0] -= startX;
21110                    offsetInWindow[1] -= startY;
21111                }
21112                return true;
21113            } else if (offsetInWindow != null) {
21114                // No motion, no dispatch. Keep offsetInWindow up to date.
21115                offsetInWindow[0] = 0;
21116                offsetInWindow[1] = 0;
21117            }
21118        }
21119        return false;
21120    }
21121
21122    /**
21123     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21124     *
21125     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21126     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21127     * scrolling operation to consume some or all of the scroll operation before the child view
21128     * consumes it.</p>
21129     *
21130     * @param dx Horizontal scroll distance in pixels
21131     * @param dy Vertical scroll distance in pixels
21132     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21133     *                 and consumed[1] the consumed dy.
21134     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21135     *                       in local view coordinates of this view from before this operation
21136     *                       to after it completes. View implementations may use this to adjust
21137     *                       expected input coordinate tracking.
21138     * @return true if the parent consumed some or all of the scroll delta
21139     * @see #dispatchNestedScroll(int, int, int, int, int[])
21140     */
21141    public boolean dispatchNestedPreScroll(int dx, int dy,
21142            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21143        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21144            if (dx != 0 || dy != 0) {
21145                int startX = 0;
21146                int startY = 0;
21147                if (offsetInWindow != null) {
21148                    getLocationInWindow(offsetInWindow);
21149                    startX = offsetInWindow[0];
21150                    startY = offsetInWindow[1];
21151                }
21152
21153                if (consumed == null) {
21154                    if (mTempNestedScrollConsumed == null) {
21155                        mTempNestedScrollConsumed = new int[2];
21156                    }
21157                    consumed = mTempNestedScrollConsumed;
21158                }
21159                consumed[0] = 0;
21160                consumed[1] = 0;
21161                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21162
21163                if (offsetInWindow != null) {
21164                    getLocationInWindow(offsetInWindow);
21165                    offsetInWindow[0] -= startX;
21166                    offsetInWindow[1] -= startY;
21167                }
21168                return consumed[0] != 0 || consumed[1] != 0;
21169            } else if (offsetInWindow != null) {
21170                offsetInWindow[0] = 0;
21171                offsetInWindow[1] = 0;
21172            }
21173        }
21174        return false;
21175    }
21176
21177    /**
21178     * Dispatch a fling to a nested scrolling parent.
21179     *
21180     * <p>This method should be used to indicate that a nested scrolling child has detected
21181     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21182     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21183     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21184     * along a scrollable axis.</p>
21185     *
21186     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21187     * its own content, it can use this method to delegate the fling to its nested scrolling
21188     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21189     *
21190     * @param velocityX Horizontal fling velocity in pixels per second
21191     * @param velocityY Vertical fling velocity in pixels per second
21192     * @param consumed true if the child consumed the fling, false otherwise
21193     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21194     */
21195    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21196        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21197            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21198        }
21199        return false;
21200    }
21201
21202    /**
21203     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21204     *
21205     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21206     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21207     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21208     * before the child view consumes it. If this method returns <code>true</code>, a nested
21209     * parent view consumed the fling and this view should not scroll as a result.</p>
21210     *
21211     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21212     * the fling at a time. If a parent view consumed the fling this method will return false.
21213     * Custom view implementations should account for this in two ways:</p>
21214     *
21215     * <ul>
21216     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21217     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21218     *     position regardless.</li>
21219     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21220     *     even to settle back to a valid idle position.</li>
21221     * </ul>
21222     *
21223     * <p>Views should also not offer fling velocities to nested parent views along an axis
21224     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21225     * should not offer a horizontal fling velocity to its parents since scrolling along that
21226     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21227     *
21228     * @param velocityX Horizontal fling velocity in pixels per second
21229     * @param velocityY Vertical fling velocity in pixels per second
21230     * @return true if a nested scrolling parent consumed the fling
21231     */
21232    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21233        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21234            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21235        }
21236        return false;
21237    }
21238
21239    /**
21240     * Gets a scale factor that determines the distance the view should scroll
21241     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21242     * @return The vertical scroll scale factor.
21243     * @hide
21244     */
21245    protected float getVerticalScrollFactor() {
21246        if (mVerticalScrollFactor == 0) {
21247            TypedValue outValue = new TypedValue();
21248            if (!mContext.getTheme().resolveAttribute(
21249                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21250                throw new IllegalStateException(
21251                        "Expected theme to define listPreferredItemHeight.");
21252            }
21253            mVerticalScrollFactor = outValue.getDimension(
21254                    mContext.getResources().getDisplayMetrics());
21255        }
21256        return mVerticalScrollFactor;
21257    }
21258
21259    /**
21260     * Gets a scale factor that determines the distance the view should scroll
21261     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21262     * @return The horizontal scroll scale factor.
21263     * @hide
21264     */
21265    protected float getHorizontalScrollFactor() {
21266        // TODO: Should use something else.
21267        return getVerticalScrollFactor();
21268    }
21269
21270    /**
21271     * Return the value specifying the text direction or policy that was set with
21272     * {@link #setTextDirection(int)}.
21273     *
21274     * @return the defined text direction. It can be one of:
21275     *
21276     * {@link #TEXT_DIRECTION_INHERIT},
21277     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21278     * {@link #TEXT_DIRECTION_ANY_RTL},
21279     * {@link #TEXT_DIRECTION_LTR},
21280     * {@link #TEXT_DIRECTION_RTL},
21281     * {@link #TEXT_DIRECTION_LOCALE},
21282     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21283     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21284     *
21285     * @attr ref android.R.styleable#View_textDirection
21286     *
21287     * @hide
21288     */
21289    @ViewDebug.ExportedProperty(category = "text", mapping = {
21290            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21291            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21292            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21293            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21294            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21295            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21296            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21297            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21298    })
21299    public int getRawTextDirection() {
21300        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21301    }
21302
21303    /**
21304     * Set the text direction.
21305     *
21306     * @param textDirection the direction to set. Should be one of:
21307     *
21308     * {@link #TEXT_DIRECTION_INHERIT},
21309     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21310     * {@link #TEXT_DIRECTION_ANY_RTL},
21311     * {@link #TEXT_DIRECTION_LTR},
21312     * {@link #TEXT_DIRECTION_RTL},
21313     * {@link #TEXT_DIRECTION_LOCALE}
21314     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21315     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21316     *
21317     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21318     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21319     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21320     *
21321     * @attr ref android.R.styleable#View_textDirection
21322     */
21323    public void setTextDirection(int textDirection) {
21324        if (getRawTextDirection() != textDirection) {
21325            // Reset the current text direction and the resolved one
21326            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21327            resetResolvedTextDirection();
21328            // Set the new text direction
21329            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21330            // Do resolution
21331            resolveTextDirection();
21332            // Notify change
21333            onRtlPropertiesChanged(getLayoutDirection());
21334            // Refresh
21335            requestLayout();
21336            invalidate(true);
21337        }
21338    }
21339
21340    /**
21341     * Return the resolved text direction.
21342     *
21343     * @return the resolved text direction. Returns one of:
21344     *
21345     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21346     * {@link #TEXT_DIRECTION_ANY_RTL},
21347     * {@link #TEXT_DIRECTION_LTR},
21348     * {@link #TEXT_DIRECTION_RTL},
21349     * {@link #TEXT_DIRECTION_LOCALE},
21350     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21351     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21352     *
21353     * @attr ref android.R.styleable#View_textDirection
21354     */
21355    @ViewDebug.ExportedProperty(category = "text", mapping = {
21356            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21357            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21358            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21359            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21360            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21361            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21362            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21363            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21364    })
21365    public int getTextDirection() {
21366        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21367    }
21368
21369    /**
21370     * Resolve the text direction.
21371     *
21372     * @return true if resolution has been done, false otherwise.
21373     *
21374     * @hide
21375     */
21376    public boolean resolveTextDirection() {
21377        // Reset any previous text direction resolution
21378        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21379
21380        if (hasRtlSupport()) {
21381            // Set resolved text direction flag depending on text direction flag
21382            final int textDirection = getRawTextDirection();
21383            switch(textDirection) {
21384                case TEXT_DIRECTION_INHERIT:
21385                    if (!canResolveTextDirection()) {
21386                        // We cannot do the resolution if there is no parent, so use the default one
21387                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21388                        // Resolution will need to happen again later
21389                        return false;
21390                    }
21391
21392                    // Parent has not yet resolved, so we still return the default
21393                    try {
21394                        if (!mParent.isTextDirectionResolved()) {
21395                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21396                            // Resolution will need to happen again later
21397                            return false;
21398                        }
21399                    } catch (AbstractMethodError e) {
21400                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21401                                " does not fully implement ViewParent", e);
21402                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
21403                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21404                        return true;
21405                    }
21406
21407                    // Set current resolved direction to the same value as the parent's one
21408                    int parentResolvedDirection;
21409                    try {
21410                        parentResolvedDirection = mParent.getTextDirection();
21411                    } catch (AbstractMethodError e) {
21412                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21413                                " does not fully implement ViewParent", e);
21414                        parentResolvedDirection = TEXT_DIRECTION_LTR;
21415                    }
21416                    switch (parentResolvedDirection) {
21417                        case TEXT_DIRECTION_FIRST_STRONG:
21418                        case TEXT_DIRECTION_ANY_RTL:
21419                        case TEXT_DIRECTION_LTR:
21420                        case TEXT_DIRECTION_RTL:
21421                        case TEXT_DIRECTION_LOCALE:
21422                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
21423                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
21424                            mPrivateFlags2 |=
21425                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21426                            break;
21427                        default:
21428                            // Default resolved direction is "first strong" heuristic
21429                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21430                    }
21431                    break;
21432                case TEXT_DIRECTION_FIRST_STRONG:
21433                case TEXT_DIRECTION_ANY_RTL:
21434                case TEXT_DIRECTION_LTR:
21435                case TEXT_DIRECTION_RTL:
21436                case TEXT_DIRECTION_LOCALE:
21437                case TEXT_DIRECTION_FIRST_STRONG_LTR:
21438                case TEXT_DIRECTION_FIRST_STRONG_RTL:
21439                    // Resolved direction is the same as text direction
21440                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21441                    break;
21442                default:
21443                    // Default resolved direction is "first strong" heuristic
21444                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21445            }
21446        } else {
21447            // Default resolved direction is "first strong" heuristic
21448            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21449        }
21450
21451        // Set to resolved
21452        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
21453        return true;
21454    }
21455
21456    /**
21457     * Check if text direction resolution can be done.
21458     *
21459     * @return true if text direction resolution can be done otherwise return false.
21460     */
21461    public boolean canResolveTextDirection() {
21462        switch (getRawTextDirection()) {
21463            case TEXT_DIRECTION_INHERIT:
21464                if (mParent != null) {
21465                    try {
21466                        return mParent.canResolveTextDirection();
21467                    } catch (AbstractMethodError e) {
21468                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21469                                " does not fully implement ViewParent", e);
21470                    }
21471                }
21472                return false;
21473
21474            default:
21475                return true;
21476        }
21477    }
21478
21479    /**
21480     * Reset resolved text direction. Text direction will be resolved during a call to
21481     * {@link #onMeasure(int, int)}.
21482     *
21483     * @hide
21484     */
21485    public void resetResolvedTextDirection() {
21486        // Reset any previous text direction resolution
21487        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21488        // Set to default value
21489        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21490    }
21491
21492    /**
21493     * @return true if text direction is inherited.
21494     *
21495     * @hide
21496     */
21497    public boolean isTextDirectionInherited() {
21498        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
21499    }
21500
21501    /**
21502     * @return true if text direction is resolved.
21503     */
21504    public boolean isTextDirectionResolved() {
21505        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
21506    }
21507
21508    /**
21509     * Return the value specifying the text alignment or policy that was set with
21510     * {@link #setTextAlignment(int)}.
21511     *
21512     * @return the defined text alignment. It can be one of:
21513     *
21514     * {@link #TEXT_ALIGNMENT_INHERIT},
21515     * {@link #TEXT_ALIGNMENT_GRAVITY},
21516     * {@link #TEXT_ALIGNMENT_CENTER},
21517     * {@link #TEXT_ALIGNMENT_TEXT_START},
21518     * {@link #TEXT_ALIGNMENT_TEXT_END},
21519     * {@link #TEXT_ALIGNMENT_VIEW_START},
21520     * {@link #TEXT_ALIGNMENT_VIEW_END}
21521     *
21522     * @attr ref android.R.styleable#View_textAlignment
21523     *
21524     * @hide
21525     */
21526    @ViewDebug.ExportedProperty(category = "text", mapping = {
21527            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21528            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21529            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21530            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21531            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21532            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21533            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21534    })
21535    @TextAlignment
21536    public int getRawTextAlignment() {
21537        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
21538    }
21539
21540    /**
21541     * Set the text alignment.
21542     *
21543     * @param textAlignment The text alignment to set. Should be one of
21544     *
21545     * {@link #TEXT_ALIGNMENT_INHERIT},
21546     * {@link #TEXT_ALIGNMENT_GRAVITY},
21547     * {@link #TEXT_ALIGNMENT_CENTER},
21548     * {@link #TEXT_ALIGNMENT_TEXT_START},
21549     * {@link #TEXT_ALIGNMENT_TEXT_END},
21550     * {@link #TEXT_ALIGNMENT_VIEW_START},
21551     * {@link #TEXT_ALIGNMENT_VIEW_END}
21552     *
21553     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
21554     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
21555     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
21556     *
21557     * @attr ref android.R.styleable#View_textAlignment
21558     */
21559    public void setTextAlignment(@TextAlignment int textAlignment) {
21560        if (textAlignment != getRawTextAlignment()) {
21561            // Reset the current and resolved text alignment
21562            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
21563            resetResolvedTextAlignment();
21564            // Set the new text alignment
21565            mPrivateFlags2 |=
21566                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
21567            // Do resolution
21568            resolveTextAlignment();
21569            // Notify change
21570            onRtlPropertiesChanged(getLayoutDirection());
21571            // Refresh
21572            requestLayout();
21573            invalidate(true);
21574        }
21575    }
21576
21577    /**
21578     * Return the resolved text alignment.
21579     *
21580     * @return the resolved text alignment. Returns one of:
21581     *
21582     * {@link #TEXT_ALIGNMENT_GRAVITY},
21583     * {@link #TEXT_ALIGNMENT_CENTER},
21584     * {@link #TEXT_ALIGNMENT_TEXT_START},
21585     * {@link #TEXT_ALIGNMENT_TEXT_END},
21586     * {@link #TEXT_ALIGNMENT_VIEW_START},
21587     * {@link #TEXT_ALIGNMENT_VIEW_END}
21588     *
21589     * @attr ref android.R.styleable#View_textAlignment
21590     */
21591    @ViewDebug.ExportedProperty(category = "text", mapping = {
21592            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21593            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21594            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21595            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21596            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21597            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21598            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21599    })
21600    @TextAlignment
21601    public int getTextAlignment() {
21602        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
21603                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
21604    }
21605
21606    /**
21607     * Resolve the text alignment.
21608     *
21609     * @return true if resolution has been done, false otherwise.
21610     *
21611     * @hide
21612     */
21613    public boolean resolveTextAlignment() {
21614        // Reset any previous text alignment resolution
21615        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21616
21617        if (hasRtlSupport()) {
21618            // Set resolved text alignment flag depending on text alignment flag
21619            final int textAlignment = getRawTextAlignment();
21620            switch (textAlignment) {
21621                case TEXT_ALIGNMENT_INHERIT:
21622                    // Check if we can resolve the text alignment
21623                    if (!canResolveTextAlignment()) {
21624                        // We cannot do the resolution if there is no parent so use the default
21625                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21626                        // Resolution will need to happen again later
21627                        return false;
21628                    }
21629
21630                    // Parent has not yet resolved, so we still return the default
21631                    try {
21632                        if (!mParent.isTextAlignmentResolved()) {
21633                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21634                            // Resolution will need to happen again later
21635                            return false;
21636                        }
21637                    } catch (AbstractMethodError e) {
21638                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21639                                " does not fully implement ViewParent", e);
21640                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
21641                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21642                        return true;
21643                    }
21644
21645                    int parentResolvedTextAlignment;
21646                    try {
21647                        parentResolvedTextAlignment = mParent.getTextAlignment();
21648                    } catch (AbstractMethodError e) {
21649                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21650                                " does not fully implement ViewParent", e);
21651                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
21652                    }
21653                    switch (parentResolvedTextAlignment) {
21654                        case TEXT_ALIGNMENT_GRAVITY:
21655                        case TEXT_ALIGNMENT_TEXT_START:
21656                        case TEXT_ALIGNMENT_TEXT_END:
21657                        case TEXT_ALIGNMENT_CENTER:
21658                        case TEXT_ALIGNMENT_VIEW_START:
21659                        case TEXT_ALIGNMENT_VIEW_END:
21660                            // Resolved text alignment is the same as the parent resolved
21661                            // text alignment
21662                            mPrivateFlags2 |=
21663                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21664                            break;
21665                        default:
21666                            // Use default resolved text alignment
21667                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21668                    }
21669                    break;
21670                case TEXT_ALIGNMENT_GRAVITY:
21671                case TEXT_ALIGNMENT_TEXT_START:
21672                case TEXT_ALIGNMENT_TEXT_END:
21673                case TEXT_ALIGNMENT_CENTER:
21674                case TEXT_ALIGNMENT_VIEW_START:
21675                case TEXT_ALIGNMENT_VIEW_END:
21676                    // Resolved text alignment is the same as text alignment
21677                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21678                    break;
21679                default:
21680                    // Use default resolved text alignment
21681                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21682            }
21683        } else {
21684            // Use default resolved text alignment
21685            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21686        }
21687
21688        // Set the resolved
21689        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21690        return true;
21691    }
21692
21693    /**
21694     * Check if text alignment resolution can be done.
21695     *
21696     * @return true if text alignment resolution can be done otherwise return false.
21697     */
21698    public boolean canResolveTextAlignment() {
21699        switch (getRawTextAlignment()) {
21700            case TEXT_DIRECTION_INHERIT:
21701                if (mParent != null) {
21702                    try {
21703                        return mParent.canResolveTextAlignment();
21704                    } catch (AbstractMethodError e) {
21705                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21706                                " does not fully implement ViewParent", e);
21707                    }
21708                }
21709                return false;
21710
21711            default:
21712                return true;
21713        }
21714    }
21715
21716    /**
21717     * Reset resolved text alignment. Text alignment will be resolved during a call to
21718     * {@link #onMeasure(int, int)}.
21719     *
21720     * @hide
21721     */
21722    public void resetResolvedTextAlignment() {
21723        // Reset any previous text alignment resolution
21724        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21725        // Set to default
21726        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21727    }
21728
21729    /**
21730     * @return true if text alignment is inherited.
21731     *
21732     * @hide
21733     */
21734    public boolean isTextAlignmentInherited() {
21735        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
21736    }
21737
21738    /**
21739     * @return true if text alignment is resolved.
21740     */
21741    public boolean isTextAlignmentResolved() {
21742        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21743    }
21744
21745    /**
21746     * Generate a value suitable for use in {@link #setId(int)}.
21747     * This value will not collide with ID values generated at build time by aapt for R.id.
21748     *
21749     * @return a generated ID value
21750     */
21751    public static int generateViewId() {
21752        for (;;) {
21753            final int result = sNextGeneratedId.get();
21754            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
21755            int newValue = result + 1;
21756            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
21757            if (sNextGeneratedId.compareAndSet(result, newValue)) {
21758                return result;
21759            }
21760        }
21761    }
21762
21763    /**
21764     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
21765     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
21766     *                           a normal View or a ViewGroup with
21767     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
21768     * @hide
21769     */
21770    public void captureTransitioningViews(List<View> transitioningViews) {
21771        if (getVisibility() == View.VISIBLE) {
21772            transitioningViews.add(this);
21773        }
21774    }
21775
21776    /**
21777     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
21778     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
21779     * @hide
21780     */
21781    public void findNamedViews(Map<String, View> namedElements) {
21782        if (getVisibility() == VISIBLE || mGhostView != null) {
21783            String transitionName = getTransitionName();
21784            if (transitionName != null) {
21785                namedElements.put(transitionName, this);
21786            }
21787        }
21788    }
21789
21790    /**
21791     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
21792     * The default implementation does not care the location or event types, but some subclasses
21793     * may use it (such as WebViews).
21794     * @param event The MotionEvent from a mouse
21795     * @param x The x position of the event, local to the view
21796     * @param y The y position of the event, local to the view
21797     * @see PointerIcon
21798     */
21799    public PointerIcon getPointerIcon(MotionEvent event, float x, float y) {
21800        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
21801            return PointerIcon.getSystemIcon(mContext, PointerIcon.STYLE_ARROW);
21802        }
21803        return mPointerIcon;
21804    }
21805
21806    /**
21807     * Set the pointer icon for the current view.
21808     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
21809     */
21810    public void setPointerIcon(PointerIcon pointerIcon) {
21811        mPointerIcon = pointerIcon;
21812        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
21813            return;
21814        }
21815        try {
21816            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
21817        } catch (RemoteException e) {
21818        }
21819    }
21820
21821    /**
21822     * Request capturing further mouse events.
21823     *
21824     * When the view captures, the mouse pointer icon will disappear and will not change its
21825     * position. Further mouse events will come to the capturing view, and the mouse movements
21826     * will can be detected through {@link MotionEvent#AXIS_RELATIVE_X} and
21827     * {@link MotionEvent#AXIS_RELATIVE_Y}. Non-mouse events (touchscreens, or stylus) will not
21828     * be affected.
21829     *
21830     * The capture will be released through {@link #releasePointerCapture()}, or will be lost
21831     * automatically when the view or containing window disappear.
21832     *
21833     * @return true when succeeds.
21834     * @see #releasePointerCapture()
21835     * @see #hasPointerCapture()
21836     */
21837    public void setPointerCapture() {
21838        final ViewRootImpl viewRootImpl = getViewRootImpl();
21839        if (viewRootImpl != null) {
21840            viewRootImpl.setPointerCapture(this);
21841        }
21842    }
21843
21844
21845    /**
21846     * Release the current capture of mouse events.
21847     *
21848     * If the view does not have the capture, it will do nothing.
21849     * @see #setPointerCapture()
21850     * @see #hasPointerCapture()
21851     */
21852    public void releasePointerCapture() {
21853        final ViewRootImpl viewRootImpl = getViewRootImpl();
21854        if (viewRootImpl != null) {
21855            viewRootImpl.releasePointerCapture(this);
21856        }
21857    }
21858
21859    /**
21860     * Checks the capture status of mouse events.
21861     *
21862     * @return true if the view has the capture.
21863     * @see #setPointerCapture()
21864     * @see #hasPointerCapture()
21865     */
21866    public boolean hasPointerCapture() {
21867        final ViewRootImpl viewRootImpl = getViewRootImpl();
21868        return (viewRootImpl != null) && viewRootImpl.hasPointerCapture(this);
21869    }
21870
21871    //
21872    // Properties
21873    //
21874    /**
21875     * A Property wrapper around the <code>alpha</code> functionality handled by the
21876     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
21877     */
21878    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
21879        @Override
21880        public void setValue(View object, float value) {
21881            object.setAlpha(value);
21882        }
21883
21884        @Override
21885        public Float get(View object) {
21886            return object.getAlpha();
21887        }
21888    };
21889
21890    /**
21891     * A Property wrapper around the <code>translationX</code> functionality handled by the
21892     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
21893     */
21894    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
21895        @Override
21896        public void setValue(View object, float value) {
21897            object.setTranslationX(value);
21898        }
21899
21900                @Override
21901        public Float get(View object) {
21902            return object.getTranslationX();
21903        }
21904    };
21905
21906    /**
21907     * A Property wrapper around the <code>translationY</code> functionality handled by the
21908     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
21909     */
21910    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
21911        @Override
21912        public void setValue(View object, float value) {
21913            object.setTranslationY(value);
21914        }
21915
21916        @Override
21917        public Float get(View object) {
21918            return object.getTranslationY();
21919        }
21920    };
21921
21922    /**
21923     * A Property wrapper around the <code>translationZ</code> functionality handled by the
21924     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
21925     */
21926    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
21927        @Override
21928        public void setValue(View object, float value) {
21929            object.setTranslationZ(value);
21930        }
21931
21932        @Override
21933        public Float get(View object) {
21934            return object.getTranslationZ();
21935        }
21936    };
21937
21938    /**
21939     * A Property wrapper around the <code>x</code> functionality handled by the
21940     * {@link View#setX(float)} and {@link View#getX()} methods.
21941     */
21942    public static final Property<View, Float> X = new FloatProperty<View>("x") {
21943        @Override
21944        public void setValue(View object, float value) {
21945            object.setX(value);
21946        }
21947
21948        @Override
21949        public Float get(View object) {
21950            return object.getX();
21951        }
21952    };
21953
21954    /**
21955     * A Property wrapper around the <code>y</code> functionality handled by the
21956     * {@link View#setY(float)} and {@link View#getY()} methods.
21957     */
21958    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
21959        @Override
21960        public void setValue(View object, float value) {
21961            object.setY(value);
21962        }
21963
21964        @Override
21965        public Float get(View object) {
21966            return object.getY();
21967        }
21968    };
21969
21970    /**
21971     * A Property wrapper around the <code>z</code> functionality handled by the
21972     * {@link View#setZ(float)} and {@link View#getZ()} methods.
21973     */
21974    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
21975        @Override
21976        public void setValue(View object, float value) {
21977            object.setZ(value);
21978        }
21979
21980        @Override
21981        public Float get(View object) {
21982            return object.getZ();
21983        }
21984    };
21985
21986    /**
21987     * A Property wrapper around the <code>rotation</code> functionality handled by the
21988     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
21989     */
21990    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
21991        @Override
21992        public void setValue(View object, float value) {
21993            object.setRotation(value);
21994        }
21995
21996        @Override
21997        public Float get(View object) {
21998            return object.getRotation();
21999        }
22000    };
22001
22002    /**
22003     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22004     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22005     */
22006    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22007        @Override
22008        public void setValue(View object, float value) {
22009            object.setRotationX(value);
22010        }
22011
22012        @Override
22013        public Float get(View object) {
22014            return object.getRotationX();
22015        }
22016    };
22017
22018    /**
22019     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22020     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22021     */
22022    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22023        @Override
22024        public void setValue(View object, float value) {
22025            object.setRotationY(value);
22026        }
22027
22028        @Override
22029        public Float get(View object) {
22030            return object.getRotationY();
22031        }
22032    };
22033
22034    /**
22035     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22036     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22037     */
22038    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22039        @Override
22040        public void setValue(View object, float value) {
22041            object.setScaleX(value);
22042        }
22043
22044        @Override
22045        public Float get(View object) {
22046            return object.getScaleX();
22047        }
22048    };
22049
22050    /**
22051     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22052     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22053     */
22054    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22055        @Override
22056        public void setValue(View object, float value) {
22057            object.setScaleY(value);
22058        }
22059
22060        @Override
22061        public Float get(View object) {
22062            return object.getScaleY();
22063        }
22064    };
22065
22066    /**
22067     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22068     * Each MeasureSpec represents a requirement for either the width or the height.
22069     * A MeasureSpec is comprised of a size and a mode. There are three possible
22070     * modes:
22071     * <dl>
22072     * <dt>UNSPECIFIED</dt>
22073     * <dd>
22074     * The parent has not imposed any constraint on the child. It can be whatever size
22075     * it wants.
22076     * </dd>
22077     *
22078     * <dt>EXACTLY</dt>
22079     * <dd>
22080     * The parent has determined an exact size for the child. The child is going to be
22081     * given those bounds regardless of how big it wants to be.
22082     * </dd>
22083     *
22084     * <dt>AT_MOST</dt>
22085     * <dd>
22086     * The child can be as large as it wants up to the specified size.
22087     * </dd>
22088     * </dl>
22089     *
22090     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22091     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22092     */
22093    public static class MeasureSpec {
22094        private static final int MODE_SHIFT = 30;
22095        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22096
22097        /** @hide */
22098        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22099        @Retention(RetentionPolicy.SOURCE)
22100        public @interface MeasureSpecMode {}
22101
22102        /**
22103         * Measure specification mode: The parent has not imposed any constraint
22104         * on the child. It can be whatever size it wants.
22105         */
22106        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22107
22108        /**
22109         * Measure specification mode: The parent has determined an exact size
22110         * for the child. The child is going to be given those bounds regardless
22111         * of how big it wants to be.
22112         */
22113        public static final int EXACTLY     = 1 << MODE_SHIFT;
22114
22115        /**
22116         * Measure specification mode: The child can be as large as it wants up
22117         * to the specified size.
22118         */
22119        public static final int AT_MOST     = 2 << MODE_SHIFT;
22120
22121        /**
22122         * Creates a measure specification based on the supplied size and mode.
22123         *
22124         * The mode must always be one of the following:
22125         * <ul>
22126         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22127         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22128         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22129         * </ul>
22130         *
22131         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22132         * implementation was such that the order of arguments did not matter
22133         * and overflow in either value could impact the resulting MeasureSpec.
22134         * {@link android.widget.RelativeLayout} was affected by this bug.
22135         * Apps targeting API levels greater than 17 will get the fixed, more strict
22136         * behavior.</p>
22137         *
22138         * @param size the size of the measure specification
22139         * @param mode the mode of the measure specification
22140         * @return the measure specification based on size and mode
22141         */
22142        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22143                                          @MeasureSpecMode int mode) {
22144            if (sUseBrokenMakeMeasureSpec) {
22145                return size + mode;
22146            } else {
22147                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22148            }
22149        }
22150
22151        /**
22152         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22153         * will automatically get a size of 0. Older apps expect this.
22154         *
22155         * @hide internal use only for compatibility with system widgets and older apps
22156         */
22157        public static int makeSafeMeasureSpec(int size, int mode) {
22158            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22159                return 0;
22160            }
22161            return makeMeasureSpec(size, mode);
22162        }
22163
22164        /**
22165         * Extracts the mode from the supplied measure specification.
22166         *
22167         * @param measureSpec the measure specification to extract the mode from
22168         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22169         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22170         *         {@link android.view.View.MeasureSpec#EXACTLY}
22171         */
22172        @MeasureSpecMode
22173        public static int getMode(int measureSpec) {
22174            //noinspection ResourceType
22175            return (measureSpec & MODE_MASK);
22176        }
22177
22178        /**
22179         * Extracts the size from the supplied measure specification.
22180         *
22181         * @param measureSpec the measure specification to extract the size from
22182         * @return the size in pixels defined in the supplied measure specification
22183         */
22184        public static int getSize(int measureSpec) {
22185            return (measureSpec & ~MODE_MASK);
22186        }
22187
22188        static int adjust(int measureSpec, int delta) {
22189            final int mode = getMode(measureSpec);
22190            int size = getSize(measureSpec);
22191            if (mode == UNSPECIFIED) {
22192                // No need to adjust size for UNSPECIFIED mode.
22193                return makeMeasureSpec(size, UNSPECIFIED);
22194            }
22195            size += delta;
22196            if (size < 0) {
22197                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22198                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22199                size = 0;
22200            }
22201            return makeMeasureSpec(size, mode);
22202        }
22203
22204        /**
22205         * Returns a String representation of the specified measure
22206         * specification.
22207         *
22208         * @param measureSpec the measure specification to convert to a String
22209         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22210         */
22211        public static String toString(int measureSpec) {
22212            int mode = getMode(measureSpec);
22213            int size = getSize(measureSpec);
22214
22215            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22216
22217            if (mode == UNSPECIFIED)
22218                sb.append("UNSPECIFIED ");
22219            else if (mode == EXACTLY)
22220                sb.append("EXACTLY ");
22221            else if (mode == AT_MOST)
22222                sb.append("AT_MOST ");
22223            else
22224                sb.append(mode).append(" ");
22225
22226            sb.append(size);
22227            return sb.toString();
22228        }
22229    }
22230
22231    private final class CheckForLongPress implements Runnable {
22232        private int mOriginalWindowAttachCount;
22233        private float mX;
22234        private float mY;
22235
22236        @Override
22237        public void run() {
22238            if (isPressed() && (mParent != null)
22239                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22240                if (performLongClick(mX, mY)) {
22241                    mHasPerformedLongPress = true;
22242                }
22243            }
22244        }
22245
22246        public void setAnchor(float x, float y) {
22247            mX = x;
22248            mY = y;
22249        }
22250
22251        public void rememberWindowAttachCount() {
22252            mOriginalWindowAttachCount = mWindowAttachCount;
22253        }
22254    }
22255
22256    private final class CheckForTap implements Runnable {
22257        public float x;
22258        public float y;
22259
22260        @Override
22261        public void run() {
22262            mPrivateFlags &= ~PFLAG_PREPRESSED;
22263            setPressed(true, x, y);
22264            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22265        }
22266    }
22267
22268    private final class PerformClick implements Runnable {
22269        @Override
22270        public void run() {
22271            performClick();
22272        }
22273    }
22274
22275    /**
22276     * This method returns a ViewPropertyAnimator object, which can be used to animate
22277     * specific properties on this View.
22278     *
22279     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22280     */
22281    public ViewPropertyAnimator animate() {
22282        if (mAnimator == null) {
22283            mAnimator = new ViewPropertyAnimator(this);
22284        }
22285        return mAnimator;
22286    }
22287
22288    /**
22289     * Sets the name of the View to be used to identify Views in Transitions.
22290     * Names should be unique in the View hierarchy.
22291     *
22292     * @param transitionName The name of the View to uniquely identify it for Transitions.
22293     */
22294    public final void setTransitionName(String transitionName) {
22295        mTransitionName = transitionName;
22296    }
22297
22298    /**
22299     * Returns the name of the View to be used to identify Views in Transitions.
22300     * Names should be unique in the View hierarchy.
22301     *
22302     * <p>This returns null if the View has not been given a name.</p>
22303     *
22304     * @return The name used of the View to be used to identify Views in Transitions or null
22305     * if no name has been given.
22306     */
22307    @ViewDebug.ExportedProperty
22308    public String getTransitionName() {
22309        return mTransitionName;
22310    }
22311
22312    /**
22313     * @hide
22314     */
22315    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22316        // Do nothing.
22317    }
22318
22319    /**
22320     * Interface definition for a callback to be invoked when a hardware key event is
22321     * dispatched to this view. The callback will be invoked before the key event is
22322     * given to the view. This is only useful for hardware keyboards; a software input
22323     * method has no obligation to trigger this listener.
22324     */
22325    public interface OnKeyListener {
22326        /**
22327         * Called when a hardware key is dispatched to a view. This allows listeners to
22328         * get a chance to respond before the target view.
22329         * <p>Key presses in software keyboards will generally NOT trigger this method,
22330         * although some may elect to do so in some situations. Do not assume a
22331         * software input method has to be key-based; even if it is, it may use key presses
22332         * in a different way than you expect, so there is no way to reliably catch soft
22333         * input key presses.
22334         *
22335         * @param v The view the key has been dispatched to.
22336         * @param keyCode The code for the physical key that was pressed
22337         * @param event The KeyEvent object containing full information about
22338         *        the event.
22339         * @return True if the listener has consumed the event, false otherwise.
22340         */
22341        boolean onKey(View v, int keyCode, KeyEvent event);
22342    }
22343
22344    /**
22345     * Interface definition for a callback to be invoked when a touch event is
22346     * dispatched to this view. The callback will be invoked before the touch
22347     * event is given to the view.
22348     */
22349    public interface OnTouchListener {
22350        /**
22351         * Called when a touch event is dispatched to a view. This allows listeners to
22352         * get a chance to respond before the target view.
22353         *
22354         * @param v The view the touch event has been dispatched to.
22355         * @param event The MotionEvent object containing full information about
22356         *        the event.
22357         * @return True if the listener has consumed the event, false otherwise.
22358         */
22359        boolean onTouch(View v, MotionEvent event);
22360    }
22361
22362    /**
22363     * Interface definition for a callback to be invoked when a hover event is
22364     * dispatched to this view. The callback will be invoked before the hover
22365     * event is given to the view.
22366     */
22367    public interface OnHoverListener {
22368        /**
22369         * Called when a hover event is dispatched to a view. This allows listeners to
22370         * get a chance to respond before the target view.
22371         *
22372         * @param v The view the hover event has been dispatched to.
22373         * @param event The MotionEvent object containing full information about
22374         *        the event.
22375         * @return True if the listener has consumed the event, false otherwise.
22376         */
22377        boolean onHover(View v, MotionEvent event);
22378    }
22379
22380    /**
22381     * Interface definition for a callback to be invoked when a generic motion event is
22382     * dispatched to this view. The callback will be invoked before the generic motion
22383     * event is given to the view.
22384     */
22385    public interface OnGenericMotionListener {
22386        /**
22387         * Called when a generic motion event is dispatched to a view. This allows listeners to
22388         * get a chance to respond before the target view.
22389         *
22390         * @param v The view the generic motion event has been dispatched to.
22391         * @param event The MotionEvent object containing full information about
22392         *        the event.
22393         * @return True if the listener has consumed the event, false otherwise.
22394         */
22395        boolean onGenericMotion(View v, MotionEvent event);
22396    }
22397
22398    /**
22399     * Interface definition for a callback to be invoked when a view has been clicked and held.
22400     */
22401    public interface OnLongClickListener {
22402        /**
22403         * Called when a view has been clicked and held.
22404         *
22405         * @param v The view that was clicked and held.
22406         *
22407         * @return true if the callback consumed the long click, false otherwise.
22408         */
22409        boolean onLongClick(View v);
22410    }
22411
22412    /**
22413     * Interface definition for a callback to be invoked when a drag is being dispatched
22414     * to this view.  The callback will be invoked before the hosting view's own
22415     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
22416     * onDrag(event) behavior, it should return 'false' from this callback.
22417     *
22418     * <div class="special reference">
22419     * <h3>Developer Guides</h3>
22420     * <p>For a guide to implementing drag and drop features, read the
22421     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22422     * </div>
22423     */
22424    public interface OnDragListener {
22425        /**
22426         * Called when a drag event is dispatched to a view. This allows listeners
22427         * to get a chance to override base View behavior.
22428         *
22429         * @param v The View that received the drag event.
22430         * @param event The {@link android.view.DragEvent} object for the drag event.
22431         * @return {@code true} if the drag event was handled successfully, or {@code false}
22432         * if the drag event was not handled. Note that {@code false} will trigger the View
22433         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
22434         */
22435        boolean onDrag(View v, DragEvent event);
22436    }
22437
22438    /**
22439     * Interface definition for a callback to be invoked when the focus state of
22440     * a view changed.
22441     */
22442    public interface OnFocusChangeListener {
22443        /**
22444         * Called when the focus state of a view has changed.
22445         *
22446         * @param v The view whose state has changed.
22447         * @param hasFocus The new focus state of v.
22448         */
22449        void onFocusChange(View v, boolean hasFocus);
22450    }
22451
22452    /**
22453     * Interface definition for a callback to be invoked when a view is clicked.
22454     */
22455    public interface OnClickListener {
22456        /**
22457         * Called when a view has been clicked.
22458         *
22459         * @param v The view that was clicked.
22460         */
22461        void onClick(View v);
22462    }
22463
22464    /**
22465     * Interface definition for a callback to be invoked when a view is context clicked.
22466     */
22467    public interface OnContextClickListener {
22468        /**
22469         * Called when a view is context clicked.
22470         *
22471         * @param v The view that has been context clicked.
22472         * @return true if the callback consumed the context click, false otherwise.
22473         */
22474        boolean onContextClick(View v);
22475    }
22476
22477    /**
22478     * Interface definition for a callback to be invoked when the context menu
22479     * for this view is being built.
22480     */
22481    public interface OnCreateContextMenuListener {
22482        /**
22483         * Called when the context menu for this view is being built. It is not
22484         * safe to hold onto the menu after this method returns.
22485         *
22486         * @param menu The context menu that is being built
22487         * @param v The view for which the context menu is being built
22488         * @param menuInfo Extra information about the item for which the
22489         *            context menu should be shown. This information will vary
22490         *            depending on the class of v.
22491         */
22492        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
22493    }
22494
22495    /**
22496     * Interface definition for a callback to be invoked when the status bar changes
22497     * visibility.  This reports <strong>global</strong> changes to the system UI
22498     * state, not what the application is requesting.
22499     *
22500     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
22501     */
22502    public interface OnSystemUiVisibilityChangeListener {
22503        /**
22504         * Called when the status bar changes visibility because of a call to
22505         * {@link View#setSystemUiVisibility(int)}.
22506         *
22507         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22508         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
22509         * This tells you the <strong>global</strong> state of these UI visibility
22510         * flags, not what your app is currently applying.
22511         */
22512        public void onSystemUiVisibilityChange(int visibility);
22513    }
22514
22515    /**
22516     * Interface definition for a callback to be invoked when this view is attached
22517     * or detached from its window.
22518     */
22519    public interface OnAttachStateChangeListener {
22520        /**
22521         * Called when the view is attached to a window.
22522         * @param v The view that was attached
22523         */
22524        public void onViewAttachedToWindow(View v);
22525        /**
22526         * Called when the view is detached from a window.
22527         * @param v The view that was detached
22528         */
22529        public void onViewDetachedFromWindow(View v);
22530    }
22531
22532    /**
22533     * Listener for applying window insets on a view in a custom way.
22534     *
22535     * <p>Apps may choose to implement this interface if they want to apply custom policy
22536     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
22537     * is set, its
22538     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
22539     * method will be called instead of the View's own
22540     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
22541     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
22542     * the View's normal behavior as part of its own.</p>
22543     */
22544    public interface OnApplyWindowInsetsListener {
22545        /**
22546         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
22547         * on a View, this listener method will be called instead of the view's own
22548         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
22549         *
22550         * @param v The view applying window insets
22551         * @param insets The insets to apply
22552         * @return The insets supplied, minus any insets that were consumed
22553         */
22554        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
22555    }
22556
22557    private final class UnsetPressedState implements Runnable {
22558        @Override
22559        public void run() {
22560            setPressed(false);
22561        }
22562    }
22563
22564    /**
22565     * Base class for derived classes that want to save and restore their own
22566     * state in {@link android.view.View#onSaveInstanceState()}.
22567     */
22568    public static class BaseSavedState extends AbsSavedState {
22569        String mStartActivityRequestWhoSaved;
22570
22571        /**
22572         * Constructor used when reading from a parcel. Reads the state of the superclass.
22573         *
22574         * @param source
22575         */
22576        public BaseSavedState(Parcel source) {
22577            super(source);
22578            mStartActivityRequestWhoSaved = source.readString();
22579        }
22580
22581        /**
22582         * Constructor called by derived classes when creating their SavedState objects
22583         *
22584         * @param superState The state of the superclass of this view
22585         */
22586        public BaseSavedState(Parcelable superState) {
22587            super(superState);
22588        }
22589
22590        @Override
22591        public void writeToParcel(Parcel out, int flags) {
22592            super.writeToParcel(out, flags);
22593            out.writeString(mStartActivityRequestWhoSaved);
22594        }
22595
22596        public static final Parcelable.Creator<BaseSavedState> CREATOR =
22597                new Parcelable.Creator<BaseSavedState>() {
22598            public BaseSavedState createFromParcel(Parcel in) {
22599                return new BaseSavedState(in);
22600            }
22601
22602            public BaseSavedState[] newArray(int size) {
22603                return new BaseSavedState[size];
22604            }
22605        };
22606    }
22607
22608    /**
22609     * A set of information given to a view when it is attached to its parent
22610     * window.
22611     */
22612    final static class AttachInfo {
22613        interface Callbacks {
22614            void playSoundEffect(int effectId);
22615            boolean performHapticFeedback(int effectId, boolean always);
22616        }
22617
22618        /**
22619         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
22620         * to a Handler. This class contains the target (View) to invalidate and
22621         * the coordinates of the dirty rectangle.
22622         *
22623         * For performance purposes, this class also implements a pool of up to
22624         * POOL_LIMIT objects that get reused. This reduces memory allocations
22625         * whenever possible.
22626         */
22627        static class InvalidateInfo {
22628            private static final int POOL_LIMIT = 10;
22629
22630            private static final SynchronizedPool<InvalidateInfo> sPool =
22631                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
22632
22633            View target;
22634
22635            int left;
22636            int top;
22637            int right;
22638            int bottom;
22639
22640            public static InvalidateInfo obtain() {
22641                InvalidateInfo instance = sPool.acquire();
22642                return (instance != null) ? instance : new InvalidateInfo();
22643            }
22644
22645            public void recycle() {
22646                target = null;
22647                sPool.release(this);
22648            }
22649        }
22650
22651        final IWindowSession mSession;
22652
22653        final IWindow mWindow;
22654
22655        final IBinder mWindowToken;
22656
22657        final Display mDisplay;
22658
22659        final Callbacks mRootCallbacks;
22660
22661        IWindowId mIWindowId;
22662        WindowId mWindowId;
22663
22664        /**
22665         * The top view of the hierarchy.
22666         */
22667        View mRootView;
22668
22669        IBinder mPanelParentWindowToken;
22670
22671        boolean mHardwareAccelerated;
22672        boolean mHardwareAccelerationRequested;
22673        ThreadedRenderer mHardwareRenderer;
22674        List<RenderNode> mPendingAnimatingRenderNodes;
22675
22676        /**
22677         * The state of the display to which the window is attached, as reported
22678         * by {@link Display#getState()}.  Note that the display state constants
22679         * declared by {@link Display} do not exactly line up with the screen state
22680         * constants declared by {@link View} (there are more display states than
22681         * screen states).
22682         */
22683        int mDisplayState = Display.STATE_UNKNOWN;
22684
22685        /**
22686         * Scale factor used by the compatibility mode
22687         */
22688        float mApplicationScale;
22689
22690        /**
22691         * Indicates whether the application is in compatibility mode
22692         */
22693        boolean mScalingRequired;
22694
22695        /**
22696         * Left position of this view's window
22697         */
22698        int mWindowLeft;
22699
22700        /**
22701         * Top position of this view's window
22702         */
22703        int mWindowTop;
22704
22705        /**
22706         * Indicates whether views need to use 32-bit drawing caches
22707         */
22708        boolean mUse32BitDrawingCache;
22709
22710        /**
22711         * For windows that are full-screen but using insets to layout inside
22712         * of the screen areas, these are the current insets to appear inside
22713         * the overscan area of the display.
22714         */
22715        final Rect mOverscanInsets = new Rect();
22716
22717        /**
22718         * For windows that are full-screen but using insets to layout inside
22719         * of the screen decorations, these are the current insets for the
22720         * content of the window.
22721         */
22722        final Rect mContentInsets = new Rect();
22723
22724        /**
22725         * For windows that are full-screen but using insets to layout inside
22726         * of the screen decorations, these are the current insets for the
22727         * actual visible parts of the window.
22728         */
22729        final Rect mVisibleInsets = new Rect();
22730
22731        /**
22732         * For windows that are full-screen but using insets to layout inside
22733         * of the screen decorations, these are the current insets for the
22734         * stable system windows.
22735         */
22736        final Rect mStableInsets = new Rect();
22737
22738        /**
22739         * For windows that include areas that are not covered by real surface these are the outsets
22740         * for real surface.
22741         */
22742        final Rect mOutsets = new Rect();
22743
22744        /**
22745         * In multi-window we force show the navigation bar. Because we don't want that the surface
22746         * size changes in this mode, we instead have a flag whether the navigation bar size should
22747         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
22748         */
22749        boolean mAlwaysConsumeNavBar;
22750
22751        /**
22752         * The internal insets given by this window.  This value is
22753         * supplied by the client (through
22754         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
22755         * be given to the window manager when changed to be used in laying
22756         * out windows behind it.
22757         */
22758        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
22759                = new ViewTreeObserver.InternalInsetsInfo();
22760
22761        /**
22762         * Set to true when mGivenInternalInsets is non-empty.
22763         */
22764        boolean mHasNonEmptyGivenInternalInsets;
22765
22766        /**
22767         * All views in the window's hierarchy that serve as scroll containers,
22768         * used to determine if the window can be resized or must be panned
22769         * to adjust for a soft input area.
22770         */
22771        final ArrayList<View> mScrollContainers = new ArrayList<View>();
22772
22773        final KeyEvent.DispatcherState mKeyDispatchState
22774                = new KeyEvent.DispatcherState();
22775
22776        /**
22777         * Indicates whether the view's window currently has the focus.
22778         */
22779        boolean mHasWindowFocus;
22780
22781        /**
22782         * The current visibility of the window.
22783         */
22784        int mWindowVisibility;
22785
22786        /**
22787         * Indicates the time at which drawing started to occur.
22788         */
22789        long mDrawingTime;
22790
22791        /**
22792         * Indicates whether or not ignoring the DIRTY_MASK flags.
22793         */
22794        boolean mIgnoreDirtyState;
22795
22796        /**
22797         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
22798         * to avoid clearing that flag prematurely.
22799         */
22800        boolean mSetIgnoreDirtyState = false;
22801
22802        /**
22803         * Indicates whether the view's window is currently in touch mode.
22804         */
22805        boolean mInTouchMode;
22806
22807        /**
22808         * Indicates whether the view has requested unbuffered input dispatching for the current
22809         * event stream.
22810         */
22811        boolean mUnbufferedDispatchRequested;
22812
22813        /**
22814         * Indicates that ViewAncestor should trigger a global layout change
22815         * the next time it performs a traversal
22816         */
22817        boolean mRecomputeGlobalAttributes;
22818
22819        /**
22820         * Always report new attributes at next traversal.
22821         */
22822        boolean mForceReportNewAttributes;
22823
22824        /**
22825         * Set during a traveral if any views want to keep the screen on.
22826         */
22827        boolean mKeepScreenOn;
22828
22829        /**
22830         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
22831         */
22832        int mSystemUiVisibility;
22833
22834        /**
22835         * Hack to force certain system UI visibility flags to be cleared.
22836         */
22837        int mDisabledSystemUiVisibility;
22838
22839        /**
22840         * Last global system UI visibility reported by the window manager.
22841         */
22842        int mGlobalSystemUiVisibility;
22843
22844        /**
22845         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
22846         * attached.
22847         */
22848        boolean mHasSystemUiListeners;
22849
22850        /**
22851         * Set if the window has requested to extend into the overscan region
22852         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
22853         */
22854        boolean mOverscanRequested;
22855
22856        /**
22857         * Set if the visibility of any views has changed.
22858         */
22859        boolean mViewVisibilityChanged;
22860
22861        /**
22862         * Set to true if a view has been scrolled.
22863         */
22864        boolean mViewScrollChanged;
22865
22866        /**
22867         * Set to true if high contrast mode enabled
22868         */
22869        boolean mHighContrastText;
22870
22871        /**
22872         * Set to true if a pointer event is currently being handled.
22873         */
22874        boolean mHandlingPointerEvent;
22875
22876        /**
22877         * Global to the view hierarchy used as a temporary for dealing with
22878         * x/y points in the transparent region computations.
22879         */
22880        final int[] mTransparentLocation = new int[2];
22881
22882        /**
22883         * Global to the view hierarchy used as a temporary for dealing with
22884         * x/y points in the ViewGroup.invalidateChild implementation.
22885         */
22886        final int[] mInvalidateChildLocation = new int[2];
22887
22888        /**
22889         * Global to the view hierarchy used as a temporary for dealng with
22890         * computing absolute on-screen location.
22891         */
22892        final int[] mTmpLocation = new int[2];
22893
22894        /**
22895         * Global to the view hierarchy used as a temporary for dealing with
22896         * x/y location when view is transformed.
22897         */
22898        final float[] mTmpTransformLocation = new float[2];
22899
22900        /**
22901         * The view tree observer used to dispatch global events like
22902         * layout, pre-draw, touch mode change, etc.
22903         */
22904        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
22905
22906        /**
22907         * A Canvas used by the view hierarchy to perform bitmap caching.
22908         */
22909        Canvas mCanvas;
22910
22911        /**
22912         * The view root impl.
22913         */
22914        final ViewRootImpl mViewRootImpl;
22915
22916        /**
22917         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
22918         * handler can be used to pump events in the UI events queue.
22919         */
22920        final Handler mHandler;
22921
22922        /**
22923         * Temporary for use in computing invalidate rectangles while
22924         * calling up the hierarchy.
22925         */
22926        final Rect mTmpInvalRect = new Rect();
22927
22928        /**
22929         * Temporary for use in computing hit areas with transformed views
22930         */
22931        final RectF mTmpTransformRect = new RectF();
22932
22933        /**
22934         * Temporary for use in computing hit areas with transformed views
22935         */
22936        final RectF mTmpTransformRect1 = new RectF();
22937
22938        /**
22939         * Temporary list of rectanges.
22940         */
22941        final List<RectF> mTmpRectList = new ArrayList<>();
22942
22943        /**
22944         * Temporary for use in transforming invalidation rect
22945         */
22946        final Matrix mTmpMatrix = new Matrix();
22947
22948        /**
22949         * Temporary for use in transforming invalidation rect
22950         */
22951        final Transformation mTmpTransformation = new Transformation();
22952
22953        /**
22954         * Temporary for use in querying outlines from OutlineProviders
22955         */
22956        final Outline mTmpOutline = new Outline();
22957
22958        /**
22959         * Temporary list for use in collecting focusable descendents of a view.
22960         */
22961        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
22962
22963        /**
22964         * The id of the window for accessibility purposes.
22965         */
22966        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
22967
22968        /**
22969         * Flags related to accessibility processing.
22970         *
22971         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
22972         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
22973         */
22974        int mAccessibilityFetchFlags;
22975
22976        /**
22977         * The drawable for highlighting accessibility focus.
22978         */
22979        Drawable mAccessibilityFocusDrawable;
22980
22981        /**
22982         * Show where the margins, bounds and layout bounds are for each view.
22983         */
22984        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
22985
22986        /**
22987         * Point used to compute visible regions.
22988         */
22989        final Point mPoint = new Point();
22990
22991        /**
22992         * Used to track which View originated a requestLayout() call, used when
22993         * requestLayout() is called during layout.
22994         */
22995        View mViewRequestingLayout;
22996
22997        /**
22998         * Used to track views that need (at least) a partial relayout at their current size
22999         * during the next traversal.
23000         */
23001        List<View> mPartialLayoutViews = new ArrayList<>();
23002
23003        /**
23004         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23005         * modification. Lazily assigned during ViewRootImpl layout.
23006         */
23007        List<View> mEmptyPartialLayoutViews;
23008
23009        /**
23010         * Used to track the identity of the current drag operation.
23011         */
23012        IBinder mDragToken;
23013
23014        /**
23015         * The drag shadow surface for the current drag operation.
23016         */
23017        public Surface mDragSurface;
23018
23019        /**
23020         * Creates a new set of attachment information with the specified
23021         * events handler and thread.
23022         *
23023         * @param handler the events handler the view must use
23024         */
23025        AttachInfo(IWindowSession session, IWindow window, Display display,
23026                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
23027            mSession = session;
23028            mWindow = window;
23029            mWindowToken = window.asBinder();
23030            mDisplay = display;
23031            mViewRootImpl = viewRootImpl;
23032            mHandler = handler;
23033            mRootCallbacks = effectPlayer;
23034        }
23035    }
23036
23037    /**
23038     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23039     * is supported. This avoids keeping too many unused fields in most
23040     * instances of View.</p>
23041     */
23042    private static class ScrollabilityCache implements Runnable {
23043
23044        /**
23045         * Scrollbars are not visible
23046         */
23047        public static final int OFF = 0;
23048
23049        /**
23050         * Scrollbars are visible
23051         */
23052        public static final int ON = 1;
23053
23054        /**
23055         * Scrollbars are fading away
23056         */
23057        public static final int FADING = 2;
23058
23059        public boolean fadeScrollBars;
23060
23061        public int fadingEdgeLength;
23062        public int scrollBarDefaultDelayBeforeFade;
23063        public int scrollBarFadeDuration;
23064
23065        public int scrollBarSize;
23066        public ScrollBarDrawable scrollBar;
23067        public float[] interpolatorValues;
23068        public View host;
23069
23070        public final Paint paint;
23071        public final Matrix matrix;
23072        public Shader shader;
23073
23074        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23075
23076        private static final float[] OPAQUE = { 255 };
23077        private static final float[] TRANSPARENT = { 0.0f };
23078
23079        /**
23080         * When fading should start. This time moves into the future every time
23081         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23082         */
23083        public long fadeStartTime;
23084
23085
23086        /**
23087         * The current state of the scrollbars: ON, OFF, or FADING
23088         */
23089        public int state = OFF;
23090
23091        private int mLastColor;
23092
23093        public final Rect mScrollBarBounds = new Rect();
23094
23095        public static final int NOT_DRAGGING = 0;
23096        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23097        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23098        public int mScrollBarDraggingState = NOT_DRAGGING;
23099
23100        public float mScrollBarDraggingPos = 0;
23101
23102        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23103            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23104            scrollBarSize = configuration.getScaledScrollBarSize();
23105            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23106            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23107
23108            paint = new Paint();
23109            matrix = new Matrix();
23110            // use use a height of 1, and then wack the matrix each time we
23111            // actually use it.
23112            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23113            paint.setShader(shader);
23114            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23115
23116            this.host = host;
23117        }
23118
23119        public void setFadeColor(int color) {
23120            if (color != mLastColor) {
23121                mLastColor = color;
23122
23123                if (color != 0) {
23124                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23125                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23126                    paint.setShader(shader);
23127                    // Restore the default transfer mode (src_over)
23128                    paint.setXfermode(null);
23129                } else {
23130                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23131                    paint.setShader(shader);
23132                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23133                }
23134            }
23135        }
23136
23137        public void run() {
23138            long now = AnimationUtils.currentAnimationTimeMillis();
23139            if (now >= fadeStartTime) {
23140
23141                // the animation fades the scrollbars out by changing
23142                // the opacity (alpha) from fully opaque to fully
23143                // transparent
23144                int nextFrame = (int) now;
23145                int framesCount = 0;
23146
23147                Interpolator interpolator = scrollBarInterpolator;
23148
23149                // Start opaque
23150                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23151
23152                // End transparent
23153                nextFrame += scrollBarFadeDuration;
23154                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23155
23156                state = FADING;
23157
23158                // Kick off the fade animation
23159                host.invalidate(true);
23160            }
23161        }
23162    }
23163
23164    /**
23165     * Resuable callback for sending
23166     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23167     */
23168    private class SendViewScrolledAccessibilityEvent implements Runnable {
23169        public volatile boolean mIsPending;
23170
23171        public void run() {
23172            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23173            mIsPending = false;
23174        }
23175    }
23176
23177    /**
23178     * <p>
23179     * This class represents a delegate that can be registered in a {@link View}
23180     * to enhance accessibility support via composition rather via inheritance.
23181     * It is specifically targeted to widget developers that extend basic View
23182     * classes i.e. classes in package android.view, that would like their
23183     * applications to be backwards compatible.
23184     * </p>
23185     * <div class="special reference">
23186     * <h3>Developer Guides</h3>
23187     * <p>For more information about making applications accessible, read the
23188     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23189     * developer guide.</p>
23190     * </div>
23191     * <p>
23192     * A scenario in which a developer would like to use an accessibility delegate
23193     * is overriding a method introduced in a later API version then the minimal API
23194     * version supported by the application. For example, the method
23195     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23196     * in API version 4 when the accessibility APIs were first introduced. If a
23197     * developer would like his application to run on API version 4 devices (assuming
23198     * all other APIs used by the application are version 4 or lower) and take advantage
23199     * of this method, instead of overriding the method which would break the application's
23200     * backwards compatibility, he can override the corresponding method in this
23201     * delegate and register the delegate in the target View if the API version of
23202     * the system is high enough i.e. the API version is same or higher to the API
23203     * version that introduced
23204     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23205     * </p>
23206     * <p>
23207     * Here is an example implementation:
23208     * </p>
23209     * <code><pre><p>
23210     * if (Build.VERSION.SDK_INT >= 14) {
23211     *     // If the API version is equal of higher than the version in
23212     *     // which onInitializeAccessibilityNodeInfo was introduced we
23213     *     // register a delegate with a customized implementation.
23214     *     View view = findViewById(R.id.view_id);
23215     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23216     *         public void onInitializeAccessibilityNodeInfo(View host,
23217     *                 AccessibilityNodeInfo info) {
23218     *             // Let the default implementation populate the info.
23219     *             super.onInitializeAccessibilityNodeInfo(host, info);
23220     *             // Set some other information.
23221     *             info.setEnabled(host.isEnabled());
23222     *         }
23223     *     });
23224     * }
23225     * </code></pre></p>
23226     * <p>
23227     * This delegate contains methods that correspond to the accessibility methods
23228     * in View. If a delegate has been specified the implementation in View hands
23229     * off handling to the corresponding method in this delegate. The default
23230     * implementation the delegate methods behaves exactly as the corresponding
23231     * method in View for the case of no accessibility delegate been set. Hence,
23232     * to customize the behavior of a View method, clients can override only the
23233     * corresponding delegate method without altering the behavior of the rest
23234     * accessibility related methods of the host view.
23235     * </p>
23236     * <p>
23237     * <strong>Note:</strong> On platform versions prior to
23238     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23239     * views in the {@code android.widget.*} package are called <i>before</i>
23240     * host methods. This prevents certain properties such as class name from
23241     * being modified by overriding
23242     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23243     * as any changes will be overwritten by the host class.
23244     * <p>
23245     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23246     * methods are called <i>after</i> host methods, which all properties to be
23247     * modified without being overwritten by the host class.
23248     */
23249    public static class AccessibilityDelegate {
23250
23251        /**
23252         * Sends an accessibility event of the given type. If accessibility is not
23253         * enabled this method has no effect.
23254         * <p>
23255         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23256         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23257         * been set.
23258         * </p>
23259         *
23260         * @param host The View hosting the delegate.
23261         * @param eventType The type of the event to send.
23262         *
23263         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23264         */
23265        public void sendAccessibilityEvent(View host, int eventType) {
23266            host.sendAccessibilityEventInternal(eventType);
23267        }
23268
23269        /**
23270         * Performs the specified accessibility action on the view. For
23271         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23272         * <p>
23273         * The default implementation behaves as
23274         * {@link View#performAccessibilityAction(int, Bundle)
23275         *  View#performAccessibilityAction(int, Bundle)} for the case of
23276         *  no accessibility delegate been set.
23277         * </p>
23278         *
23279         * @param action The action to perform.
23280         * @return Whether the action was performed.
23281         *
23282         * @see View#performAccessibilityAction(int, Bundle)
23283         *      View#performAccessibilityAction(int, Bundle)
23284         */
23285        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23286            return host.performAccessibilityActionInternal(action, args);
23287        }
23288
23289        /**
23290         * Sends an accessibility event. This method behaves exactly as
23291         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23292         * empty {@link AccessibilityEvent} and does not perform a check whether
23293         * accessibility is enabled.
23294         * <p>
23295         * The default implementation behaves as
23296         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23297         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23298         * the case of no accessibility delegate been set.
23299         * </p>
23300         *
23301         * @param host The View hosting the delegate.
23302         * @param event The event to send.
23303         *
23304         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23305         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23306         */
23307        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23308            host.sendAccessibilityEventUncheckedInternal(event);
23309        }
23310
23311        /**
23312         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23313         * to its children for adding their text content to the event.
23314         * <p>
23315         * The default implementation behaves as
23316         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23317         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23318         * the case of no accessibility delegate been set.
23319         * </p>
23320         *
23321         * @param host The View hosting the delegate.
23322         * @param event The event.
23323         * @return True if the event population was completed.
23324         *
23325         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23326         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23327         */
23328        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23329            return host.dispatchPopulateAccessibilityEventInternal(event);
23330        }
23331
23332        /**
23333         * Gives a chance to the host View to populate the accessibility event with its
23334         * text content.
23335         * <p>
23336         * The default implementation behaves as
23337         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23338         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23339         * the case of no accessibility delegate been set.
23340         * </p>
23341         *
23342         * @param host The View hosting the delegate.
23343         * @param event The accessibility event which to populate.
23344         *
23345         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23346         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23347         */
23348        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23349            host.onPopulateAccessibilityEventInternal(event);
23350        }
23351
23352        /**
23353         * Initializes an {@link AccessibilityEvent} with information about the
23354         * the host View which is the event source.
23355         * <p>
23356         * The default implementation behaves as
23357         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23358         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23359         * the case of no accessibility delegate been set.
23360         * </p>
23361         *
23362         * @param host The View hosting the delegate.
23363         * @param event The event to initialize.
23364         *
23365         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23366         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23367         */
23368        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23369            host.onInitializeAccessibilityEventInternal(event);
23370        }
23371
23372        /**
23373         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
23374         * <p>
23375         * The default implementation behaves as
23376         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23377         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
23378         * the case of no accessibility delegate been set.
23379         * </p>
23380         *
23381         * @param host The View hosting the delegate.
23382         * @param info The instance to initialize.
23383         *
23384         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23385         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23386         */
23387        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
23388            host.onInitializeAccessibilityNodeInfoInternal(info);
23389        }
23390
23391        /**
23392         * Called when a child of the host View has requested sending an
23393         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
23394         * to augment the event.
23395         * <p>
23396         * The default implementation behaves as
23397         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23398         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
23399         * the case of no accessibility delegate been set.
23400         * </p>
23401         *
23402         * @param host The View hosting the delegate.
23403         * @param child The child which requests sending the event.
23404         * @param event The event to be sent.
23405         * @return True if the event should be sent
23406         *
23407         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23408         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23409         */
23410        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
23411                AccessibilityEvent event) {
23412            return host.onRequestSendAccessibilityEventInternal(child, event);
23413        }
23414
23415        /**
23416         * Gets the provider for managing a virtual view hierarchy rooted at this View
23417         * and reported to {@link android.accessibilityservice.AccessibilityService}s
23418         * that explore the window content.
23419         * <p>
23420         * The default implementation behaves as
23421         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
23422         * the case of no accessibility delegate been set.
23423         * </p>
23424         *
23425         * @return The provider.
23426         *
23427         * @see AccessibilityNodeProvider
23428         */
23429        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
23430            return null;
23431        }
23432
23433        /**
23434         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
23435         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
23436         * This method is responsible for obtaining an accessibility node info from a
23437         * pool of reusable instances and calling
23438         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
23439         * view to initialize the former.
23440         * <p>
23441         * <strong>Note:</strong> The client is responsible for recycling the obtained
23442         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
23443         * creation.
23444         * </p>
23445         * <p>
23446         * The default implementation behaves as
23447         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
23448         * the case of no accessibility delegate been set.
23449         * </p>
23450         * @return A populated {@link AccessibilityNodeInfo}.
23451         *
23452         * @see AccessibilityNodeInfo
23453         *
23454         * @hide
23455         */
23456        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
23457            return host.createAccessibilityNodeInfoInternal();
23458        }
23459    }
23460
23461    private class MatchIdPredicate implements Predicate<View> {
23462        public int mId;
23463
23464        @Override
23465        public boolean apply(View view) {
23466            return (view.mID == mId);
23467        }
23468    }
23469
23470    private class MatchLabelForPredicate implements Predicate<View> {
23471        private int mLabeledId;
23472
23473        @Override
23474        public boolean apply(View view) {
23475            return (view.mLabelForId == mLabeledId);
23476        }
23477    }
23478
23479    private class SendViewStateChangedAccessibilityEvent implements Runnable {
23480        private int mChangeTypes = 0;
23481        private boolean mPosted;
23482        private boolean mPostedWithDelay;
23483        private long mLastEventTimeMillis;
23484
23485        @Override
23486        public void run() {
23487            mPosted = false;
23488            mPostedWithDelay = false;
23489            mLastEventTimeMillis = SystemClock.uptimeMillis();
23490            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
23491                final AccessibilityEvent event = AccessibilityEvent.obtain();
23492                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
23493                event.setContentChangeTypes(mChangeTypes);
23494                sendAccessibilityEventUnchecked(event);
23495            }
23496            mChangeTypes = 0;
23497        }
23498
23499        public void runOrPost(int changeType) {
23500            mChangeTypes |= changeType;
23501
23502            // If this is a live region or the child of a live region, collect
23503            // all events from this frame and send them on the next frame.
23504            if (inLiveRegion()) {
23505                // If we're already posted with a delay, remove that.
23506                if (mPostedWithDelay) {
23507                    removeCallbacks(this);
23508                    mPostedWithDelay = false;
23509                }
23510                // Only post if we're not already posted.
23511                if (!mPosted) {
23512                    post(this);
23513                    mPosted = true;
23514                }
23515                return;
23516            }
23517
23518            if (mPosted) {
23519                return;
23520            }
23521
23522            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
23523            final long minEventIntevalMillis =
23524                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
23525            if (timeSinceLastMillis >= minEventIntevalMillis) {
23526                removeCallbacks(this);
23527                run();
23528            } else {
23529                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
23530                mPostedWithDelay = true;
23531            }
23532        }
23533    }
23534
23535    private boolean inLiveRegion() {
23536        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23537            return true;
23538        }
23539
23540        ViewParent parent = getParent();
23541        while (parent instanceof View) {
23542            if (((View) parent).getAccessibilityLiveRegion()
23543                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23544                return true;
23545            }
23546            parent = parent.getParent();
23547        }
23548
23549        return false;
23550    }
23551
23552    /**
23553     * Dump all private flags in readable format, useful for documentation and
23554     * sanity checking.
23555     */
23556    private static void dumpFlags() {
23557        final HashMap<String, String> found = Maps.newHashMap();
23558        try {
23559            for (Field field : View.class.getDeclaredFields()) {
23560                final int modifiers = field.getModifiers();
23561                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
23562                    if (field.getType().equals(int.class)) {
23563                        final int value = field.getInt(null);
23564                        dumpFlag(found, field.getName(), value);
23565                    } else if (field.getType().equals(int[].class)) {
23566                        final int[] values = (int[]) field.get(null);
23567                        for (int i = 0; i < values.length; i++) {
23568                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
23569                        }
23570                    }
23571                }
23572            }
23573        } catch (IllegalAccessException e) {
23574            throw new RuntimeException(e);
23575        }
23576
23577        final ArrayList<String> keys = Lists.newArrayList();
23578        keys.addAll(found.keySet());
23579        Collections.sort(keys);
23580        for (String key : keys) {
23581            Log.d(VIEW_LOG_TAG, found.get(key));
23582        }
23583    }
23584
23585    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
23586        // Sort flags by prefix, then by bits, always keeping unique keys
23587        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
23588        final int prefix = name.indexOf('_');
23589        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
23590        final String output = bits + " " + name;
23591        found.put(key, output);
23592    }
23593
23594    /** {@hide} */
23595    public void encode(@NonNull ViewHierarchyEncoder stream) {
23596        stream.beginObject(this);
23597        encodeProperties(stream);
23598        stream.endObject();
23599    }
23600
23601    /** {@hide} */
23602    @CallSuper
23603    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
23604        Object resolveId = ViewDebug.resolveId(getContext(), mID);
23605        if (resolveId instanceof String) {
23606            stream.addProperty("id", (String) resolveId);
23607        } else {
23608            stream.addProperty("id", mID);
23609        }
23610
23611        stream.addProperty("misc:transformation.alpha",
23612                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
23613        stream.addProperty("misc:transitionName", getTransitionName());
23614
23615        // layout
23616        stream.addProperty("layout:left", mLeft);
23617        stream.addProperty("layout:right", mRight);
23618        stream.addProperty("layout:top", mTop);
23619        stream.addProperty("layout:bottom", mBottom);
23620        stream.addProperty("layout:width", getWidth());
23621        stream.addProperty("layout:height", getHeight());
23622        stream.addProperty("layout:layoutDirection", getLayoutDirection());
23623        stream.addProperty("layout:layoutRtl", isLayoutRtl());
23624        stream.addProperty("layout:hasTransientState", hasTransientState());
23625        stream.addProperty("layout:baseline", getBaseline());
23626
23627        // layout params
23628        ViewGroup.LayoutParams layoutParams = getLayoutParams();
23629        if (layoutParams != null) {
23630            stream.addPropertyKey("layoutParams");
23631            layoutParams.encode(stream);
23632        }
23633
23634        // scrolling
23635        stream.addProperty("scrolling:scrollX", mScrollX);
23636        stream.addProperty("scrolling:scrollY", mScrollY);
23637
23638        // padding
23639        stream.addProperty("padding:paddingLeft", mPaddingLeft);
23640        stream.addProperty("padding:paddingRight", mPaddingRight);
23641        stream.addProperty("padding:paddingTop", mPaddingTop);
23642        stream.addProperty("padding:paddingBottom", mPaddingBottom);
23643        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
23644        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
23645        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
23646        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
23647        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
23648
23649        // measurement
23650        stream.addProperty("measurement:minHeight", mMinHeight);
23651        stream.addProperty("measurement:minWidth", mMinWidth);
23652        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
23653        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
23654
23655        // drawing
23656        stream.addProperty("drawing:elevation", getElevation());
23657        stream.addProperty("drawing:translationX", getTranslationX());
23658        stream.addProperty("drawing:translationY", getTranslationY());
23659        stream.addProperty("drawing:translationZ", getTranslationZ());
23660        stream.addProperty("drawing:rotation", getRotation());
23661        stream.addProperty("drawing:rotationX", getRotationX());
23662        stream.addProperty("drawing:rotationY", getRotationY());
23663        stream.addProperty("drawing:scaleX", getScaleX());
23664        stream.addProperty("drawing:scaleY", getScaleY());
23665        stream.addProperty("drawing:pivotX", getPivotX());
23666        stream.addProperty("drawing:pivotY", getPivotY());
23667        stream.addProperty("drawing:opaque", isOpaque());
23668        stream.addProperty("drawing:alpha", getAlpha());
23669        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
23670        stream.addProperty("drawing:shadow", hasShadow());
23671        stream.addProperty("drawing:solidColor", getSolidColor());
23672        stream.addProperty("drawing:layerType", mLayerType);
23673        stream.addProperty("drawing:willNotDraw", willNotDraw());
23674        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
23675        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
23676        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
23677        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
23678
23679        // focus
23680        stream.addProperty("focus:hasFocus", hasFocus());
23681        stream.addProperty("focus:isFocused", isFocused());
23682        stream.addProperty("focus:isFocusable", isFocusable());
23683        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
23684
23685        stream.addProperty("misc:clickable", isClickable());
23686        stream.addProperty("misc:pressed", isPressed());
23687        stream.addProperty("misc:selected", isSelected());
23688        stream.addProperty("misc:touchMode", isInTouchMode());
23689        stream.addProperty("misc:hovered", isHovered());
23690        stream.addProperty("misc:activated", isActivated());
23691
23692        stream.addProperty("misc:visibility", getVisibility());
23693        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
23694        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
23695
23696        stream.addProperty("misc:enabled", isEnabled());
23697        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
23698        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
23699
23700        // theme attributes
23701        Resources.Theme theme = getContext().getTheme();
23702        if (theme != null) {
23703            stream.addPropertyKey("theme");
23704            theme.encode(stream);
23705        }
23706
23707        // view attribute information
23708        int n = mAttributes != null ? mAttributes.length : 0;
23709        stream.addProperty("meta:__attrCount__", n/2);
23710        for (int i = 0; i < n; i += 2) {
23711            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
23712        }
23713
23714        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
23715
23716        // text
23717        stream.addProperty("text:textDirection", getTextDirection());
23718        stream.addProperty("text:textAlignment", getTextAlignment());
23719
23720        // accessibility
23721        CharSequence contentDescription = getContentDescription();
23722        stream.addProperty("accessibility:contentDescription",
23723                contentDescription == null ? "" : contentDescription.toString());
23724        stream.addProperty("accessibility:labelFor", getLabelFor());
23725        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
23726    }
23727}
23728