View.java revision 761f59c19f1a0e527bb533df16abee7fac166dbd
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 handled 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     * |-------|-------|-------|-------|
2438     */
2439
2440    /**
2441     * Flag indicating that view has a transform animation set on it. This is used to track whether
2442     * an animation is cleared between successive frames, in order to tell the associated
2443     * DisplayList to clear its animation matrix.
2444     */
2445    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2446
2447    /**
2448     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2449     * animation is cleared between successive frames, in order to tell the associated
2450     * DisplayList to restore its alpha value.
2451     */
2452    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2453
2454    /**
2455     * Flag indicating that the view has been through at least one layout since it
2456     * was last attached to a window.
2457     */
2458    static final int PFLAG3_IS_LAID_OUT = 0x4;
2459
2460    /**
2461     * Flag indicating that a call to measure() was skipped and should be done
2462     * instead when layout() is invoked.
2463     */
2464    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2465
2466    /**
2467     * Flag indicating that an overridden method correctly called down to
2468     * the superclass implementation as required by the API spec.
2469     */
2470    static final int PFLAG3_CALLED_SUPER = 0x10;
2471
2472    /**
2473     * Flag indicating that we're in the process of applying window insets.
2474     */
2475    static final int PFLAG3_APPLYING_INSETS = 0x20;
2476
2477    /**
2478     * Flag indicating that we're in the process of fitting system windows using the old method.
2479     */
2480    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2481
2482    /**
2483     * Flag indicating that nested scrolling is enabled for this view.
2484     * The view will optionally cooperate with views up its parent chain to allow for
2485     * integrated nested scrolling along the same axis.
2486     */
2487    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2488
2489    /**
2490     * Flag indicating that the bottom scroll indicator should be displayed
2491     * when this view can scroll up.
2492     */
2493    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2494
2495    /**
2496     * Flag indicating that the bottom scroll indicator should be displayed
2497     * when this view can scroll down.
2498     */
2499    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2500
2501    /**
2502     * Flag indicating that the left scroll indicator should be displayed
2503     * when this view can scroll left.
2504     */
2505    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2506
2507    /**
2508     * Flag indicating that the right scroll indicator should be displayed
2509     * when this view can scroll right.
2510     */
2511    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2512
2513    /**
2514     * Flag indicating that the start scroll indicator should be displayed
2515     * when this view can scroll in the start direction.
2516     */
2517    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2518
2519    /**
2520     * Flag indicating that the end scroll indicator should be displayed
2521     * when this view can scroll in the end direction.
2522     */
2523    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2524
2525    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2526
2527    static final int SCROLL_INDICATORS_NONE = 0x0000;
2528
2529    /**
2530     * Mask for use with setFlags indicating bits used for indicating which
2531     * scroll indicators are enabled.
2532     */
2533    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2534            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2535            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2536            | PFLAG3_SCROLL_INDICATOR_END;
2537
2538    /**
2539     * Left-shift required to translate between public scroll indicator flags
2540     * and internal PFLAGS3 flags. When used as a right-shift, translates
2541     * PFLAGS3 flags to public flags.
2542     */
2543    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2544
2545    /** @hide */
2546    @Retention(RetentionPolicy.SOURCE)
2547    @IntDef(flag = true,
2548            value = {
2549                    SCROLL_INDICATOR_TOP,
2550                    SCROLL_INDICATOR_BOTTOM,
2551                    SCROLL_INDICATOR_LEFT,
2552                    SCROLL_INDICATOR_RIGHT,
2553                    SCROLL_INDICATOR_START,
2554                    SCROLL_INDICATOR_END,
2555            })
2556    public @interface ScrollIndicators {}
2557
2558    /**
2559     * Scroll indicator direction for the top edge of the view.
2560     *
2561     * @see #setScrollIndicators(int)
2562     * @see #setScrollIndicators(int, int)
2563     * @see #getScrollIndicators()
2564     */
2565    public static final int SCROLL_INDICATOR_TOP =
2566            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2567
2568    /**
2569     * Scroll indicator direction for the bottom edge of the view.
2570     *
2571     * @see #setScrollIndicators(int)
2572     * @see #setScrollIndicators(int, int)
2573     * @see #getScrollIndicators()
2574     */
2575    public static final int SCROLL_INDICATOR_BOTTOM =
2576            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2577
2578    /**
2579     * Scroll indicator direction for the left edge of the view.
2580     *
2581     * @see #setScrollIndicators(int)
2582     * @see #setScrollIndicators(int, int)
2583     * @see #getScrollIndicators()
2584     */
2585    public static final int SCROLL_INDICATOR_LEFT =
2586            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2587
2588    /**
2589     * Scroll indicator direction for the right edge of the view.
2590     *
2591     * @see #setScrollIndicators(int)
2592     * @see #setScrollIndicators(int, int)
2593     * @see #getScrollIndicators()
2594     */
2595    public static final int SCROLL_INDICATOR_RIGHT =
2596            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2597
2598    /**
2599     * Scroll indicator direction for the starting edge of the view.
2600     * <p>
2601     * Resolved according to the view's layout direction, see
2602     * {@link #getLayoutDirection()} for more information.
2603     *
2604     * @see #setScrollIndicators(int)
2605     * @see #setScrollIndicators(int, int)
2606     * @see #getScrollIndicators()
2607     */
2608    public static final int SCROLL_INDICATOR_START =
2609            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2610
2611    /**
2612     * Scroll indicator direction for the ending edge of the view.
2613     * <p>
2614     * Resolved according to the view's layout direction, see
2615     * {@link #getLayoutDirection()} for more information.
2616     *
2617     * @see #setScrollIndicators(int)
2618     * @see #setScrollIndicators(int, int)
2619     * @see #getScrollIndicators()
2620     */
2621    public static final int SCROLL_INDICATOR_END =
2622            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2623
2624    /**
2625     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2626     * into this view.<p>
2627     */
2628    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2629
2630    /**
2631     * The mask for use with private flags indicating bits used for pointer icon shapes.
2632     */
2633    static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000;
2634
2635    /**
2636     * Left-shift used for pointer icon shape values in private flags.
2637     */
2638    static final int PFLAG3_POINTER_ICON_LSHIFT = 15;
2639
2640    /**
2641     * Value indicating no specific pointer icons.
2642     */
2643    private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT;
2644
2645    /**
2646     * Value indicating {@link PointerIcon.STYLE_NULL}.
2647     */
2648    private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT;
2649
2650    /**
2651     * The base value for other pointer icon shapes.
2652     */
2653    private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT;
2654
2655    /**
2656     * Whether this view has rendered elements that overlap (see {@link
2657     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2658     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2659     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2660     * determined by whatever {@link #hasOverlappingRendering()} returns.
2661     */
2662    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2663
2664    /**
2665     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2666     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2667     */
2668    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2669
2670    /* End of masks for mPrivateFlags3 */
2671
2672    /**
2673     * Always allow a user to over-scroll this view, provided it is a
2674     * view that can scroll.
2675     *
2676     * @see #getOverScrollMode()
2677     * @see #setOverScrollMode(int)
2678     */
2679    public static final int OVER_SCROLL_ALWAYS = 0;
2680
2681    /**
2682     * Allow a user to over-scroll this view only if the content is large
2683     * enough to meaningfully scroll, provided it is a view that can scroll.
2684     *
2685     * @see #getOverScrollMode()
2686     * @see #setOverScrollMode(int)
2687     */
2688    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2689
2690    /**
2691     * Never allow a user to over-scroll this view.
2692     *
2693     * @see #getOverScrollMode()
2694     * @see #setOverScrollMode(int)
2695     */
2696    public static final int OVER_SCROLL_NEVER = 2;
2697
2698    /**
2699     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2700     * requested the system UI (status bar) to be visible (the default).
2701     *
2702     * @see #setSystemUiVisibility(int)
2703     */
2704    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2705
2706    /**
2707     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2708     * system UI to enter an unobtrusive "low profile" mode.
2709     *
2710     * <p>This is for use in games, book readers, video players, or any other
2711     * "immersive" application where the usual system chrome is deemed too distracting.
2712     *
2713     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2714     *
2715     * @see #setSystemUiVisibility(int)
2716     */
2717    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2718
2719    /**
2720     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2721     * system navigation be temporarily hidden.
2722     *
2723     * <p>This is an even less obtrusive state than that called for by
2724     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2725     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2726     * those to disappear. This is useful (in conjunction with the
2727     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2728     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2729     * window flags) for displaying content using every last pixel on the display.
2730     *
2731     * <p>There is a limitation: because navigation controls are so important, the least user
2732     * interaction will cause them to reappear immediately.  When this happens, both
2733     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2734     * so that both elements reappear at the same time.
2735     *
2736     * @see #setSystemUiVisibility(int)
2737     */
2738    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2739
2740    /**
2741     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2742     * into the normal fullscreen mode so that its content can take over the screen
2743     * while still allowing the user to interact with the application.
2744     *
2745     * <p>This has the same visual effect as
2746     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2747     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2748     * meaning that non-critical screen decorations (such as the status bar) will be
2749     * hidden while the user is in the View's window, focusing the experience on
2750     * that content.  Unlike the window flag, if you are using ActionBar in
2751     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2752     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2753     * hide the action bar.
2754     *
2755     * <p>This approach to going fullscreen is best used over the window flag when
2756     * it is a transient state -- that is, the application does this at certain
2757     * points in its user interaction where it wants to allow the user to focus
2758     * on content, but not as a continuous state.  For situations where the application
2759     * would like to simply stay full screen the entire time (such as a game that
2760     * wants to take over the screen), the
2761     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2762     * is usually a better approach.  The state set here will be removed by the system
2763     * in various situations (such as the user moving to another application) like
2764     * the other system UI states.
2765     *
2766     * <p>When using this flag, the application should provide some easy facility
2767     * for the user to go out of it.  A common example would be in an e-book
2768     * reader, where tapping on the screen brings back whatever screen and UI
2769     * decorations that had been hidden while the user was immersed in reading
2770     * the book.
2771     *
2772     * @see #setSystemUiVisibility(int)
2773     */
2774    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2775
2776    /**
2777     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2778     * flags, we would like a stable view of the content insets given to
2779     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2780     * will always represent the worst case that the application can expect
2781     * as a continuous state.  In the stock Android UI this is the space for
2782     * the system bar, nav bar, and status bar, but not more transient elements
2783     * such as an input method.
2784     *
2785     * The stable layout your UI sees is based on the system UI modes you can
2786     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2787     * then you will get a stable layout for changes of the
2788     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2789     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2790     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2791     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2792     * with a stable layout.  (Note that you should avoid using
2793     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2794     *
2795     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2796     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2797     * then a hidden status bar will be considered a "stable" state for purposes
2798     * here.  This allows your UI to continually hide the status bar, while still
2799     * using the system UI flags to hide the action bar while still retaining
2800     * a stable layout.  Note that changing the window fullscreen flag will never
2801     * provide a stable layout for a clean transition.
2802     *
2803     * <p>If you are using ActionBar in
2804     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2805     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2806     * insets it adds to those given to the application.
2807     */
2808    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2809
2810    /**
2811     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2812     * to be laid out as if it has requested
2813     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2814     * allows it to avoid artifacts when switching in and out of that mode, at
2815     * the expense that some of its user interface may be covered by screen
2816     * decorations when they are shown.  You can perform layout of your inner
2817     * UI elements to account for the navigation system UI through the
2818     * {@link #fitSystemWindows(Rect)} method.
2819     */
2820    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2821
2822    /**
2823     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2824     * to be laid out as if it has requested
2825     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2826     * allows it to avoid artifacts when switching in and out of that mode, at
2827     * the expense that some of its user interface may be covered by screen
2828     * decorations when they are shown.  You can perform layout of your inner
2829     * UI elements to account for non-fullscreen system UI through the
2830     * {@link #fitSystemWindows(Rect)} method.
2831     */
2832    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2833
2834    /**
2835     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2836     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2837     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2838     * user interaction.
2839     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2840     * has an effect when used in combination with that flag.</p>
2841     */
2842    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2843
2844    /**
2845     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2846     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2847     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2848     * experience while also hiding the system bars.  If this flag is not set,
2849     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2850     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2851     * if the user swipes from the top of the screen.
2852     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2853     * system gestures, such as swiping from the top of the screen.  These transient system bars
2854     * will overlay app’s content, may have some degree of transparency, and will automatically
2855     * hide after a short timeout.
2856     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2857     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2858     * with one or both of those flags.</p>
2859     */
2860    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2861
2862    /**
2863     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2864     * is compatible with light status bar backgrounds.
2865     *
2866     * <p>For this to take effect, the window must request
2867     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2868     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2869     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2870     *         FLAG_TRANSLUCENT_STATUS}.
2871     *
2872     * @see android.R.attr#windowLightStatusBar
2873     */
2874    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2875
2876    /**
2877     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2878     */
2879    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2880
2881    /**
2882     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2883     */
2884    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2885
2886    /**
2887     * @hide
2888     *
2889     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2890     * out of the public fields to keep the undefined bits out of the developer's way.
2891     *
2892     * Flag to make the status bar not expandable.  Unless you also
2893     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2894     */
2895    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2896
2897    /**
2898     * @hide
2899     *
2900     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2901     * out of the public fields to keep the undefined bits out of the developer's way.
2902     *
2903     * Flag to hide notification icons and scrolling ticker text.
2904     */
2905    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2906
2907    /**
2908     * @hide
2909     *
2910     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2911     * out of the public fields to keep the undefined bits out of the developer's way.
2912     *
2913     * Flag to disable incoming notification alerts.  This will not block
2914     * icons, but it will block sound, vibrating and other visual or aural notifications.
2915     */
2916    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2917
2918    /**
2919     * @hide
2920     *
2921     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2922     * out of the public fields to keep the undefined bits out of the developer's way.
2923     *
2924     * Flag to hide only the scrolling ticker.  Note that
2925     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2926     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2927     */
2928    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2929
2930    /**
2931     * @hide
2932     *
2933     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2934     * out of the public fields to keep the undefined bits out of the developer's way.
2935     *
2936     * Flag to hide the center system info area.
2937     */
2938    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2939
2940    /**
2941     * @hide
2942     *
2943     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2944     * out of the public fields to keep the undefined bits out of the developer's way.
2945     *
2946     * Flag to hide only the home button.  Don't use this
2947     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2948     */
2949    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2950
2951    /**
2952     * @hide
2953     *
2954     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2955     * out of the public fields to keep the undefined bits out of the developer's way.
2956     *
2957     * Flag to hide only the back button. Don't use this
2958     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2959     */
2960    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2961
2962    /**
2963     * @hide
2964     *
2965     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2966     * out of the public fields to keep the undefined bits out of the developer's way.
2967     *
2968     * Flag to hide only the clock.  You might use this if your activity has
2969     * its own clock making the status bar's clock redundant.
2970     */
2971    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2972
2973    /**
2974     * @hide
2975     *
2976     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2977     * out of the public fields to keep the undefined bits out of the developer's way.
2978     *
2979     * Flag to hide only the recent apps button. Don't use this
2980     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2981     */
2982    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2983
2984    /**
2985     * @hide
2986     *
2987     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2988     * out of the public fields to keep the undefined bits out of the developer's way.
2989     *
2990     * Flag to disable the global search gesture. Don't use this
2991     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2992     */
2993    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2994
2995    /**
2996     * @hide
2997     *
2998     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2999     * out of the public fields to keep the undefined bits out of the developer's way.
3000     *
3001     * Flag to specify that the status bar is displayed in transient mode.
3002     */
3003    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3004
3005    /**
3006     * @hide
3007     *
3008     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3009     * out of the public fields to keep the undefined bits out of the developer's way.
3010     *
3011     * Flag to specify that the navigation bar is displayed in transient mode.
3012     */
3013    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3014
3015    /**
3016     * @hide
3017     *
3018     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3019     * out of the public fields to keep the undefined bits out of the developer's way.
3020     *
3021     * Flag to specify that the hidden status bar would like to be shown.
3022     */
3023    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3024
3025    /**
3026     * @hide
3027     *
3028     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3029     * out of the public fields to keep the undefined bits out of the developer's way.
3030     *
3031     * Flag to specify that the hidden navigation bar would like to be shown.
3032     */
3033    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3034
3035    /**
3036     * @hide
3037     *
3038     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3039     * out of the public fields to keep the undefined bits out of the developer's way.
3040     *
3041     * Flag to specify that the status bar is displayed in translucent mode.
3042     */
3043    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3044
3045    /**
3046     * @hide
3047     *
3048     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3049     * out of the public fields to keep the undefined bits out of the developer's way.
3050     *
3051     * Flag to specify that the navigation bar is displayed in translucent mode.
3052     */
3053    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3054
3055    /**
3056     * @hide
3057     *
3058     * Whether Recents is visible or not.
3059     */
3060    public static final int RECENT_APPS_VISIBLE = 0x00004000;
3061
3062    /**
3063     * @hide
3064     *
3065     * Makes navigation bar transparent (but not the status bar).
3066     */
3067    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3068
3069    /**
3070     * @hide
3071     *
3072     * Makes status bar transparent (but not the navigation bar).
3073     */
3074    public static final int STATUS_BAR_TRANSPARENT = 0x0000008;
3075
3076    /**
3077     * @hide
3078     *
3079     * Makes both status bar and navigation bar transparent.
3080     */
3081    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3082            | STATUS_BAR_TRANSPARENT;
3083
3084    /**
3085     * @hide
3086     */
3087    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3088
3089    /**
3090     * These are the system UI flags that can be cleared by events outside
3091     * of an application.  Currently this is just the ability to tap on the
3092     * screen while hiding the navigation bar to have it return.
3093     * @hide
3094     */
3095    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3096            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3097            | SYSTEM_UI_FLAG_FULLSCREEN;
3098
3099    /**
3100     * Flags that can impact the layout in relation to system UI.
3101     */
3102    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3103            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3104            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3105
3106    /** @hide */
3107    @IntDef(flag = true,
3108            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3109    @Retention(RetentionPolicy.SOURCE)
3110    public @interface FindViewFlags {}
3111
3112    /**
3113     * Find views that render the specified text.
3114     *
3115     * @see #findViewsWithText(ArrayList, CharSequence, int)
3116     */
3117    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3118
3119    /**
3120     * Find find views that contain the specified content description.
3121     *
3122     * @see #findViewsWithText(ArrayList, CharSequence, int)
3123     */
3124    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3125
3126    /**
3127     * Find views that contain {@link AccessibilityNodeProvider}. Such
3128     * a View is a root of virtual view hierarchy and may contain the searched
3129     * text. If this flag is set Views with providers are automatically
3130     * added and it is a responsibility of the client to call the APIs of
3131     * the provider to determine whether the virtual tree rooted at this View
3132     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3133     * representing the virtual views with this text.
3134     *
3135     * @see #findViewsWithText(ArrayList, CharSequence, int)
3136     *
3137     * @hide
3138     */
3139    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3140
3141    /**
3142     * The undefined cursor position.
3143     *
3144     * @hide
3145     */
3146    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3147
3148    /**
3149     * Indicates that the screen has changed state and is now off.
3150     *
3151     * @see #onScreenStateChanged(int)
3152     */
3153    public static final int SCREEN_STATE_OFF = 0x0;
3154
3155    /**
3156     * Indicates that the screen has changed state and is now on.
3157     *
3158     * @see #onScreenStateChanged(int)
3159     */
3160    public static final int SCREEN_STATE_ON = 0x1;
3161
3162    /**
3163     * Indicates no axis of view scrolling.
3164     */
3165    public static final int SCROLL_AXIS_NONE = 0;
3166
3167    /**
3168     * Indicates scrolling along the horizontal axis.
3169     */
3170    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3171
3172    /**
3173     * Indicates scrolling along the vertical axis.
3174     */
3175    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3176
3177    /**
3178     * Controls the over-scroll mode for this view.
3179     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3180     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3181     * and {@link #OVER_SCROLL_NEVER}.
3182     */
3183    private int mOverScrollMode;
3184
3185    /**
3186     * The parent this view is attached to.
3187     * {@hide}
3188     *
3189     * @see #getParent()
3190     */
3191    protected ViewParent mParent;
3192
3193    /**
3194     * {@hide}
3195     */
3196    AttachInfo mAttachInfo;
3197
3198    /**
3199     * {@hide}
3200     */
3201    @ViewDebug.ExportedProperty(flagMapping = {
3202        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3203                name = "FORCE_LAYOUT"),
3204        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3205                name = "LAYOUT_REQUIRED"),
3206        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3207            name = "DRAWING_CACHE_INVALID", outputIf = false),
3208        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3209        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3210        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3211        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3212    }, formatToHexString = true)
3213    int mPrivateFlags;
3214    int mPrivateFlags2;
3215    int mPrivateFlags3;
3216
3217    /**
3218     * This view's request for the visibility of the status bar.
3219     * @hide
3220     */
3221    @ViewDebug.ExportedProperty(flagMapping = {
3222        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3223                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3224                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3225        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3226                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3227                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3228        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3229                                equals = SYSTEM_UI_FLAG_VISIBLE,
3230                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3231    }, formatToHexString = true)
3232    int mSystemUiVisibility;
3233
3234    /**
3235     * Reference count for transient state.
3236     * @see #setHasTransientState(boolean)
3237     */
3238    int mTransientStateCount = 0;
3239
3240    /**
3241     * Count of how many windows this view has been attached to.
3242     */
3243    int mWindowAttachCount;
3244
3245    /**
3246     * The layout parameters associated with this view and used by the parent
3247     * {@link android.view.ViewGroup} to determine how this view should be
3248     * laid out.
3249     * {@hide}
3250     */
3251    protected ViewGroup.LayoutParams mLayoutParams;
3252
3253    /**
3254     * The view flags hold various views states.
3255     * {@hide}
3256     */
3257    @ViewDebug.ExportedProperty(formatToHexString = true)
3258    int mViewFlags;
3259
3260    static class TransformationInfo {
3261        /**
3262         * The transform matrix for the View. This transform is calculated internally
3263         * based on the translation, rotation, and scale properties.
3264         *
3265         * Do *not* use this variable directly; instead call getMatrix(), which will
3266         * load the value from the View's RenderNode.
3267         */
3268        private final Matrix mMatrix = new Matrix();
3269
3270        /**
3271         * The inverse transform matrix for the View. This transform is calculated
3272         * internally based on the translation, rotation, and scale properties.
3273         *
3274         * Do *not* use this variable directly; instead call getInverseMatrix(),
3275         * which will load the value from the View's RenderNode.
3276         */
3277        private Matrix mInverseMatrix;
3278
3279        /**
3280         * The opacity of the View. This is a value from 0 to 1, where 0 means
3281         * completely transparent and 1 means completely opaque.
3282         */
3283        @ViewDebug.ExportedProperty
3284        float mAlpha = 1f;
3285
3286        /**
3287         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3288         * property only used by transitions, which is composited with the other alpha
3289         * values to calculate the final visual alpha value.
3290         */
3291        float mTransitionAlpha = 1f;
3292    }
3293
3294    TransformationInfo mTransformationInfo;
3295
3296    /**
3297     * Current clip bounds. to which all drawing of this view are constrained.
3298     */
3299    Rect mClipBounds = null;
3300
3301    private boolean mLastIsOpaque;
3302
3303    /**
3304     * The distance in pixels from the left edge of this view's parent
3305     * to the left edge of this view.
3306     * {@hide}
3307     */
3308    @ViewDebug.ExportedProperty(category = "layout")
3309    protected int mLeft;
3310    /**
3311     * The distance in pixels from the left edge of this view's parent
3312     * to the right edge of this view.
3313     * {@hide}
3314     */
3315    @ViewDebug.ExportedProperty(category = "layout")
3316    protected int mRight;
3317    /**
3318     * The distance in pixels from the top edge of this view's parent
3319     * to the top edge of this view.
3320     * {@hide}
3321     */
3322    @ViewDebug.ExportedProperty(category = "layout")
3323    protected int mTop;
3324    /**
3325     * The distance in pixels from the top edge of this view's parent
3326     * to the bottom edge of this view.
3327     * {@hide}
3328     */
3329    @ViewDebug.ExportedProperty(category = "layout")
3330    protected int mBottom;
3331
3332    /**
3333     * The offset, in pixels, by which the content of this view is scrolled
3334     * horizontally.
3335     * {@hide}
3336     */
3337    @ViewDebug.ExportedProperty(category = "scrolling")
3338    protected int mScrollX;
3339    /**
3340     * The offset, in pixels, by which the content of this view is scrolled
3341     * vertically.
3342     * {@hide}
3343     */
3344    @ViewDebug.ExportedProperty(category = "scrolling")
3345    protected int mScrollY;
3346
3347    /**
3348     * The left padding in pixels, that is the distance in pixels between the
3349     * left edge of this view and the left edge of its content.
3350     * {@hide}
3351     */
3352    @ViewDebug.ExportedProperty(category = "padding")
3353    protected int mPaddingLeft = 0;
3354    /**
3355     * The right padding in pixels, that is the distance in pixels between the
3356     * right edge of this view and the right edge of its content.
3357     * {@hide}
3358     */
3359    @ViewDebug.ExportedProperty(category = "padding")
3360    protected int mPaddingRight = 0;
3361    /**
3362     * The top padding in pixels, that is the distance in pixels between the
3363     * top edge of this view and the top edge of its content.
3364     * {@hide}
3365     */
3366    @ViewDebug.ExportedProperty(category = "padding")
3367    protected int mPaddingTop;
3368    /**
3369     * The bottom padding in pixels, that is the distance in pixels between the
3370     * bottom edge of this view and the bottom edge of its content.
3371     * {@hide}
3372     */
3373    @ViewDebug.ExportedProperty(category = "padding")
3374    protected int mPaddingBottom;
3375
3376    /**
3377     * The layout insets in pixels, that is the distance in pixels between the
3378     * visible edges of this view its bounds.
3379     */
3380    private Insets mLayoutInsets;
3381
3382    /**
3383     * Briefly describes the view and is primarily used for accessibility support.
3384     */
3385    private CharSequence mContentDescription;
3386
3387    /**
3388     * Specifies the id of a view for which this view serves as a label for
3389     * accessibility purposes.
3390     */
3391    private int mLabelForId = View.NO_ID;
3392
3393    /**
3394     * Predicate for matching labeled view id with its label for
3395     * accessibility purposes.
3396     */
3397    private MatchLabelForPredicate mMatchLabelForPredicate;
3398
3399    /**
3400     * Specifies a view before which this one is visited in accessibility traversal.
3401     */
3402    private int mAccessibilityTraversalBeforeId = NO_ID;
3403
3404    /**
3405     * Specifies a view after which this one is visited in accessibility traversal.
3406     */
3407    private int mAccessibilityTraversalAfterId = NO_ID;
3408
3409    /**
3410     * Predicate for matching a view by its id.
3411     */
3412    private MatchIdPredicate mMatchIdPredicate;
3413
3414    /**
3415     * Cache the paddingRight set by the user to append to the scrollbar's size.
3416     *
3417     * @hide
3418     */
3419    @ViewDebug.ExportedProperty(category = "padding")
3420    protected int mUserPaddingRight;
3421
3422    /**
3423     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3424     *
3425     * @hide
3426     */
3427    @ViewDebug.ExportedProperty(category = "padding")
3428    protected int mUserPaddingBottom;
3429
3430    /**
3431     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3432     *
3433     * @hide
3434     */
3435    @ViewDebug.ExportedProperty(category = "padding")
3436    protected int mUserPaddingLeft;
3437
3438    /**
3439     * Cache the paddingStart set by the user to append to the scrollbar's size.
3440     *
3441     */
3442    @ViewDebug.ExportedProperty(category = "padding")
3443    int mUserPaddingStart;
3444
3445    /**
3446     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3447     *
3448     */
3449    @ViewDebug.ExportedProperty(category = "padding")
3450    int mUserPaddingEnd;
3451
3452    /**
3453     * Cache initial left padding.
3454     *
3455     * @hide
3456     */
3457    int mUserPaddingLeftInitial;
3458
3459    /**
3460     * Cache initial right padding.
3461     *
3462     * @hide
3463     */
3464    int mUserPaddingRightInitial;
3465
3466    /**
3467     * Default undefined padding
3468     */
3469    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3470
3471    /**
3472     * Cache if a left padding has been defined
3473     */
3474    private boolean mLeftPaddingDefined = false;
3475
3476    /**
3477     * Cache if a right padding has been defined
3478     */
3479    private boolean mRightPaddingDefined = false;
3480
3481    /**
3482     * @hide
3483     */
3484    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3485    /**
3486     * @hide
3487     */
3488    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3489
3490    private LongSparseLongArray mMeasureCache;
3491
3492    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3493    private Drawable mBackground;
3494    private TintInfo mBackgroundTint;
3495
3496    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3497    private ForegroundInfo mForegroundInfo;
3498
3499    private Drawable mScrollIndicatorDrawable;
3500
3501    /**
3502     * RenderNode used for backgrounds.
3503     * <p>
3504     * When non-null and valid, this is expected to contain an up-to-date copy
3505     * of the background drawable. It is cleared on temporary detach, and reset
3506     * on cleanup.
3507     */
3508    private RenderNode mBackgroundRenderNode;
3509
3510    private int mBackgroundResource;
3511    private boolean mBackgroundSizeChanged;
3512
3513    private String mTransitionName;
3514
3515    static class TintInfo {
3516        ColorStateList mTintList;
3517        PorterDuff.Mode mTintMode;
3518        boolean mHasTintMode;
3519        boolean mHasTintList;
3520    }
3521
3522    private static class ForegroundInfo {
3523        private Drawable mDrawable;
3524        private TintInfo mTintInfo;
3525        private int mGravity = Gravity.FILL;
3526        private boolean mInsidePadding = true;
3527        private boolean mBoundsChanged = true;
3528        private final Rect mSelfBounds = new Rect();
3529        private final Rect mOverlayBounds = new Rect();
3530    }
3531
3532    static class ListenerInfo {
3533        /**
3534         * Listener used to dispatch focus change events.
3535         * This field should be made private, so it is hidden from the SDK.
3536         * {@hide}
3537         */
3538        protected OnFocusChangeListener mOnFocusChangeListener;
3539
3540        /**
3541         * Listeners for layout change events.
3542         */
3543        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3544
3545        protected OnScrollChangeListener mOnScrollChangeListener;
3546
3547        /**
3548         * Listeners for attach events.
3549         */
3550        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3551
3552        /**
3553         * Listener used to dispatch click events.
3554         * This field should be made private, so it is hidden from the SDK.
3555         * {@hide}
3556         */
3557        public OnClickListener mOnClickListener;
3558
3559        /**
3560         * Listener used to dispatch long click events.
3561         * This field should be made private, so it is hidden from the SDK.
3562         * {@hide}
3563         */
3564        protected OnLongClickListener mOnLongClickListener;
3565
3566        /**
3567         * Listener used to dispatch context click events. This field should be made private, so it
3568         * is hidden from the SDK.
3569         * {@hide}
3570         */
3571        protected OnContextClickListener mOnContextClickListener;
3572
3573        /**
3574         * Listener used to build the context menu.
3575         * This field should be made private, so it is hidden from the SDK.
3576         * {@hide}
3577         */
3578        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3579
3580        private OnKeyListener mOnKeyListener;
3581
3582        private OnTouchListener mOnTouchListener;
3583
3584        private OnHoverListener mOnHoverListener;
3585
3586        private OnGenericMotionListener mOnGenericMotionListener;
3587
3588        private OnDragListener mOnDragListener;
3589
3590        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3591
3592        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3593    }
3594
3595    ListenerInfo mListenerInfo;
3596
3597    // Temporary values used to hold (x,y) coordinates when delegating from the
3598    // two-arg performLongClick() method to the legacy no-arg version.
3599    private float mLongClickX = Float.NaN;
3600    private float mLongClickY = Float.NaN;
3601
3602    /**
3603     * The application environment this view lives in.
3604     * This field should be made private, so it is hidden from the SDK.
3605     * {@hide}
3606     */
3607    @ViewDebug.ExportedProperty(deepExport = true)
3608    protected Context mContext;
3609
3610    private final Resources mResources;
3611
3612    private ScrollabilityCache mScrollCache;
3613
3614    private int[] mDrawableState = null;
3615
3616    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3617
3618    /**
3619     * Animator that automatically runs based on state changes.
3620     */
3621    private StateListAnimator mStateListAnimator;
3622
3623    /**
3624     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3625     * the user may specify which view to go to next.
3626     */
3627    private int mNextFocusLeftId = View.NO_ID;
3628
3629    /**
3630     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3631     * the user may specify which view to go to next.
3632     */
3633    private int mNextFocusRightId = View.NO_ID;
3634
3635    /**
3636     * When this view has focus and the next focus is {@link #FOCUS_UP},
3637     * the user may specify which view to go to next.
3638     */
3639    private int mNextFocusUpId = View.NO_ID;
3640
3641    /**
3642     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3643     * the user may specify which view to go to next.
3644     */
3645    private int mNextFocusDownId = View.NO_ID;
3646
3647    /**
3648     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3649     * the user may specify which view to go to next.
3650     */
3651    int mNextFocusForwardId = View.NO_ID;
3652
3653    private CheckForLongPress mPendingCheckForLongPress;
3654    private CheckForTap mPendingCheckForTap = null;
3655    private PerformClick mPerformClick;
3656    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3657
3658    private UnsetPressedState mUnsetPressedState;
3659
3660    /**
3661     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3662     * up event while a long press is invoked as soon as the long press duration is reached, so
3663     * a long press could be performed before the tap is checked, in which case the tap's action
3664     * should not be invoked.
3665     */
3666    private boolean mHasPerformedLongPress;
3667
3668    /**
3669     * Whether a context click button is currently pressed down. This is true when the stylus is
3670     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3671     * pressed. This is false once the button is released or if the stylus has been lifted.
3672     */
3673    private boolean mInContextButtonPress;
3674
3675    /**
3676     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3677     * true after a stylus button press has occured, when the next up event should not be recognized
3678     * as a tap.
3679     */
3680    private boolean mIgnoreNextUpEvent;
3681
3682    /**
3683     * The minimum height of the view. We'll try our best to have the height
3684     * of this view to at least this amount.
3685     */
3686    @ViewDebug.ExportedProperty(category = "measurement")
3687    private int mMinHeight;
3688
3689    /**
3690     * The minimum width of the view. We'll try our best to have the width
3691     * of this view to at least this amount.
3692     */
3693    @ViewDebug.ExportedProperty(category = "measurement")
3694    private int mMinWidth;
3695
3696    /**
3697     * The delegate to handle touch events that are physically in this view
3698     * but should be handled by another view.
3699     */
3700    private TouchDelegate mTouchDelegate = null;
3701
3702    /**
3703     * Solid color to use as a background when creating the drawing cache. Enables
3704     * the cache to use 16 bit bitmaps instead of 32 bit.
3705     */
3706    private int mDrawingCacheBackgroundColor = 0;
3707
3708    /**
3709     * Special tree observer used when mAttachInfo is null.
3710     */
3711    private ViewTreeObserver mFloatingTreeObserver;
3712
3713    /**
3714     * Cache the touch slop from the context that created the view.
3715     */
3716    private int mTouchSlop;
3717
3718    /**
3719     * Object that handles automatic animation of view properties.
3720     */
3721    private ViewPropertyAnimator mAnimator = null;
3722
3723    /**
3724     * List of registered FrameMetricsObservers.
3725     */
3726    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3727
3728    /**
3729     * Flag indicating that a drag can cross window boundaries.  When
3730     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3731     * with this flag set, all visible applications will be able to participate
3732     * in the drag operation and receive the dragged content.
3733     *
3734     * If this is the only flag set, then the drag recipient will only have access to text data
3735     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3736     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags.
3737     */
3738    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3739
3740    /**
3741     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3742     * request read access to the content URI(s) contained in the {@link ClipData} object.
3743     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3744     */
3745    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3746
3747    /**
3748     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3749     * request write access to the content URI(s) contained in the {@link ClipData} object.
3750     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3751     */
3752    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3753
3754    /**
3755     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3756     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3757     * reboots until explicitly revoked with
3758     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3759     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3760     */
3761    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3762            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3763
3764    /**
3765     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3766     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3767     * match against the original granted URI.
3768     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3769     */
3770    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3771            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3772
3773    /**
3774     * Flag indicating that the drag shadow will be opaque.  When
3775     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3776     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3777     */
3778    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3779
3780    /**
3781     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3782     */
3783    private float mVerticalScrollFactor;
3784
3785    /**
3786     * Position of the vertical scroll bar.
3787     */
3788    private int mVerticalScrollbarPosition;
3789
3790    /**
3791     * Position the scroll bar at the default position as determined by the system.
3792     */
3793    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3794
3795    /**
3796     * Position the scroll bar along the left edge.
3797     */
3798    public static final int SCROLLBAR_POSITION_LEFT = 1;
3799
3800    /**
3801     * Position the scroll bar along the right edge.
3802     */
3803    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3804
3805    /**
3806     * Indicates that the view does not have a layer.
3807     *
3808     * @see #getLayerType()
3809     * @see #setLayerType(int, android.graphics.Paint)
3810     * @see #LAYER_TYPE_SOFTWARE
3811     * @see #LAYER_TYPE_HARDWARE
3812     */
3813    public static final int LAYER_TYPE_NONE = 0;
3814
3815    /**
3816     * <p>Indicates that the view has a software layer. A software layer is backed
3817     * by a bitmap and causes the view to be rendered using Android's software
3818     * rendering pipeline, even if hardware acceleration is enabled.</p>
3819     *
3820     * <p>Software layers have various usages:</p>
3821     * <p>When the application is not using hardware acceleration, a software layer
3822     * is useful to apply a specific color filter and/or blending mode and/or
3823     * translucency to a view and all its children.</p>
3824     * <p>When the application is using hardware acceleration, a software layer
3825     * is useful to render drawing primitives not supported by the hardware
3826     * accelerated pipeline. It can also be used to cache a complex view tree
3827     * into a texture and reduce the complexity of drawing operations. For instance,
3828     * when animating a complex view tree with a translation, a software layer can
3829     * be used to render the view tree only once.</p>
3830     * <p>Software layers should be avoided when the affected view tree updates
3831     * often. Every update will require to re-render the software layer, which can
3832     * potentially be slow (particularly when hardware acceleration is turned on
3833     * since the layer will have to be uploaded into a hardware texture after every
3834     * update.)</p>
3835     *
3836     * @see #getLayerType()
3837     * @see #setLayerType(int, android.graphics.Paint)
3838     * @see #LAYER_TYPE_NONE
3839     * @see #LAYER_TYPE_HARDWARE
3840     */
3841    public static final int LAYER_TYPE_SOFTWARE = 1;
3842
3843    /**
3844     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3845     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3846     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3847     * rendering pipeline, but only if hardware acceleration is turned on for the
3848     * view hierarchy. When hardware acceleration is turned off, hardware layers
3849     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3850     *
3851     * <p>A hardware layer is useful to apply a specific color filter and/or
3852     * blending mode and/or translucency to a view and all its children.</p>
3853     * <p>A hardware layer can be used to cache a complex view tree into a
3854     * texture and reduce the complexity of drawing operations. For instance,
3855     * when animating a complex view tree with a translation, a hardware layer can
3856     * be used to render the view tree only once.</p>
3857     * <p>A hardware layer can also be used to increase the rendering quality when
3858     * rotation transformations are applied on a view. It can also be used to
3859     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3860     *
3861     * @see #getLayerType()
3862     * @see #setLayerType(int, android.graphics.Paint)
3863     * @see #LAYER_TYPE_NONE
3864     * @see #LAYER_TYPE_SOFTWARE
3865     */
3866    public static final int LAYER_TYPE_HARDWARE = 2;
3867
3868    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3869            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3870            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3871            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3872    })
3873    int mLayerType = LAYER_TYPE_NONE;
3874    Paint mLayerPaint;
3875
3876    /**
3877     * Set to true when drawing cache is enabled and cannot be created.
3878     *
3879     * @hide
3880     */
3881    public boolean mCachingFailed;
3882    private Bitmap mDrawingCache;
3883    private Bitmap mUnscaledDrawingCache;
3884
3885    /**
3886     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3887     * <p>
3888     * When non-null and valid, this is expected to contain an up-to-date copy
3889     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3890     * cleanup.
3891     */
3892    final RenderNode mRenderNode;
3893
3894    /**
3895     * Set to true when the view is sending hover accessibility events because it
3896     * is the innermost hovered view.
3897     */
3898    private boolean mSendingHoverAccessibilityEvents;
3899
3900    /**
3901     * Delegate for injecting accessibility functionality.
3902     */
3903    AccessibilityDelegate mAccessibilityDelegate;
3904
3905    /**
3906     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3907     * and add/remove objects to/from the overlay directly through the Overlay methods.
3908     */
3909    ViewOverlay mOverlay;
3910
3911    /**
3912     * The currently active parent view for receiving delegated nested scrolling events.
3913     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3914     * by {@link #stopNestedScroll()} at the same point where we clear
3915     * requestDisallowInterceptTouchEvent.
3916     */
3917    private ViewParent mNestedScrollingParent;
3918
3919    /**
3920     * Consistency verifier for debugging purposes.
3921     * @hide
3922     */
3923    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3924            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3925                    new InputEventConsistencyVerifier(this, 0) : null;
3926
3927    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3928
3929    private int[] mTempNestedScrollConsumed;
3930
3931    /**
3932     * An overlay is going to draw this View instead of being drawn as part of this
3933     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3934     * when this view is invalidated.
3935     */
3936    GhostView mGhostView;
3937
3938    /**
3939     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3940     * @hide
3941     */
3942    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3943    public String[] mAttributes;
3944
3945    /**
3946     * Maps a Resource id to its name.
3947     */
3948    private static SparseArray<String> mAttributeMap;
3949
3950    /**
3951     * Queue of pending runnables. Used to postpone calls to post() until this
3952     * view is attached and has a handler.
3953     */
3954    private HandlerActionQueue mRunQueue;
3955
3956    /**
3957     * The pointer icon when the mouse hovers on this view. The default is null.
3958     */
3959    private PointerIcon mPointerIcon;
3960
3961    /**
3962     * @hide
3963     */
3964    String mStartActivityRequestWho;
3965
3966    /**
3967     * Simple constructor to use when creating a view from code.
3968     *
3969     * @param context The Context the view is running in, through which it can
3970     *        access the current theme, resources, etc.
3971     */
3972    public View(Context context) {
3973        mContext = context;
3974        mResources = context != null ? context.getResources() : null;
3975        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3976        // Set some flags defaults
3977        mPrivateFlags2 =
3978                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3979                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3980                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3981                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3982                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3983                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3984        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3985        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3986        mUserPaddingStart = UNDEFINED_PADDING;
3987        mUserPaddingEnd = UNDEFINED_PADDING;
3988        mRenderNode = RenderNode.create(getClass().getName(), this);
3989
3990        if (!sCompatibilityDone && context != null) {
3991            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3992
3993            // Older apps may need this compatibility hack for measurement.
3994            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3995
3996            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3997            // of whether a layout was requested on that View.
3998            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3999
4000            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4001
4002            // In M and newer, our widgets can pass a "hint" value in the size
4003            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4004            // know what the expected parent size is going to be, so e.g. list items can size
4005            // themselves at 1/3 the size of their container. It breaks older apps though,
4006            // specifically apps that use some popular open source libraries.
4007            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4008
4009            // Old versions of the platform would give different results from
4010            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4011            // modes, so we always need to run an additional EXACTLY pass.
4012            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4013
4014            // Prior to N, layout params could change without requiring a
4015            // subsequent call to setLayoutParams() and they would usually
4016            // work. Partial layout breaks this assumption.
4017            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4018
4019            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4020            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4021            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4022
4023            sCompatibilityDone = true;
4024        }
4025    }
4026
4027    /**
4028     * Constructor that is called when inflating a view from XML. This is called
4029     * when a view is being constructed from an XML file, supplying attributes
4030     * that were specified in the XML file. This version uses a default style of
4031     * 0, so the only attribute values applied are those in the Context's Theme
4032     * and the given AttributeSet.
4033     *
4034     * <p>
4035     * The method onFinishInflate() will be called after all children have been
4036     * added.
4037     *
4038     * @param context The Context the view is running in, through which it can
4039     *        access the current theme, resources, etc.
4040     * @param attrs The attributes of the XML tag that is inflating the view.
4041     * @see #View(Context, AttributeSet, int)
4042     */
4043    public View(Context context, @Nullable AttributeSet attrs) {
4044        this(context, attrs, 0);
4045    }
4046
4047    /**
4048     * Perform inflation from XML and apply a class-specific base style from a
4049     * theme attribute. This constructor of View allows subclasses to use their
4050     * own base style when they are inflating. For example, a Button class's
4051     * constructor would call this version of the super class constructor and
4052     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4053     * allows the theme's button style to modify all of the base view attributes
4054     * (in particular its background) as well as the Button class's attributes.
4055     *
4056     * @param context The Context the view is running in, through which it can
4057     *        access the current theme, resources, etc.
4058     * @param attrs The attributes of the XML tag that is inflating the view.
4059     * @param defStyleAttr An attribute in the current theme that contains a
4060     *        reference to a style resource that supplies default values for
4061     *        the view. Can be 0 to not look for defaults.
4062     * @see #View(Context, AttributeSet)
4063     */
4064    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4065        this(context, attrs, defStyleAttr, 0);
4066    }
4067
4068    /**
4069     * Perform inflation from XML and apply a class-specific base style from a
4070     * theme attribute or style resource. This constructor of View allows
4071     * subclasses to use their own base style when they are inflating.
4072     * <p>
4073     * When determining the final value of a particular attribute, there are
4074     * four inputs that come into play:
4075     * <ol>
4076     * <li>Any attribute values in the given AttributeSet.
4077     * <li>The style resource specified in the AttributeSet (named "style").
4078     * <li>The default style specified by <var>defStyleAttr</var>.
4079     * <li>The default style specified by <var>defStyleRes</var>.
4080     * <li>The base values in this theme.
4081     * </ol>
4082     * <p>
4083     * Each of these inputs is considered in-order, with the first listed taking
4084     * precedence over the following ones. In other words, if in the
4085     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4086     * , then the button's text will <em>always</em> be black, regardless of
4087     * what is specified in any of the styles.
4088     *
4089     * @param context The Context the view is running in, through which it can
4090     *        access the current theme, resources, etc.
4091     * @param attrs The attributes of the XML tag that is inflating the view.
4092     * @param defStyleAttr An attribute in the current theme that contains a
4093     *        reference to a style resource that supplies default values for
4094     *        the view. Can be 0 to not look for defaults.
4095     * @param defStyleRes A resource identifier of a style resource that
4096     *        supplies default values for the view, used only if
4097     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4098     *        to not look for defaults.
4099     * @see #View(Context, AttributeSet, int)
4100     */
4101    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4102        this(context);
4103
4104        final TypedArray a = context.obtainStyledAttributes(
4105                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4106
4107        if (mDebugViewAttributes) {
4108            saveAttributeData(attrs, a);
4109        }
4110
4111        Drawable background = null;
4112
4113        int leftPadding = -1;
4114        int topPadding = -1;
4115        int rightPadding = -1;
4116        int bottomPadding = -1;
4117        int startPadding = UNDEFINED_PADDING;
4118        int endPadding = UNDEFINED_PADDING;
4119
4120        int padding = -1;
4121
4122        int viewFlagValues = 0;
4123        int viewFlagMasks = 0;
4124
4125        boolean setScrollContainer = false;
4126
4127        int x = 0;
4128        int y = 0;
4129
4130        float tx = 0;
4131        float ty = 0;
4132        float tz = 0;
4133        float elevation = 0;
4134        float rotation = 0;
4135        float rotationX = 0;
4136        float rotationY = 0;
4137        float sx = 1f;
4138        float sy = 1f;
4139        boolean transformSet = false;
4140
4141        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4142        int overScrollMode = mOverScrollMode;
4143        boolean initializeScrollbars = false;
4144        boolean initializeScrollIndicators = false;
4145
4146        boolean startPaddingDefined = false;
4147        boolean endPaddingDefined = false;
4148        boolean leftPaddingDefined = false;
4149        boolean rightPaddingDefined = false;
4150
4151        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4152
4153        final int N = a.getIndexCount();
4154        for (int i = 0; i < N; i++) {
4155            int attr = a.getIndex(i);
4156            switch (attr) {
4157                case com.android.internal.R.styleable.View_background:
4158                    background = a.getDrawable(attr);
4159                    break;
4160                case com.android.internal.R.styleable.View_padding:
4161                    padding = a.getDimensionPixelSize(attr, -1);
4162                    mUserPaddingLeftInitial = padding;
4163                    mUserPaddingRightInitial = padding;
4164                    leftPaddingDefined = true;
4165                    rightPaddingDefined = true;
4166                    break;
4167                 case com.android.internal.R.styleable.View_paddingLeft:
4168                    leftPadding = a.getDimensionPixelSize(attr, -1);
4169                    mUserPaddingLeftInitial = leftPadding;
4170                    leftPaddingDefined = true;
4171                    break;
4172                case com.android.internal.R.styleable.View_paddingTop:
4173                    topPadding = a.getDimensionPixelSize(attr, -1);
4174                    break;
4175                case com.android.internal.R.styleable.View_paddingRight:
4176                    rightPadding = a.getDimensionPixelSize(attr, -1);
4177                    mUserPaddingRightInitial = rightPadding;
4178                    rightPaddingDefined = true;
4179                    break;
4180                case com.android.internal.R.styleable.View_paddingBottom:
4181                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4182                    break;
4183                case com.android.internal.R.styleable.View_paddingStart:
4184                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4185                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4186                    break;
4187                case com.android.internal.R.styleable.View_paddingEnd:
4188                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4189                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4190                    break;
4191                case com.android.internal.R.styleable.View_scrollX:
4192                    x = a.getDimensionPixelOffset(attr, 0);
4193                    break;
4194                case com.android.internal.R.styleable.View_scrollY:
4195                    y = a.getDimensionPixelOffset(attr, 0);
4196                    break;
4197                case com.android.internal.R.styleable.View_alpha:
4198                    setAlpha(a.getFloat(attr, 1f));
4199                    break;
4200                case com.android.internal.R.styleable.View_transformPivotX:
4201                    setPivotX(a.getDimensionPixelOffset(attr, 0));
4202                    break;
4203                case com.android.internal.R.styleable.View_transformPivotY:
4204                    setPivotY(a.getDimensionPixelOffset(attr, 0));
4205                    break;
4206                case com.android.internal.R.styleable.View_translationX:
4207                    tx = a.getDimensionPixelOffset(attr, 0);
4208                    transformSet = true;
4209                    break;
4210                case com.android.internal.R.styleable.View_translationY:
4211                    ty = a.getDimensionPixelOffset(attr, 0);
4212                    transformSet = true;
4213                    break;
4214                case com.android.internal.R.styleable.View_translationZ:
4215                    tz = a.getDimensionPixelOffset(attr, 0);
4216                    transformSet = true;
4217                    break;
4218                case com.android.internal.R.styleable.View_elevation:
4219                    elevation = a.getDimensionPixelOffset(attr, 0);
4220                    transformSet = true;
4221                    break;
4222                case com.android.internal.R.styleable.View_rotation:
4223                    rotation = a.getFloat(attr, 0);
4224                    transformSet = true;
4225                    break;
4226                case com.android.internal.R.styleable.View_rotationX:
4227                    rotationX = a.getFloat(attr, 0);
4228                    transformSet = true;
4229                    break;
4230                case com.android.internal.R.styleable.View_rotationY:
4231                    rotationY = a.getFloat(attr, 0);
4232                    transformSet = true;
4233                    break;
4234                case com.android.internal.R.styleable.View_scaleX:
4235                    sx = a.getFloat(attr, 1f);
4236                    transformSet = true;
4237                    break;
4238                case com.android.internal.R.styleable.View_scaleY:
4239                    sy = a.getFloat(attr, 1f);
4240                    transformSet = true;
4241                    break;
4242                case com.android.internal.R.styleable.View_id:
4243                    mID = a.getResourceId(attr, NO_ID);
4244                    break;
4245                case com.android.internal.R.styleable.View_tag:
4246                    mTag = a.getText(attr);
4247                    break;
4248                case com.android.internal.R.styleable.View_fitsSystemWindows:
4249                    if (a.getBoolean(attr, false)) {
4250                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4251                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4252                    }
4253                    break;
4254                case com.android.internal.R.styleable.View_focusable:
4255                    if (a.getBoolean(attr, false)) {
4256                        viewFlagValues |= FOCUSABLE;
4257                        viewFlagMasks |= FOCUSABLE_MASK;
4258                    }
4259                    break;
4260                case com.android.internal.R.styleable.View_focusableInTouchMode:
4261                    if (a.getBoolean(attr, false)) {
4262                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4263                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4264                    }
4265                    break;
4266                case com.android.internal.R.styleable.View_clickable:
4267                    if (a.getBoolean(attr, false)) {
4268                        viewFlagValues |= CLICKABLE;
4269                        viewFlagMasks |= CLICKABLE;
4270                    }
4271                    break;
4272                case com.android.internal.R.styleable.View_longClickable:
4273                    if (a.getBoolean(attr, false)) {
4274                        viewFlagValues |= LONG_CLICKABLE;
4275                        viewFlagMasks |= LONG_CLICKABLE;
4276                    }
4277                    break;
4278                case com.android.internal.R.styleable.View_contextClickable:
4279                    if (a.getBoolean(attr, false)) {
4280                        viewFlagValues |= CONTEXT_CLICKABLE;
4281                        viewFlagMasks |= CONTEXT_CLICKABLE;
4282                    }
4283                    break;
4284                case com.android.internal.R.styleable.View_saveEnabled:
4285                    if (!a.getBoolean(attr, true)) {
4286                        viewFlagValues |= SAVE_DISABLED;
4287                        viewFlagMasks |= SAVE_DISABLED_MASK;
4288                    }
4289                    break;
4290                case com.android.internal.R.styleable.View_duplicateParentState:
4291                    if (a.getBoolean(attr, false)) {
4292                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4293                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4294                    }
4295                    break;
4296                case com.android.internal.R.styleable.View_visibility:
4297                    final int visibility = a.getInt(attr, 0);
4298                    if (visibility != 0) {
4299                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4300                        viewFlagMasks |= VISIBILITY_MASK;
4301                    }
4302                    break;
4303                case com.android.internal.R.styleable.View_layoutDirection:
4304                    // Clear any layout direction flags (included resolved bits) already set
4305                    mPrivateFlags2 &=
4306                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4307                    // Set the layout direction flags depending on the value of the attribute
4308                    final int layoutDirection = a.getInt(attr, -1);
4309                    final int value = (layoutDirection != -1) ?
4310                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4311                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4312                    break;
4313                case com.android.internal.R.styleable.View_drawingCacheQuality:
4314                    final int cacheQuality = a.getInt(attr, 0);
4315                    if (cacheQuality != 0) {
4316                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4317                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4318                    }
4319                    break;
4320                case com.android.internal.R.styleable.View_contentDescription:
4321                    setContentDescription(a.getString(attr));
4322                    break;
4323                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4324                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4325                    break;
4326                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4327                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4328                    break;
4329                case com.android.internal.R.styleable.View_labelFor:
4330                    setLabelFor(a.getResourceId(attr, NO_ID));
4331                    break;
4332                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4333                    if (!a.getBoolean(attr, true)) {
4334                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4335                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4336                    }
4337                    break;
4338                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4339                    if (!a.getBoolean(attr, true)) {
4340                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4341                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4342                    }
4343                    break;
4344                case R.styleable.View_scrollbars:
4345                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4346                    if (scrollbars != SCROLLBARS_NONE) {
4347                        viewFlagValues |= scrollbars;
4348                        viewFlagMasks |= SCROLLBARS_MASK;
4349                        initializeScrollbars = true;
4350                    }
4351                    break;
4352                //noinspection deprecation
4353                case R.styleable.View_fadingEdge:
4354                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4355                        // Ignore the attribute starting with ICS
4356                        break;
4357                    }
4358                    // With builds < ICS, fall through and apply fading edges
4359                case R.styleable.View_requiresFadingEdge:
4360                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4361                    if (fadingEdge != FADING_EDGE_NONE) {
4362                        viewFlagValues |= fadingEdge;
4363                        viewFlagMasks |= FADING_EDGE_MASK;
4364                        initializeFadingEdgeInternal(a);
4365                    }
4366                    break;
4367                case R.styleable.View_scrollbarStyle:
4368                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4369                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4370                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4371                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4372                    }
4373                    break;
4374                case R.styleable.View_isScrollContainer:
4375                    setScrollContainer = true;
4376                    if (a.getBoolean(attr, false)) {
4377                        setScrollContainer(true);
4378                    }
4379                    break;
4380                case com.android.internal.R.styleable.View_keepScreenOn:
4381                    if (a.getBoolean(attr, false)) {
4382                        viewFlagValues |= KEEP_SCREEN_ON;
4383                        viewFlagMasks |= KEEP_SCREEN_ON;
4384                    }
4385                    break;
4386                case R.styleable.View_filterTouchesWhenObscured:
4387                    if (a.getBoolean(attr, false)) {
4388                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4389                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4390                    }
4391                    break;
4392                case R.styleable.View_nextFocusLeft:
4393                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4394                    break;
4395                case R.styleable.View_nextFocusRight:
4396                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4397                    break;
4398                case R.styleable.View_nextFocusUp:
4399                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4400                    break;
4401                case R.styleable.View_nextFocusDown:
4402                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4403                    break;
4404                case R.styleable.View_nextFocusForward:
4405                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4406                    break;
4407                case R.styleable.View_minWidth:
4408                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4409                    break;
4410                case R.styleable.View_minHeight:
4411                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4412                    break;
4413                case R.styleable.View_onClick:
4414                    if (context.isRestricted()) {
4415                        throw new IllegalStateException("The android:onClick attribute cannot "
4416                                + "be used within a restricted context");
4417                    }
4418
4419                    final String handlerName = a.getString(attr);
4420                    if (handlerName != null) {
4421                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4422                    }
4423                    break;
4424                case R.styleable.View_overScrollMode:
4425                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4426                    break;
4427                case R.styleable.View_verticalScrollbarPosition:
4428                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4429                    break;
4430                case R.styleable.View_layerType:
4431                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4432                    break;
4433                case R.styleable.View_textDirection:
4434                    // Clear any text direction flag already set
4435                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4436                    // Set the text direction flags depending on the value of the attribute
4437                    final int textDirection = a.getInt(attr, -1);
4438                    if (textDirection != -1) {
4439                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4440                    }
4441                    break;
4442                case R.styleable.View_textAlignment:
4443                    // Clear any text alignment flag already set
4444                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4445                    // Set the text alignment flag depending on the value of the attribute
4446                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4447                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4448                    break;
4449                case R.styleable.View_importantForAccessibility:
4450                    setImportantForAccessibility(a.getInt(attr,
4451                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4452                    break;
4453                case R.styleable.View_accessibilityLiveRegion:
4454                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4455                    break;
4456                case R.styleable.View_transitionName:
4457                    setTransitionName(a.getString(attr));
4458                    break;
4459                case R.styleable.View_nestedScrollingEnabled:
4460                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4461                    break;
4462                case R.styleable.View_stateListAnimator:
4463                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4464                            a.getResourceId(attr, 0)));
4465                    break;
4466                case R.styleable.View_backgroundTint:
4467                    // This will get applied later during setBackground().
4468                    if (mBackgroundTint == null) {
4469                        mBackgroundTint = new TintInfo();
4470                    }
4471                    mBackgroundTint.mTintList = a.getColorStateList(
4472                            R.styleable.View_backgroundTint);
4473                    mBackgroundTint.mHasTintList = true;
4474                    break;
4475                case R.styleable.View_backgroundTintMode:
4476                    // This will get applied later during setBackground().
4477                    if (mBackgroundTint == null) {
4478                        mBackgroundTint = new TintInfo();
4479                    }
4480                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4481                            R.styleable.View_backgroundTintMode, -1), null);
4482                    mBackgroundTint.mHasTintMode = true;
4483                    break;
4484                case R.styleable.View_outlineProvider:
4485                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4486                            PROVIDER_BACKGROUND));
4487                    break;
4488                case R.styleable.View_foreground:
4489                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4490                        setForeground(a.getDrawable(attr));
4491                    }
4492                    break;
4493                case R.styleable.View_foregroundGravity:
4494                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4495                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4496                    }
4497                    break;
4498                case R.styleable.View_foregroundTintMode:
4499                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4500                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4501                    }
4502                    break;
4503                case R.styleable.View_foregroundTint:
4504                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4505                        setForegroundTintList(a.getColorStateList(attr));
4506                    }
4507                    break;
4508                case R.styleable.View_foregroundInsidePadding:
4509                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4510                        if (mForegroundInfo == null) {
4511                            mForegroundInfo = new ForegroundInfo();
4512                        }
4513                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4514                                mForegroundInfo.mInsidePadding);
4515                    }
4516                    break;
4517                case R.styleable.View_scrollIndicators:
4518                    final int scrollIndicators =
4519                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4520                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4521                    if (scrollIndicators != 0) {
4522                        mPrivateFlags3 |= scrollIndicators;
4523                        initializeScrollIndicators = true;
4524                    }
4525                    break;
4526                case R.styleable.View_pointerShape:
4527                    final int resourceId = a.getResourceId(attr, 0);
4528                    if (resourceId != 0) {
4529                        setPointerIcon(PointerIcon.loadCustomIcon(
4530                                context.getResources(), resourceId));
4531                    } else {
4532                        final int pointerShape = a.getInt(attr, PointerIcon.STYLE_NOT_SPECIFIED);
4533                        if (pointerShape != PointerIcon.STYLE_NOT_SPECIFIED) {
4534                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerShape));
4535                        }
4536                    }
4537                    break;
4538                case R.styleable.View_forceHasOverlappingRendering:
4539                    if (a.peekValue(attr) != null) {
4540                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4541                    }
4542                    break;
4543
4544            }
4545        }
4546
4547        setOverScrollMode(overScrollMode);
4548
4549        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4550        // the resolved layout direction). Those cached values will be used later during padding
4551        // resolution.
4552        mUserPaddingStart = startPadding;
4553        mUserPaddingEnd = endPadding;
4554
4555        if (background != null) {
4556            setBackground(background);
4557        }
4558
4559        // setBackground above will record that padding is currently provided by the background.
4560        // If we have padding specified via xml, record that here instead and use it.
4561        mLeftPaddingDefined = leftPaddingDefined;
4562        mRightPaddingDefined = rightPaddingDefined;
4563
4564        if (padding >= 0) {
4565            leftPadding = padding;
4566            topPadding = padding;
4567            rightPadding = padding;
4568            bottomPadding = padding;
4569            mUserPaddingLeftInitial = padding;
4570            mUserPaddingRightInitial = padding;
4571        }
4572
4573        if (isRtlCompatibilityMode()) {
4574            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4575            // left / right padding are used if defined (meaning here nothing to do). If they are not
4576            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4577            // start / end and resolve them as left / right (layout direction is not taken into account).
4578            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4579            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4580            // defined.
4581            if (!mLeftPaddingDefined && startPaddingDefined) {
4582                leftPadding = startPadding;
4583            }
4584            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4585            if (!mRightPaddingDefined && endPaddingDefined) {
4586                rightPadding = endPadding;
4587            }
4588            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4589        } else {
4590            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4591            // values defined. Otherwise, left /right values are used.
4592            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4593            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4594            // defined.
4595            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4596
4597            if (mLeftPaddingDefined && !hasRelativePadding) {
4598                mUserPaddingLeftInitial = leftPadding;
4599            }
4600            if (mRightPaddingDefined && !hasRelativePadding) {
4601                mUserPaddingRightInitial = rightPadding;
4602            }
4603        }
4604
4605        internalSetPadding(
4606                mUserPaddingLeftInitial,
4607                topPadding >= 0 ? topPadding : mPaddingTop,
4608                mUserPaddingRightInitial,
4609                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4610
4611        if (viewFlagMasks != 0) {
4612            setFlags(viewFlagValues, viewFlagMasks);
4613        }
4614
4615        if (initializeScrollbars) {
4616            initializeScrollbarsInternal(a);
4617        }
4618
4619        if (initializeScrollIndicators) {
4620            initializeScrollIndicatorsInternal();
4621        }
4622
4623        a.recycle();
4624
4625        // Needs to be called after mViewFlags is set
4626        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4627            recomputePadding();
4628        }
4629
4630        if (x != 0 || y != 0) {
4631            scrollTo(x, y);
4632        }
4633
4634        if (transformSet) {
4635            setTranslationX(tx);
4636            setTranslationY(ty);
4637            setTranslationZ(tz);
4638            setElevation(elevation);
4639            setRotation(rotation);
4640            setRotationX(rotationX);
4641            setRotationY(rotationY);
4642            setScaleX(sx);
4643            setScaleY(sy);
4644        }
4645
4646        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4647            setScrollContainer(true);
4648        }
4649
4650        computeOpaqueFlags();
4651    }
4652
4653    /**
4654     * An implementation of OnClickListener that attempts to lazily load a
4655     * named click handling method from a parent or ancestor context.
4656     */
4657    private static class DeclaredOnClickListener implements OnClickListener {
4658        private final View mHostView;
4659        private final String mMethodName;
4660
4661        private Method mResolvedMethod;
4662        private Context mResolvedContext;
4663
4664        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4665            mHostView = hostView;
4666            mMethodName = methodName;
4667        }
4668
4669        @Override
4670        public void onClick(@NonNull View v) {
4671            if (mResolvedMethod == null) {
4672                resolveMethod(mHostView.getContext(), mMethodName);
4673            }
4674
4675            try {
4676                mResolvedMethod.invoke(mResolvedContext, v);
4677            } catch (IllegalAccessException e) {
4678                throw new IllegalStateException(
4679                        "Could not execute non-public method for android:onClick", e);
4680            } catch (InvocationTargetException e) {
4681                throw new IllegalStateException(
4682                        "Could not execute method for android:onClick", e);
4683            }
4684        }
4685
4686        @NonNull
4687        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4688            while (context != null) {
4689                try {
4690                    if (!context.isRestricted()) {
4691                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4692                        if (method != null) {
4693                            mResolvedMethod = method;
4694                            mResolvedContext = context;
4695                            return;
4696                        }
4697                    }
4698                } catch (NoSuchMethodException e) {
4699                    // Failed to find method, keep searching up the hierarchy.
4700                }
4701
4702                if (context instanceof ContextWrapper) {
4703                    context = ((ContextWrapper) context).getBaseContext();
4704                } else {
4705                    // Can't search up the hierarchy, null out and fail.
4706                    context = null;
4707                }
4708            }
4709
4710            final int id = mHostView.getId();
4711            final String idText = id == NO_ID ? "" : " with id '"
4712                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4713            throw new IllegalStateException("Could not find method " + mMethodName
4714                    + "(View) in a parent or ancestor Context for android:onClick "
4715                    + "attribute defined on view " + mHostView.getClass() + idText);
4716        }
4717    }
4718
4719    /**
4720     * Non-public constructor for use in testing
4721     */
4722    View() {
4723        mResources = null;
4724        mRenderNode = RenderNode.create(getClass().getName(), this);
4725    }
4726
4727    private static SparseArray<String> getAttributeMap() {
4728        if (mAttributeMap == null) {
4729            mAttributeMap = new SparseArray<>();
4730        }
4731        return mAttributeMap;
4732    }
4733
4734    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4735        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4736        final int indexCount = t.getIndexCount();
4737        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4738
4739        int i = 0;
4740
4741        // Store raw XML attributes.
4742        for (int j = 0; j < attrsCount; ++j) {
4743            attributes[i] = attrs.getAttributeName(j);
4744            attributes[i + 1] = attrs.getAttributeValue(j);
4745            i += 2;
4746        }
4747
4748        // Store resolved styleable attributes.
4749        final Resources res = t.getResources();
4750        final SparseArray<String> attributeMap = getAttributeMap();
4751        for (int j = 0; j < indexCount; ++j) {
4752            final int index = t.getIndex(j);
4753            if (!t.hasValueOrEmpty(index)) {
4754                // Value is undefined. Skip it.
4755                continue;
4756            }
4757
4758            final int resourceId = t.getResourceId(index, 0);
4759            if (resourceId == 0) {
4760                // Value is not a reference. Skip it.
4761                continue;
4762            }
4763
4764            String resourceName = attributeMap.get(resourceId);
4765            if (resourceName == null) {
4766                try {
4767                    resourceName = res.getResourceName(resourceId);
4768                } catch (Resources.NotFoundException e) {
4769                    resourceName = "0x" + Integer.toHexString(resourceId);
4770                }
4771                attributeMap.put(resourceId, resourceName);
4772            }
4773
4774            attributes[i] = resourceName;
4775            attributes[i + 1] = t.getString(index);
4776            i += 2;
4777        }
4778
4779        // Trim to fit contents.
4780        final String[] trimmed = new String[i];
4781        System.arraycopy(attributes, 0, trimmed, 0, i);
4782        mAttributes = trimmed;
4783    }
4784
4785    public String toString() {
4786        StringBuilder out = new StringBuilder(128);
4787        out.append(getClass().getName());
4788        out.append('{');
4789        out.append(Integer.toHexString(System.identityHashCode(this)));
4790        out.append(' ');
4791        switch (mViewFlags&VISIBILITY_MASK) {
4792            case VISIBLE: out.append('V'); break;
4793            case INVISIBLE: out.append('I'); break;
4794            case GONE: out.append('G'); break;
4795            default: out.append('.'); break;
4796        }
4797        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4798        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4799        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4800        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4801        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4802        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4803        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4804        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4805        out.append(' ');
4806        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4807        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4808        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4809        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4810            out.append('p');
4811        } else {
4812            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4813        }
4814        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4815        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4816        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4817        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4818        out.append(' ');
4819        out.append(mLeft);
4820        out.append(',');
4821        out.append(mTop);
4822        out.append('-');
4823        out.append(mRight);
4824        out.append(',');
4825        out.append(mBottom);
4826        final int id = getId();
4827        if (id != NO_ID) {
4828            out.append(" #");
4829            out.append(Integer.toHexString(id));
4830            final Resources r = mResources;
4831            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
4832                try {
4833                    String pkgname;
4834                    switch (id&0xff000000) {
4835                        case 0x7f000000:
4836                            pkgname="app";
4837                            break;
4838                        case 0x01000000:
4839                            pkgname="android";
4840                            break;
4841                        default:
4842                            pkgname = r.getResourcePackageName(id);
4843                            break;
4844                    }
4845                    String typename = r.getResourceTypeName(id);
4846                    String entryname = r.getResourceEntryName(id);
4847                    out.append(" ");
4848                    out.append(pkgname);
4849                    out.append(":");
4850                    out.append(typename);
4851                    out.append("/");
4852                    out.append(entryname);
4853                } catch (Resources.NotFoundException e) {
4854                }
4855            }
4856        }
4857        out.append("}");
4858        return out.toString();
4859    }
4860
4861    /**
4862     * <p>
4863     * Initializes the fading edges from a given set of styled attributes. This
4864     * method should be called by subclasses that need fading edges and when an
4865     * instance of these subclasses is created programmatically rather than
4866     * being inflated from XML. This method is automatically called when the XML
4867     * is inflated.
4868     * </p>
4869     *
4870     * @param a the styled attributes set to initialize the fading edges from
4871     *
4872     * @removed
4873     */
4874    protected void initializeFadingEdge(TypedArray a) {
4875        // This method probably shouldn't have been included in the SDK to begin with.
4876        // It relies on 'a' having been initialized using an attribute filter array that is
4877        // not publicly available to the SDK. The old method has been renamed
4878        // to initializeFadingEdgeInternal and hidden for framework use only;
4879        // this one initializes using defaults to make it safe to call for apps.
4880
4881        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4882
4883        initializeFadingEdgeInternal(arr);
4884
4885        arr.recycle();
4886    }
4887
4888    /**
4889     * <p>
4890     * Initializes the fading edges from a given set of styled attributes. This
4891     * method should be called by subclasses that need fading edges and when an
4892     * instance of these subclasses is created programmatically rather than
4893     * being inflated from XML. This method is automatically called when the XML
4894     * is inflated.
4895     * </p>
4896     *
4897     * @param a the styled attributes set to initialize the fading edges from
4898     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4899     */
4900    protected void initializeFadingEdgeInternal(TypedArray a) {
4901        initScrollCache();
4902
4903        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4904                R.styleable.View_fadingEdgeLength,
4905                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4906    }
4907
4908    /**
4909     * Returns the size of the vertical faded edges used to indicate that more
4910     * content in this view is visible.
4911     *
4912     * @return The size in pixels of the vertical faded edge or 0 if vertical
4913     *         faded edges are not enabled for this view.
4914     * @attr ref android.R.styleable#View_fadingEdgeLength
4915     */
4916    public int getVerticalFadingEdgeLength() {
4917        if (isVerticalFadingEdgeEnabled()) {
4918            ScrollabilityCache cache = mScrollCache;
4919            if (cache != null) {
4920                return cache.fadingEdgeLength;
4921            }
4922        }
4923        return 0;
4924    }
4925
4926    /**
4927     * Set the size of the faded edge used to indicate that more content in this
4928     * view is available.  Will not change whether the fading edge is enabled; use
4929     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4930     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4931     * for the vertical or horizontal fading edges.
4932     *
4933     * @param length The size in pixels of the faded edge used to indicate that more
4934     *        content in this view is visible.
4935     */
4936    public void setFadingEdgeLength(int length) {
4937        initScrollCache();
4938        mScrollCache.fadingEdgeLength = length;
4939    }
4940
4941    /**
4942     * Returns the size of the horizontal faded edges used to indicate that more
4943     * content in this view is visible.
4944     *
4945     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4946     *         faded edges are not enabled for this view.
4947     * @attr ref android.R.styleable#View_fadingEdgeLength
4948     */
4949    public int getHorizontalFadingEdgeLength() {
4950        if (isHorizontalFadingEdgeEnabled()) {
4951            ScrollabilityCache cache = mScrollCache;
4952            if (cache != null) {
4953                return cache.fadingEdgeLength;
4954            }
4955        }
4956        return 0;
4957    }
4958
4959    /**
4960     * Returns the width of the vertical scrollbar.
4961     *
4962     * @return The width in pixels of the vertical scrollbar or 0 if there
4963     *         is no vertical scrollbar.
4964     */
4965    public int getVerticalScrollbarWidth() {
4966        ScrollabilityCache cache = mScrollCache;
4967        if (cache != null) {
4968            ScrollBarDrawable scrollBar = cache.scrollBar;
4969            if (scrollBar != null) {
4970                int size = scrollBar.getSize(true);
4971                if (size <= 0) {
4972                    size = cache.scrollBarSize;
4973                }
4974                return size;
4975            }
4976            return 0;
4977        }
4978        return 0;
4979    }
4980
4981    /**
4982     * Returns the height of the horizontal scrollbar.
4983     *
4984     * @return The height in pixels of the horizontal scrollbar or 0 if
4985     *         there is no horizontal scrollbar.
4986     */
4987    protected int getHorizontalScrollbarHeight() {
4988        ScrollabilityCache cache = mScrollCache;
4989        if (cache != null) {
4990            ScrollBarDrawable scrollBar = cache.scrollBar;
4991            if (scrollBar != null) {
4992                int size = scrollBar.getSize(false);
4993                if (size <= 0) {
4994                    size = cache.scrollBarSize;
4995                }
4996                return size;
4997            }
4998            return 0;
4999        }
5000        return 0;
5001    }
5002
5003    /**
5004     * <p>
5005     * Initializes the scrollbars from a given set of styled attributes. This
5006     * method should be called by subclasses that need scrollbars and when an
5007     * instance of these subclasses is created programmatically rather than
5008     * being inflated from XML. This method is automatically called when the XML
5009     * is inflated.
5010     * </p>
5011     *
5012     * @param a the styled attributes set to initialize the scrollbars from
5013     *
5014     * @removed
5015     */
5016    protected void initializeScrollbars(TypedArray a) {
5017        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5018        // using the View filter array which is not available to the SDK. As such, internal
5019        // framework usage now uses initializeScrollbarsInternal and we grab a default
5020        // TypedArray with the right filter instead here.
5021        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5022
5023        initializeScrollbarsInternal(arr);
5024
5025        // We ignored the method parameter. Recycle the one we actually did use.
5026        arr.recycle();
5027    }
5028
5029    /**
5030     * <p>
5031     * Initializes the scrollbars from a given set of styled attributes. This
5032     * method should be called by subclasses that need scrollbars and when an
5033     * instance of these subclasses is created programmatically rather than
5034     * being inflated from XML. This method is automatically called when the XML
5035     * is inflated.
5036     * </p>
5037     *
5038     * @param a the styled attributes set to initialize the scrollbars from
5039     * @hide
5040     */
5041    protected void initializeScrollbarsInternal(TypedArray a) {
5042        initScrollCache();
5043
5044        final ScrollabilityCache scrollabilityCache = mScrollCache;
5045
5046        if (scrollabilityCache.scrollBar == null) {
5047            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5048            scrollabilityCache.scrollBar.setState(getDrawableState());
5049            scrollabilityCache.scrollBar.setCallback(this);
5050        }
5051
5052        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5053
5054        if (!fadeScrollbars) {
5055            scrollabilityCache.state = ScrollabilityCache.ON;
5056        }
5057        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5058
5059
5060        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5061                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5062                        .getScrollBarFadeDuration());
5063        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5064                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5065                ViewConfiguration.getScrollDefaultDelay());
5066
5067
5068        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5069                com.android.internal.R.styleable.View_scrollbarSize,
5070                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5071
5072        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5073        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5074
5075        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5076        if (thumb != null) {
5077            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5078        }
5079
5080        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5081                false);
5082        if (alwaysDraw) {
5083            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5084        }
5085
5086        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5087        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5088
5089        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5090        if (thumb != null) {
5091            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5092        }
5093
5094        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5095                false);
5096        if (alwaysDraw) {
5097            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5098        }
5099
5100        // Apply layout direction to the new Drawables if needed
5101        final int layoutDirection = getLayoutDirection();
5102        if (track != null) {
5103            track.setLayoutDirection(layoutDirection);
5104        }
5105        if (thumb != null) {
5106            thumb.setLayoutDirection(layoutDirection);
5107        }
5108
5109        // Re-apply user/background padding so that scrollbar(s) get added
5110        resolvePadding();
5111    }
5112
5113    private void initializeScrollIndicatorsInternal() {
5114        // Some day maybe we'll break this into top/left/start/etc. and let the
5115        // client control it. Until then, you can have any scroll indicator you
5116        // want as long as it's a 1dp foreground-colored rectangle.
5117        if (mScrollIndicatorDrawable == null) {
5118            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5119        }
5120    }
5121
5122    /**
5123     * <p>
5124     * Initalizes the scrollability cache if necessary.
5125     * </p>
5126     */
5127    private void initScrollCache() {
5128        if (mScrollCache == null) {
5129            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5130        }
5131    }
5132
5133    private ScrollabilityCache getScrollCache() {
5134        initScrollCache();
5135        return mScrollCache;
5136    }
5137
5138    /**
5139     * Set the position of the vertical scroll bar. Should be one of
5140     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5141     * {@link #SCROLLBAR_POSITION_RIGHT}.
5142     *
5143     * @param position Where the vertical scroll bar should be positioned.
5144     */
5145    public void setVerticalScrollbarPosition(int position) {
5146        if (mVerticalScrollbarPosition != position) {
5147            mVerticalScrollbarPosition = position;
5148            computeOpaqueFlags();
5149            resolvePadding();
5150        }
5151    }
5152
5153    /**
5154     * @return The position where the vertical scroll bar will show, if applicable.
5155     * @see #setVerticalScrollbarPosition(int)
5156     */
5157    public int getVerticalScrollbarPosition() {
5158        return mVerticalScrollbarPosition;
5159    }
5160
5161    boolean isOnScrollbar(float x, float y) {
5162        if (mScrollCache == null) {
5163            return false;
5164        }
5165        x += getScrollX();
5166        y += getScrollY();
5167        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5168            final Rect bounds = mScrollCache.mScrollBarBounds;
5169            getVerticalScrollBarBounds(bounds);
5170            if (bounds.contains((int)x, (int)y)) {
5171                return true;
5172            }
5173        }
5174        if (isHorizontalScrollBarEnabled()) {
5175            final Rect bounds = mScrollCache.mScrollBarBounds;
5176            getHorizontalScrollBarBounds(bounds);
5177            if (bounds.contains((int)x, (int)y)) {
5178                return true;
5179            }
5180        }
5181        return false;
5182    }
5183
5184    boolean isOnScrollbarThumb(float x, float y) {
5185        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5186    }
5187
5188    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5189        if (mScrollCache == null) {
5190            return false;
5191        }
5192        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5193            x += getScrollX();
5194            y += getScrollY();
5195            final Rect bounds = mScrollCache.mScrollBarBounds;
5196            getVerticalScrollBarBounds(bounds);
5197            final int range = computeVerticalScrollRange();
5198            final int offset = computeVerticalScrollOffset();
5199            final int extent = computeVerticalScrollExtent();
5200            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5201                    extent, range);
5202            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5203                    extent, range, offset);
5204            final int thumbTop = bounds.top + thumbOffset;
5205            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5206                    && y <= thumbTop + thumbLength) {
5207                return true;
5208            }
5209        }
5210        return false;
5211    }
5212
5213    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5214        if (mScrollCache == null) {
5215            return false;
5216        }
5217        if (isHorizontalScrollBarEnabled()) {
5218            x += getScrollX();
5219            y += getScrollY();
5220            final Rect bounds = mScrollCache.mScrollBarBounds;
5221            getHorizontalScrollBarBounds(bounds);
5222            final int range = computeHorizontalScrollRange();
5223            final int offset = computeHorizontalScrollOffset();
5224            final int extent = computeHorizontalScrollExtent();
5225            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5226                    extent, range);
5227            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5228                    extent, range, offset);
5229            final int thumbLeft = bounds.left + thumbOffset;
5230            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5231                    && y <= bounds.bottom) {
5232                return true;
5233            }
5234        }
5235        return false;
5236    }
5237
5238    boolean isDraggingScrollBar() {
5239        return mScrollCache != null
5240                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5241    }
5242
5243    /**
5244     * Sets the state of all scroll indicators.
5245     * <p>
5246     * See {@link #setScrollIndicators(int, int)} for usage information.
5247     *
5248     * @param indicators a bitmask of indicators that should be enabled, or
5249     *                   {@code 0} to disable all indicators
5250     * @see #setScrollIndicators(int, int)
5251     * @see #getScrollIndicators()
5252     * @attr ref android.R.styleable#View_scrollIndicators
5253     */
5254    public void setScrollIndicators(@ScrollIndicators int indicators) {
5255        setScrollIndicators(indicators,
5256                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5257    }
5258
5259    /**
5260     * Sets the state of the scroll indicators specified by the mask. To change
5261     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5262     * <p>
5263     * When a scroll indicator is enabled, it will be displayed if the view
5264     * can scroll in the direction of the indicator.
5265     * <p>
5266     * Multiple indicator types may be enabled or disabled by passing the
5267     * logical OR of the desired types. If multiple types are specified, they
5268     * will all be set to the same enabled state.
5269     * <p>
5270     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5271     *
5272     * @param indicators the indicator direction, or the logical OR of multiple
5273     *             indicator directions. One or more of:
5274     *             <ul>
5275     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5276     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5277     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5278     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5279     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5280     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5281     *             </ul>
5282     * @see #setScrollIndicators(int)
5283     * @see #getScrollIndicators()
5284     * @attr ref android.R.styleable#View_scrollIndicators
5285     */
5286    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5287        // Shift and sanitize mask.
5288        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5289        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5290
5291        // Shift and mask indicators.
5292        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5293        indicators &= mask;
5294
5295        // Merge with non-masked flags.
5296        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5297
5298        if (mPrivateFlags3 != updatedFlags) {
5299            mPrivateFlags3 = updatedFlags;
5300
5301            if (indicators != 0) {
5302                initializeScrollIndicatorsInternal();
5303            }
5304            invalidate();
5305        }
5306    }
5307
5308    /**
5309     * Returns a bitmask representing the enabled scroll indicators.
5310     * <p>
5311     * For example, if the top and left scroll indicators are enabled and all
5312     * other indicators are disabled, the return value will be
5313     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5314     * <p>
5315     * To check whether the bottom scroll indicator is enabled, use the value
5316     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5317     *
5318     * @return a bitmask representing the enabled scroll indicators
5319     */
5320    @ScrollIndicators
5321    public int getScrollIndicators() {
5322        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5323                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5324    }
5325
5326    ListenerInfo getListenerInfo() {
5327        if (mListenerInfo != null) {
5328            return mListenerInfo;
5329        }
5330        mListenerInfo = new ListenerInfo();
5331        return mListenerInfo;
5332    }
5333
5334    /**
5335     * Register a callback to be invoked when the scroll X or Y positions of
5336     * this view change.
5337     * <p>
5338     * <b>Note:</b> Some views handle scrolling independently from View and may
5339     * have their own separate listeners for scroll-type events. For example,
5340     * {@link android.widget.ListView ListView} allows clients to register an
5341     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5342     * to listen for changes in list scroll position.
5343     *
5344     * @param l The listener to notify when the scroll X or Y position changes.
5345     * @see android.view.View#getScrollX()
5346     * @see android.view.View#getScrollY()
5347     */
5348    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5349        getListenerInfo().mOnScrollChangeListener = l;
5350    }
5351
5352    /**
5353     * Register a callback to be invoked when focus of this view changed.
5354     *
5355     * @param l The callback that will run.
5356     */
5357    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5358        getListenerInfo().mOnFocusChangeListener = l;
5359    }
5360
5361    /**
5362     * Add a listener that will be called when the bounds of the view change due to
5363     * layout processing.
5364     *
5365     * @param listener The listener that will be called when layout bounds change.
5366     */
5367    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5368        ListenerInfo li = getListenerInfo();
5369        if (li.mOnLayoutChangeListeners == null) {
5370            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5371        }
5372        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5373            li.mOnLayoutChangeListeners.add(listener);
5374        }
5375    }
5376
5377    /**
5378     * Remove a listener for layout changes.
5379     *
5380     * @param listener The listener for layout bounds change.
5381     */
5382    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5383        ListenerInfo li = mListenerInfo;
5384        if (li == null || li.mOnLayoutChangeListeners == null) {
5385            return;
5386        }
5387        li.mOnLayoutChangeListeners.remove(listener);
5388    }
5389
5390    /**
5391     * Add a listener for attach state changes.
5392     *
5393     * This listener will be called whenever this view is attached or detached
5394     * from a window. Remove the listener using
5395     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5396     *
5397     * @param listener Listener to attach
5398     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5399     */
5400    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5401        ListenerInfo li = getListenerInfo();
5402        if (li.mOnAttachStateChangeListeners == null) {
5403            li.mOnAttachStateChangeListeners
5404                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5405        }
5406        li.mOnAttachStateChangeListeners.add(listener);
5407    }
5408
5409    /**
5410     * Remove a listener for attach state changes. The listener will receive no further
5411     * notification of window attach/detach events.
5412     *
5413     * @param listener Listener to remove
5414     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5415     */
5416    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5417        ListenerInfo li = mListenerInfo;
5418        if (li == null || li.mOnAttachStateChangeListeners == null) {
5419            return;
5420        }
5421        li.mOnAttachStateChangeListeners.remove(listener);
5422    }
5423
5424    /**
5425     * Returns the focus-change callback registered for this view.
5426     *
5427     * @return The callback, or null if one is not registered.
5428     */
5429    public OnFocusChangeListener getOnFocusChangeListener() {
5430        ListenerInfo li = mListenerInfo;
5431        return li != null ? li.mOnFocusChangeListener : null;
5432    }
5433
5434    /**
5435     * Register a callback to be invoked when this view is clicked. If this view is not
5436     * clickable, it becomes clickable.
5437     *
5438     * @param l The callback that will run
5439     *
5440     * @see #setClickable(boolean)
5441     */
5442    public void setOnClickListener(@Nullable OnClickListener l) {
5443        if (!isClickable()) {
5444            setClickable(true);
5445        }
5446        getListenerInfo().mOnClickListener = l;
5447    }
5448
5449    /**
5450     * Return whether this view has an attached OnClickListener.  Returns
5451     * true if there is a listener, false if there is none.
5452     */
5453    public boolean hasOnClickListeners() {
5454        ListenerInfo li = mListenerInfo;
5455        return (li != null && li.mOnClickListener != null);
5456    }
5457
5458    /**
5459     * Register a callback to be invoked when this view is clicked and held. If this view is not
5460     * long clickable, it becomes long clickable.
5461     *
5462     * @param l The callback that will run
5463     *
5464     * @see #setLongClickable(boolean)
5465     */
5466    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5467        if (!isLongClickable()) {
5468            setLongClickable(true);
5469        }
5470        getListenerInfo().mOnLongClickListener = l;
5471    }
5472
5473    /**
5474     * Register a callback to be invoked when this view is context clicked. If the view is not
5475     * context clickable, it becomes context clickable.
5476     *
5477     * @param l The callback that will run
5478     * @see #setContextClickable(boolean)
5479     */
5480    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5481        if (!isContextClickable()) {
5482            setContextClickable(true);
5483        }
5484        getListenerInfo().mOnContextClickListener = l;
5485    }
5486
5487    /**
5488     * Register a callback to be invoked when the context menu for this view is
5489     * being built. If this view is not long clickable, it becomes long clickable.
5490     *
5491     * @param l The callback that will run
5492     *
5493     */
5494    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5495        if (!isLongClickable()) {
5496            setLongClickable(true);
5497        }
5498        getListenerInfo().mOnCreateContextMenuListener = l;
5499    }
5500
5501    /**
5502     * Set an observer to collect stats for each frame rendered for this view.
5503     *
5504     * @hide
5505     */
5506    public void addFrameMetricsListener(Window window, Window.FrameMetricsListener listener,
5507            Handler handler) {
5508        if (mAttachInfo != null) {
5509            if (mAttachInfo.mHardwareRenderer != null) {
5510                if (mFrameMetricsObservers == null) {
5511                    mFrameMetricsObservers = new ArrayList<>();
5512                }
5513
5514                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5515                        handler.getLooper(), listener);
5516                mFrameMetricsObservers.add(fmo);
5517                mAttachInfo.mHardwareRenderer.addFrameMetricsObserver(fmo);
5518            } else {
5519                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5520            }
5521        } else {
5522            if (mFrameMetricsObservers == null) {
5523                mFrameMetricsObservers = new ArrayList<>();
5524            }
5525
5526            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5527                    handler.getLooper(), listener);
5528            mFrameMetricsObservers.add(fmo);
5529        }
5530    }
5531
5532    /**
5533     * Remove observer configured to collect frame stats for this view.
5534     *
5535     * @hide
5536     */
5537    public void removeFrameMetricsListener(Window.FrameMetricsListener listener) {
5538        ThreadedRenderer renderer = getHardwareRenderer();
5539        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5540        if (fmo == null) {
5541            throw new IllegalArgumentException("attempt to remove FrameMetricsListener that was never added");
5542        }
5543
5544        if (mFrameMetricsObservers != null) {
5545            mFrameMetricsObservers.remove(fmo);
5546            if (renderer != null) {
5547                renderer.removeFrameMetricsObserver(fmo);
5548            }
5549        }
5550    }
5551
5552    private void registerPendingFrameMetricsObservers() {
5553        if (mFrameMetricsObservers != null) {
5554            ThreadedRenderer renderer = getHardwareRenderer();
5555            if (renderer != null) {
5556                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5557                    renderer.addFrameMetricsObserver(fmo);
5558                }
5559            } else {
5560                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5561            }
5562        }
5563    }
5564
5565    private FrameMetricsObserver findFrameMetricsObserver(Window.FrameMetricsListener listener) {
5566        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5567            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5568            if (observer.mListener == listener) {
5569                return observer;
5570            }
5571        }
5572
5573        return null;
5574    }
5575
5576    /**
5577     * Call this view's OnClickListener, if it is defined.  Performs all normal
5578     * actions associated with clicking: reporting accessibility event, playing
5579     * a sound, etc.
5580     *
5581     * @return True there was an assigned OnClickListener that was called, false
5582     *         otherwise is returned.
5583     */
5584    public boolean performClick() {
5585        final boolean result;
5586        final ListenerInfo li = mListenerInfo;
5587        if (li != null && li.mOnClickListener != null) {
5588            playSoundEffect(SoundEffectConstants.CLICK);
5589            li.mOnClickListener.onClick(this);
5590            result = true;
5591        } else {
5592            result = false;
5593        }
5594
5595        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5596        return result;
5597    }
5598
5599    /**
5600     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5601     * this only calls the listener, and does not do any associated clicking
5602     * actions like reporting an accessibility event.
5603     *
5604     * @return True there was an assigned OnClickListener that was called, false
5605     *         otherwise is returned.
5606     */
5607    public boolean callOnClick() {
5608        ListenerInfo li = mListenerInfo;
5609        if (li != null && li.mOnClickListener != null) {
5610            li.mOnClickListener.onClick(this);
5611            return true;
5612        }
5613        return false;
5614    }
5615
5616    /**
5617     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5618     * context menu if the OnLongClickListener did not consume the event.
5619     *
5620     * @return {@code true} if one of the above receivers consumed the event,
5621     *         {@code false} otherwise
5622     */
5623    public boolean performLongClick() {
5624        return performLongClickInternal(mLongClickX, mLongClickY);
5625    }
5626
5627    /**
5628     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5629     * context menu if the OnLongClickListener did not consume the event,
5630     * anchoring it to an (x,y) coordinate.
5631     *
5632     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5633     *          to disable anchoring
5634     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5635     *          to disable anchoring
5636     * @return {@code true} if one of the above receivers consumed the event,
5637     *         {@code false} otherwise
5638     */
5639    public boolean performLongClick(float x, float y) {
5640        mLongClickX = x;
5641        mLongClickY = y;
5642        final boolean handled = performLongClick();
5643        mLongClickX = Float.NaN;
5644        mLongClickY = Float.NaN;
5645        return handled;
5646    }
5647
5648    /**
5649     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5650     * context menu if the OnLongClickListener did not consume the event,
5651     * optionally anchoring it to an (x,y) coordinate.
5652     *
5653     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5654     *          to disable anchoring
5655     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5656     *          to disable anchoring
5657     * @return {@code true} if one of the above receivers consumed the event,
5658     *         {@code false} otherwise
5659     */
5660    private boolean performLongClickInternal(float x, float y) {
5661        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5662
5663        boolean handled = false;
5664        final ListenerInfo li = mListenerInfo;
5665        if (li != null && li.mOnLongClickListener != null) {
5666            handled = li.mOnLongClickListener.onLongClick(View.this);
5667        }
5668        if (!handled) {
5669            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5670            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5671        }
5672        if (handled) {
5673            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5674        }
5675        return handled;
5676    }
5677
5678    /**
5679     * Call this view's OnContextClickListener, if it is defined.
5680     *
5681     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5682     *         otherwise.
5683     */
5684    public boolean performContextClick() {
5685        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5686
5687        boolean handled = false;
5688        ListenerInfo li = mListenerInfo;
5689        if (li != null && li.mOnContextClickListener != null) {
5690            handled = li.mOnContextClickListener.onContextClick(View.this);
5691        }
5692        if (handled) {
5693            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5694        }
5695        return handled;
5696    }
5697
5698    /**
5699     * Performs button-related actions during a touch down event.
5700     *
5701     * @param event The event.
5702     * @return True if the down was consumed.
5703     *
5704     * @hide
5705     */
5706    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5707        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5708            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5709            showContextMenu(event.getX(), event.getY());
5710            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5711            return true;
5712        }
5713        return false;
5714    }
5715
5716    /**
5717     * Shows the context menu for this view.
5718     *
5719     * @return {@code true} if the context menu was shown, {@code false}
5720     *         otherwise
5721     * @see #showContextMenu(float, float)
5722     */
5723    public boolean showContextMenu() {
5724        return getParent().showContextMenuForChild(this);
5725    }
5726
5727    /**
5728     * Shows the context menu for this view anchored to the specified
5729     * view-relative coordinate.
5730     *
5731     * @param x the X coordinate in pixels relative to the view to which the
5732     *          menu should be anchored
5733     * @param y the Y coordinate in pixels relative to the view to which the
5734     *          menu should be anchored
5735     * @return {@code true} if the context menu was shown, {@code false}
5736     *         otherwise
5737     */
5738    public boolean showContextMenu(float x, float y) {
5739        return getParent().showContextMenuForChild(this, x, y);
5740    }
5741
5742    /**
5743     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5744     *
5745     * @param callback Callback that will control the lifecycle of the action mode
5746     * @return The new action mode if it is started, null otherwise
5747     *
5748     * @see ActionMode
5749     * @see #startActionMode(android.view.ActionMode.Callback, int)
5750     */
5751    public ActionMode startActionMode(ActionMode.Callback callback) {
5752        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5753    }
5754
5755    /**
5756     * Start an action mode with the given type.
5757     *
5758     * @param callback Callback that will control the lifecycle of the action mode
5759     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5760     * @return The new action mode if it is started, null otherwise
5761     *
5762     * @see ActionMode
5763     */
5764    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5765        ViewParent parent = getParent();
5766        if (parent == null) return null;
5767        try {
5768            return parent.startActionModeForChild(this, callback, type);
5769        } catch (AbstractMethodError ame) {
5770            // Older implementations of custom views might not implement this.
5771            return parent.startActionModeForChild(this, callback);
5772        }
5773    }
5774
5775    /**
5776     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5777     * Context, creating a unique View identifier to retrieve the result.
5778     *
5779     * @param intent The Intent to be started.
5780     * @param requestCode The request code to use.
5781     * @hide
5782     */
5783    public void startActivityForResult(Intent intent, int requestCode) {
5784        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5785        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5786    }
5787
5788    /**
5789     * If this View corresponds to the calling who, dispatches the activity result.
5790     * @param who The identifier for the targeted View to receive the result.
5791     * @param requestCode The integer request code originally supplied to
5792     *                    startActivityForResult(), allowing you to identify who this
5793     *                    result came from.
5794     * @param resultCode The integer result code returned by the child activity
5795     *                   through its setResult().
5796     * @param data An Intent, which can return result data to the caller
5797     *               (various data can be attached to Intent "extras").
5798     * @return {@code true} if the activity result was dispatched.
5799     * @hide
5800     */
5801    public boolean dispatchActivityResult(
5802            String who, int requestCode, int resultCode, Intent data) {
5803        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5804            onActivityResult(requestCode, resultCode, data);
5805            mStartActivityRequestWho = null;
5806            return true;
5807        }
5808        return false;
5809    }
5810
5811    /**
5812     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5813     *
5814     * @param requestCode The integer request code originally supplied to
5815     *                    startActivityForResult(), allowing you to identify who this
5816     *                    result came from.
5817     * @param resultCode The integer result code returned by the child activity
5818     *                   through its setResult().
5819     * @param data An Intent, which can return result data to the caller
5820     *               (various data can be attached to Intent "extras").
5821     * @hide
5822     */
5823    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5824        // Do nothing.
5825    }
5826
5827    /**
5828     * Register a callback to be invoked when a hardware key is pressed in this view.
5829     * Key presses in software input methods will generally not trigger the methods of
5830     * this listener.
5831     * @param l the key listener to attach to this view
5832     */
5833    public void setOnKeyListener(OnKeyListener l) {
5834        getListenerInfo().mOnKeyListener = l;
5835    }
5836
5837    /**
5838     * Register a callback to be invoked when a touch event is sent to this view.
5839     * @param l the touch listener to attach to this view
5840     */
5841    public void setOnTouchListener(OnTouchListener l) {
5842        getListenerInfo().mOnTouchListener = l;
5843    }
5844
5845    /**
5846     * Register a callback to be invoked when a generic motion event is sent to this view.
5847     * @param l the generic motion listener to attach to this view
5848     */
5849    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5850        getListenerInfo().mOnGenericMotionListener = l;
5851    }
5852
5853    /**
5854     * Register a callback to be invoked when a hover event is sent to this view.
5855     * @param l the hover listener to attach to this view
5856     */
5857    public void setOnHoverListener(OnHoverListener l) {
5858        getListenerInfo().mOnHoverListener = l;
5859    }
5860
5861    /**
5862     * Register a drag event listener callback object for this View. The parameter is
5863     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5864     * View, the system calls the
5865     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5866     * @param l An implementation of {@link android.view.View.OnDragListener}.
5867     */
5868    public void setOnDragListener(OnDragListener l) {
5869        getListenerInfo().mOnDragListener = l;
5870    }
5871
5872    /**
5873     * Give this view focus. This will cause
5874     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5875     *
5876     * Note: this does not check whether this {@link View} should get focus, it just
5877     * gives it focus no matter what.  It should only be called internally by framework
5878     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5879     *
5880     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5881     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5882     *        focus moved when requestFocus() is called. It may not always
5883     *        apply, in which case use the default View.FOCUS_DOWN.
5884     * @param previouslyFocusedRect The rectangle of the view that had focus
5885     *        prior in this View's coordinate system.
5886     */
5887    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5888        if (DBG) {
5889            System.out.println(this + " requestFocus()");
5890        }
5891
5892        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5893            mPrivateFlags |= PFLAG_FOCUSED;
5894
5895            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5896
5897            if (mParent != null) {
5898                mParent.requestChildFocus(this, this);
5899            }
5900
5901            if (mAttachInfo != null) {
5902                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5903            }
5904
5905            onFocusChanged(true, direction, previouslyFocusedRect);
5906            refreshDrawableState();
5907        }
5908    }
5909
5910    /**
5911     * Populates <code>outRect</code> with the hotspot bounds. By default,
5912     * the hotspot bounds are identical to the screen bounds.
5913     *
5914     * @param outRect rect to populate with hotspot bounds
5915     * @hide Only for internal use by views and widgets.
5916     */
5917    public void getHotspotBounds(Rect outRect) {
5918        final Drawable background = getBackground();
5919        if (background != null) {
5920            background.getHotspotBounds(outRect);
5921        } else {
5922            getBoundsOnScreen(outRect);
5923        }
5924    }
5925
5926    /**
5927     * Request that a rectangle of this view be visible on the screen,
5928     * scrolling if necessary just enough.
5929     *
5930     * <p>A View should call this if it maintains some notion of which part
5931     * of its content is interesting.  For example, a text editing view
5932     * should call this when its cursor moves.
5933     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5934     * It should not be affected by which part of the View is currently visible or its scroll
5935     * position.
5936     *
5937     * @param rectangle The rectangle in the View's content coordinate space
5938     * @return Whether any parent scrolled.
5939     */
5940    public boolean requestRectangleOnScreen(Rect rectangle) {
5941        return requestRectangleOnScreen(rectangle, false);
5942    }
5943
5944    /**
5945     * Request that a rectangle of this view be visible on the screen,
5946     * scrolling if necessary just enough.
5947     *
5948     * <p>A View should call this if it maintains some notion of which part
5949     * of its content is interesting.  For example, a text editing view
5950     * should call this when its cursor moves.
5951     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5952     * It should not be affected by which part of the View is currently visible or its scroll
5953     * position.
5954     * <p>When <code>immediate</code> is set to true, scrolling will not be
5955     * animated.
5956     *
5957     * @param rectangle The rectangle in the View's content coordinate space
5958     * @param immediate True to forbid animated scrolling, false otherwise
5959     * @return Whether any parent scrolled.
5960     */
5961    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5962        if (mParent == null) {
5963            return false;
5964        }
5965
5966        View child = this;
5967
5968        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5969        position.set(rectangle);
5970
5971        ViewParent parent = mParent;
5972        boolean scrolled = false;
5973        while (parent != null) {
5974            rectangle.set((int) position.left, (int) position.top,
5975                    (int) position.right, (int) position.bottom);
5976
5977            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
5978
5979            if (!(parent instanceof View)) {
5980                break;
5981            }
5982
5983            // move it from child's content coordinate space to parent's content coordinate space
5984            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
5985
5986            child = (View) parent;
5987            parent = child.getParent();
5988        }
5989
5990        return scrolled;
5991    }
5992
5993    /**
5994     * Called when this view wants to give up focus. If focus is cleared
5995     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5996     * <p>
5997     * <strong>Note:</strong> When a View clears focus the framework is trying
5998     * to give focus to the first focusable View from the top. Hence, if this
5999     * View is the first from the top that can take focus, then all callbacks
6000     * related to clearing focus will be invoked after which the framework will
6001     * give focus to this view.
6002     * </p>
6003     */
6004    public void clearFocus() {
6005        if (DBG) {
6006            System.out.println(this + " clearFocus()");
6007        }
6008
6009        clearFocusInternal(null, true, true);
6010    }
6011
6012    /**
6013     * Clears focus from the view, optionally propagating the change up through
6014     * the parent hierarchy and requesting that the root view place new focus.
6015     *
6016     * @param propagate whether to propagate the change up through the parent
6017     *            hierarchy
6018     * @param refocus when propagate is true, specifies whether to request the
6019     *            root view place new focus
6020     */
6021    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6022        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6023            mPrivateFlags &= ~PFLAG_FOCUSED;
6024
6025            if (propagate && mParent != null) {
6026                mParent.clearChildFocus(this);
6027            }
6028
6029            onFocusChanged(false, 0, null);
6030            refreshDrawableState();
6031
6032            if (propagate && (!refocus || !rootViewRequestFocus())) {
6033                notifyGlobalFocusCleared(this);
6034            }
6035        }
6036    }
6037
6038    void notifyGlobalFocusCleared(View oldFocus) {
6039        if (oldFocus != null && mAttachInfo != null) {
6040            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6041        }
6042    }
6043
6044    boolean rootViewRequestFocus() {
6045        final View root = getRootView();
6046        return root != null && root.requestFocus();
6047    }
6048
6049    /**
6050     * Called internally by the view system when a new view is getting focus.
6051     * This is what clears the old focus.
6052     * <p>
6053     * <b>NOTE:</b> The parent view's focused child must be updated manually
6054     * after calling this method. Otherwise, the view hierarchy may be left in
6055     * an inconstent state.
6056     */
6057    void unFocus(View focused) {
6058        if (DBG) {
6059            System.out.println(this + " unFocus()");
6060        }
6061
6062        clearFocusInternal(focused, false, false);
6063    }
6064
6065    /**
6066     * Returns true if this view has focus itself, or is the ancestor of the
6067     * view that has focus.
6068     *
6069     * @return True if this view has or contains focus, false otherwise.
6070     */
6071    @ViewDebug.ExportedProperty(category = "focus")
6072    public boolean hasFocus() {
6073        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6074    }
6075
6076    /**
6077     * Returns true if this view is focusable or if it contains a reachable View
6078     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6079     * is a View whose parents do not block descendants focus.
6080     *
6081     * Only {@link #VISIBLE} views are considered focusable.
6082     *
6083     * @return True if the view is focusable or if the view contains a focusable
6084     *         View, false otherwise.
6085     *
6086     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6087     * @see ViewGroup#getTouchscreenBlocksFocus()
6088     */
6089    public boolean hasFocusable() {
6090        if (!isFocusableInTouchMode()) {
6091            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6092                final ViewGroup g = (ViewGroup) p;
6093                if (g.shouldBlockFocusForTouchscreen()) {
6094                    return false;
6095                }
6096            }
6097        }
6098        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6099    }
6100
6101    /**
6102     * Called by the view system when the focus state of this view changes.
6103     * When the focus change event is caused by directional navigation, direction
6104     * and previouslyFocusedRect provide insight into where the focus is coming from.
6105     * When overriding, be sure to call up through to the super class so that
6106     * the standard focus handling will occur.
6107     *
6108     * @param gainFocus True if the View has focus; false otherwise.
6109     * @param direction The direction focus has moved when requestFocus()
6110     *                  is called to give this view focus. Values are
6111     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6112     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6113     *                  It may not always apply, in which case use the default.
6114     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6115     *        system, of the previously focused view.  If applicable, this will be
6116     *        passed in as finer grained information about where the focus is coming
6117     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6118     */
6119    @CallSuper
6120    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6121            @Nullable Rect previouslyFocusedRect) {
6122        if (gainFocus) {
6123            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6124        } else {
6125            notifyViewAccessibilityStateChangedIfNeeded(
6126                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6127        }
6128
6129        InputMethodManager imm = InputMethodManager.peekInstance();
6130        if (!gainFocus) {
6131            if (isPressed()) {
6132                setPressed(false);
6133            }
6134            if (imm != null && mAttachInfo != null
6135                    && mAttachInfo.mHasWindowFocus) {
6136                imm.focusOut(this);
6137            }
6138            onFocusLost();
6139        } else if (imm != null && mAttachInfo != null
6140                && mAttachInfo.mHasWindowFocus) {
6141            imm.focusIn(this);
6142        }
6143
6144        invalidate(true);
6145        ListenerInfo li = mListenerInfo;
6146        if (li != null && li.mOnFocusChangeListener != null) {
6147            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6148        }
6149
6150        if (mAttachInfo != null) {
6151            mAttachInfo.mKeyDispatchState.reset(this);
6152        }
6153    }
6154
6155    /**
6156     * Sends an accessibility event of the given type. If accessibility is
6157     * not enabled this method has no effect. The default implementation calls
6158     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6159     * to populate information about the event source (this View), then calls
6160     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6161     * populate the text content of the event source including its descendants,
6162     * and last calls
6163     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6164     * on its parent to request sending of the event to interested parties.
6165     * <p>
6166     * If an {@link AccessibilityDelegate} has been specified via calling
6167     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6168     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6169     * responsible for handling this call.
6170     * </p>
6171     *
6172     * @param eventType The type of the event to send, as defined by several types from
6173     * {@link android.view.accessibility.AccessibilityEvent}, such as
6174     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6175     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6176     *
6177     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6178     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6179     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6180     * @see AccessibilityDelegate
6181     */
6182    public void sendAccessibilityEvent(int eventType) {
6183        if (mAccessibilityDelegate != null) {
6184            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6185        } else {
6186            sendAccessibilityEventInternal(eventType);
6187        }
6188    }
6189
6190    /**
6191     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6192     * {@link AccessibilityEvent} to make an announcement which is related to some
6193     * sort of a context change for which none of the events representing UI transitions
6194     * is a good fit. For example, announcing a new page in a book. If accessibility
6195     * is not enabled this method does nothing.
6196     *
6197     * @param text The announcement text.
6198     */
6199    public void announceForAccessibility(CharSequence text) {
6200        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6201            AccessibilityEvent event = AccessibilityEvent.obtain(
6202                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6203            onInitializeAccessibilityEvent(event);
6204            event.getText().add(text);
6205            event.setContentDescription(null);
6206            mParent.requestSendAccessibilityEvent(this, event);
6207        }
6208    }
6209
6210    /**
6211     * @see #sendAccessibilityEvent(int)
6212     *
6213     * Note: Called from the default {@link AccessibilityDelegate}.
6214     *
6215     * @hide
6216     */
6217    public void sendAccessibilityEventInternal(int eventType) {
6218        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6219            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6220        }
6221    }
6222
6223    /**
6224     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6225     * takes as an argument an empty {@link AccessibilityEvent} and does not
6226     * perform a check whether accessibility is enabled.
6227     * <p>
6228     * If an {@link AccessibilityDelegate} has been specified via calling
6229     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6230     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6231     * is responsible for handling this call.
6232     * </p>
6233     *
6234     * @param event The event to send.
6235     *
6236     * @see #sendAccessibilityEvent(int)
6237     */
6238    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6239        if (mAccessibilityDelegate != null) {
6240            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6241        } else {
6242            sendAccessibilityEventUncheckedInternal(event);
6243        }
6244    }
6245
6246    /**
6247     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6248     *
6249     * Note: Called from the default {@link AccessibilityDelegate}.
6250     *
6251     * @hide
6252     */
6253    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6254        if (!isShown()) {
6255            return;
6256        }
6257        onInitializeAccessibilityEvent(event);
6258        // Only a subset of accessibility events populates text content.
6259        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6260            dispatchPopulateAccessibilityEvent(event);
6261        }
6262        // In the beginning we called #isShown(), so we know that getParent() is not null.
6263        getParent().requestSendAccessibilityEvent(this, event);
6264    }
6265
6266    /**
6267     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6268     * to its children for adding their text content to the event. Note that the
6269     * event text is populated in a separate dispatch path since we add to the
6270     * event not only the text of the source but also the text of all its descendants.
6271     * A typical implementation will call
6272     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6273     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6274     * on each child. Override this method if custom population of the event text
6275     * content is required.
6276     * <p>
6277     * If an {@link AccessibilityDelegate} has been specified via calling
6278     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6279     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6280     * is responsible for handling this call.
6281     * </p>
6282     * <p>
6283     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6284     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6285     * </p>
6286     *
6287     * @param event The event.
6288     *
6289     * @return True if the event population was completed.
6290     */
6291    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6292        if (mAccessibilityDelegate != null) {
6293            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6294        } else {
6295            return dispatchPopulateAccessibilityEventInternal(event);
6296        }
6297    }
6298
6299    /**
6300     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6301     *
6302     * Note: Called from the default {@link AccessibilityDelegate}.
6303     *
6304     * @hide
6305     */
6306    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6307        onPopulateAccessibilityEvent(event);
6308        return false;
6309    }
6310
6311    /**
6312     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6313     * giving a chance to this View to populate the accessibility event with its
6314     * text content. While this method is free to modify event
6315     * attributes other than text content, doing so should normally be performed in
6316     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6317     * <p>
6318     * Example: Adding formatted date string to an accessibility event in addition
6319     *          to the text added by the super implementation:
6320     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6321     *     super.onPopulateAccessibilityEvent(event);
6322     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6323     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6324     *         mCurrentDate.getTimeInMillis(), flags);
6325     *     event.getText().add(selectedDateUtterance);
6326     * }</pre>
6327     * <p>
6328     * If an {@link AccessibilityDelegate} has been specified via calling
6329     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6330     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6331     * is responsible for handling this call.
6332     * </p>
6333     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6334     * information to the event, in case the default implementation has basic information to add.
6335     * </p>
6336     *
6337     * @param event The accessibility event which to populate.
6338     *
6339     * @see #sendAccessibilityEvent(int)
6340     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6341     */
6342    @CallSuper
6343    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6344        if (mAccessibilityDelegate != null) {
6345            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6346        } else {
6347            onPopulateAccessibilityEventInternal(event);
6348        }
6349    }
6350
6351    /**
6352     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6353     *
6354     * Note: Called from the default {@link AccessibilityDelegate}.
6355     *
6356     * @hide
6357     */
6358    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6359    }
6360
6361    /**
6362     * Initializes an {@link AccessibilityEvent} with information about
6363     * this View which is the event source. In other words, the source of
6364     * an accessibility event is the view whose state change triggered firing
6365     * the event.
6366     * <p>
6367     * Example: Setting the password property of an event in addition
6368     *          to properties set by the super implementation:
6369     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6370     *     super.onInitializeAccessibilityEvent(event);
6371     *     event.setPassword(true);
6372     * }</pre>
6373     * <p>
6374     * If an {@link AccessibilityDelegate} has been specified via calling
6375     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6376     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6377     * is responsible for handling this call.
6378     * </p>
6379     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6380     * information to the event, in case the default implementation has basic information to add.
6381     * </p>
6382     * @param event The event to initialize.
6383     *
6384     * @see #sendAccessibilityEvent(int)
6385     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6386     */
6387    @CallSuper
6388    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6389        if (mAccessibilityDelegate != null) {
6390            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6391        } else {
6392            onInitializeAccessibilityEventInternal(event);
6393        }
6394    }
6395
6396    /**
6397     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6398     *
6399     * Note: Called from the default {@link AccessibilityDelegate}.
6400     *
6401     * @hide
6402     */
6403    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6404        event.setSource(this);
6405        event.setClassName(getAccessibilityClassName());
6406        event.setPackageName(getContext().getPackageName());
6407        event.setEnabled(isEnabled());
6408        event.setContentDescription(mContentDescription);
6409
6410        switch (event.getEventType()) {
6411            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6412                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6413                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6414                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6415                event.setItemCount(focusablesTempList.size());
6416                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6417                if (mAttachInfo != null) {
6418                    focusablesTempList.clear();
6419                }
6420            } break;
6421            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6422                CharSequence text = getIterableTextForAccessibility();
6423                if (text != null && text.length() > 0) {
6424                    event.setFromIndex(getAccessibilitySelectionStart());
6425                    event.setToIndex(getAccessibilitySelectionEnd());
6426                    event.setItemCount(text.length());
6427                }
6428            } break;
6429        }
6430    }
6431
6432    /**
6433     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6434     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6435     * This method is responsible for obtaining an accessibility node info from a
6436     * pool of reusable instances and calling
6437     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6438     * initialize the former.
6439     * <p>
6440     * Note: The client is responsible for recycling the obtained instance by calling
6441     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6442     * </p>
6443     *
6444     * @return A populated {@link AccessibilityNodeInfo}.
6445     *
6446     * @see AccessibilityNodeInfo
6447     */
6448    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6449        if (mAccessibilityDelegate != null) {
6450            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6451        } else {
6452            return createAccessibilityNodeInfoInternal();
6453        }
6454    }
6455
6456    /**
6457     * @see #createAccessibilityNodeInfo()
6458     *
6459     * @hide
6460     */
6461    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6462        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6463        if (provider != null) {
6464            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6465        } else {
6466            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6467            onInitializeAccessibilityNodeInfo(info);
6468            return info;
6469        }
6470    }
6471
6472    /**
6473     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6474     * The base implementation sets:
6475     * <ul>
6476     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6477     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6478     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6479     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6480     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6481     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6482     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6483     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6484     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6485     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6486     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6487     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6488     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6489     * </ul>
6490     * <p>
6491     * Subclasses should override this method, call the super implementation,
6492     * and set additional attributes.
6493     * </p>
6494     * <p>
6495     * If an {@link AccessibilityDelegate} has been specified via calling
6496     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6497     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6498     * is responsible for handling this call.
6499     * </p>
6500     *
6501     * @param info The instance to initialize.
6502     */
6503    @CallSuper
6504    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6505        if (mAccessibilityDelegate != null) {
6506            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6507        } else {
6508            onInitializeAccessibilityNodeInfoInternal(info);
6509        }
6510    }
6511
6512    /**
6513     * Gets the location of this view in screen coordinates.
6514     *
6515     * @param outRect The output location
6516     * @hide
6517     */
6518    public void getBoundsOnScreen(Rect outRect) {
6519        getBoundsOnScreen(outRect, false);
6520    }
6521
6522    /**
6523     * Gets the location of this view in screen coordinates.
6524     *
6525     * @param outRect The output location
6526     * @param clipToParent Whether to clip child bounds to the parent ones.
6527     * @hide
6528     */
6529    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6530        if (mAttachInfo == null) {
6531            return;
6532        }
6533
6534        RectF position = mAttachInfo.mTmpTransformRect;
6535        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6536
6537        if (!hasIdentityMatrix()) {
6538            getMatrix().mapRect(position);
6539        }
6540
6541        position.offset(mLeft, mTop);
6542
6543        ViewParent parent = mParent;
6544        while (parent instanceof View) {
6545            View parentView = (View) parent;
6546
6547            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6548
6549            if (clipToParent) {
6550                position.left = Math.max(position.left, 0);
6551                position.top = Math.max(position.top, 0);
6552                position.right = Math.min(position.right, parentView.getWidth());
6553                position.bottom = Math.min(position.bottom, parentView.getHeight());
6554            }
6555
6556            if (!parentView.hasIdentityMatrix()) {
6557                parentView.getMatrix().mapRect(position);
6558            }
6559
6560            position.offset(parentView.mLeft, parentView.mTop);
6561
6562            parent = parentView.mParent;
6563        }
6564
6565        if (parent instanceof ViewRootImpl) {
6566            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6567            position.offset(0, -viewRootImpl.mCurScrollY);
6568        }
6569
6570        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6571
6572        outRect.set(Math.round(position.left), Math.round(position.top),
6573                Math.round(position.right), Math.round(position.bottom));
6574    }
6575
6576    /**
6577     * Return the class name of this object to be used for accessibility purposes.
6578     * Subclasses should only override this if they are implementing something that
6579     * should be seen as a completely new class of view when used by accessibility,
6580     * unrelated to the class it is deriving from.  This is used to fill in
6581     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6582     */
6583    public CharSequence getAccessibilityClassName() {
6584        return View.class.getName();
6585    }
6586
6587    /**
6588     * Called when assist structure is being retrieved from a view as part of
6589     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6590     * @param structure Fill in with structured view data.  The default implementation
6591     * fills in all data that can be inferred from the view itself.
6592     */
6593    public void onProvideStructure(ViewStructure structure) {
6594        final int id = mID;
6595        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6596                && (id&0x0000ffff) != 0) {
6597            String pkg, type, entry;
6598            try {
6599                final Resources res = getResources();
6600                entry = res.getResourceEntryName(id);
6601                type = res.getResourceTypeName(id);
6602                pkg = res.getResourcePackageName(id);
6603            } catch (Resources.NotFoundException e) {
6604                entry = type = pkg = null;
6605            }
6606            structure.setId(id, pkg, type, entry);
6607        } else {
6608            structure.setId(id, null, null, null);
6609        }
6610        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6611        if (!hasIdentityMatrix()) {
6612            structure.setTransformation(getMatrix());
6613        }
6614        structure.setElevation(getZ());
6615        structure.setVisibility(getVisibility());
6616        structure.setEnabled(isEnabled());
6617        if (isClickable()) {
6618            structure.setClickable(true);
6619        }
6620        if (isFocusable()) {
6621            structure.setFocusable(true);
6622        }
6623        if (isFocused()) {
6624            structure.setFocused(true);
6625        }
6626        if (isAccessibilityFocused()) {
6627            structure.setAccessibilityFocused(true);
6628        }
6629        if (isSelected()) {
6630            structure.setSelected(true);
6631        }
6632        if (isActivated()) {
6633            structure.setActivated(true);
6634        }
6635        if (isLongClickable()) {
6636            structure.setLongClickable(true);
6637        }
6638        if (this instanceof Checkable) {
6639            structure.setCheckable(true);
6640            if (((Checkable)this).isChecked()) {
6641                structure.setChecked(true);
6642            }
6643        }
6644        if (isContextClickable()) {
6645            structure.setContextClickable(true);
6646        }
6647        structure.setClassName(getAccessibilityClassName().toString());
6648        structure.setContentDescription(getContentDescription());
6649    }
6650
6651    /**
6652     * Called when assist structure is being retrieved from a view as part of
6653     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6654     * generate additional virtual structure under this view.  The defaullt implementation
6655     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6656     * view's virtual accessibility nodes, if any.  You can override this for a more
6657     * optimal implementation providing this data.
6658     */
6659    public void onProvideVirtualStructure(ViewStructure structure) {
6660        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6661        if (provider != null) {
6662            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6663            structure.setChildCount(1);
6664            ViewStructure root = structure.newChild(0);
6665            populateVirtualStructure(root, provider, info);
6666            info.recycle();
6667        }
6668    }
6669
6670    private void populateVirtualStructure(ViewStructure structure,
6671            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
6672        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6673                null, null, null);
6674        Rect rect = structure.getTempRect();
6675        info.getBoundsInParent(rect);
6676        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6677        structure.setVisibility(VISIBLE);
6678        structure.setEnabled(info.isEnabled());
6679        if (info.isClickable()) {
6680            structure.setClickable(true);
6681        }
6682        if (info.isFocusable()) {
6683            structure.setFocusable(true);
6684        }
6685        if (info.isFocused()) {
6686            structure.setFocused(true);
6687        }
6688        if (info.isAccessibilityFocused()) {
6689            structure.setAccessibilityFocused(true);
6690        }
6691        if (info.isSelected()) {
6692            structure.setSelected(true);
6693        }
6694        if (info.isLongClickable()) {
6695            structure.setLongClickable(true);
6696        }
6697        if (info.isCheckable()) {
6698            structure.setCheckable(true);
6699            if (info.isChecked()) {
6700                structure.setChecked(true);
6701            }
6702        }
6703        if (info.isContextClickable()) {
6704            structure.setContextClickable(true);
6705        }
6706        CharSequence cname = info.getClassName();
6707        structure.setClassName(cname != null ? cname.toString() : null);
6708        structure.setContentDescription(info.getContentDescription());
6709        if (info.getText() != null || info.getError() != null) {
6710            structure.setText(info.getText(), info.getTextSelectionStart(),
6711                    info.getTextSelectionEnd());
6712        }
6713        final int NCHILDREN = info.getChildCount();
6714        if (NCHILDREN > 0) {
6715            structure.setChildCount(NCHILDREN);
6716            for (int i=0; i<NCHILDREN; i++) {
6717                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6718                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6719                ViewStructure child = structure.newChild(i);
6720                populateVirtualStructure(child, provider, cinfo);
6721                cinfo.recycle();
6722            }
6723        }
6724    }
6725
6726    /**
6727     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6728     * implementation calls {@link #onProvideStructure} and
6729     * {@link #onProvideVirtualStructure}.
6730     */
6731    public void dispatchProvideStructure(ViewStructure structure) {
6732        if (!isAssistBlocked()) {
6733            onProvideStructure(structure);
6734            onProvideVirtualStructure(structure);
6735        } else {
6736            structure.setClassName(getAccessibilityClassName().toString());
6737            structure.setAssistBlocked(true);
6738        }
6739    }
6740
6741    /**
6742     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6743     *
6744     * Note: Called from the default {@link AccessibilityDelegate}.
6745     *
6746     * @hide
6747     */
6748    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6749        if (mAttachInfo == null) {
6750            return;
6751        }
6752
6753        Rect bounds = mAttachInfo.mTmpInvalRect;
6754
6755        getDrawingRect(bounds);
6756        info.setBoundsInParent(bounds);
6757
6758        getBoundsOnScreen(bounds, true);
6759        info.setBoundsInScreen(bounds);
6760
6761        ViewParent parent = getParentForAccessibility();
6762        if (parent instanceof View) {
6763            info.setParent((View) parent);
6764        }
6765
6766        if (mID != View.NO_ID) {
6767            View rootView = getRootView();
6768            if (rootView == null) {
6769                rootView = this;
6770            }
6771
6772            View label = rootView.findLabelForView(this, mID);
6773            if (label != null) {
6774                info.setLabeledBy(label);
6775            }
6776
6777            if ((mAttachInfo.mAccessibilityFetchFlags
6778                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6779                    && Resources.resourceHasPackage(mID)) {
6780                try {
6781                    String viewId = getResources().getResourceName(mID);
6782                    info.setViewIdResourceName(viewId);
6783                } catch (Resources.NotFoundException nfe) {
6784                    /* ignore */
6785                }
6786            }
6787        }
6788
6789        if (mLabelForId != View.NO_ID) {
6790            View rootView = getRootView();
6791            if (rootView == null) {
6792                rootView = this;
6793            }
6794            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6795            if (labeled != null) {
6796                info.setLabelFor(labeled);
6797            }
6798        }
6799
6800        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6801            View rootView = getRootView();
6802            if (rootView == null) {
6803                rootView = this;
6804            }
6805            View next = rootView.findViewInsideOutShouldExist(this,
6806                    mAccessibilityTraversalBeforeId);
6807            if (next != null && next.includeForAccessibility()) {
6808                info.setTraversalBefore(next);
6809            }
6810        }
6811
6812        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6813            View rootView = getRootView();
6814            if (rootView == null) {
6815                rootView = this;
6816            }
6817            View next = rootView.findViewInsideOutShouldExist(this,
6818                    mAccessibilityTraversalAfterId);
6819            if (next != null && next.includeForAccessibility()) {
6820                info.setTraversalAfter(next);
6821            }
6822        }
6823
6824        info.setVisibleToUser(isVisibleToUser());
6825
6826        if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags
6827                & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) {
6828            info.setImportantForAccessibility(isImportantForAccessibility());
6829        } else {
6830            info.setImportantForAccessibility(true);
6831        }
6832
6833        info.setPackageName(mContext.getPackageName());
6834        info.setClassName(getAccessibilityClassName());
6835        info.setContentDescription(getContentDescription());
6836
6837        info.setEnabled(isEnabled());
6838        info.setClickable(isClickable());
6839        info.setFocusable(isFocusable());
6840        info.setFocused(isFocused());
6841        info.setAccessibilityFocused(isAccessibilityFocused());
6842        info.setSelected(isSelected());
6843        info.setLongClickable(isLongClickable());
6844        info.setContextClickable(isContextClickable());
6845        info.setLiveRegion(getAccessibilityLiveRegion());
6846
6847        // TODO: These make sense only if we are in an AdapterView but all
6848        // views can be selected. Maybe from accessibility perspective
6849        // we should report as selectable view in an AdapterView.
6850        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6851        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6852
6853        if (isFocusable()) {
6854            if (isFocused()) {
6855                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6856            } else {
6857                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6858            }
6859        }
6860
6861        if (!isAccessibilityFocused()) {
6862            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6863        } else {
6864            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6865        }
6866
6867        if (isClickable() && isEnabled()) {
6868            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6869        }
6870
6871        if (isLongClickable() && isEnabled()) {
6872            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6873        }
6874
6875        if (isContextClickable() && isEnabled()) {
6876            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6877        }
6878
6879        CharSequence text = getIterableTextForAccessibility();
6880        if (text != null && text.length() > 0) {
6881            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6882
6883            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6884            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6885            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6886            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6887                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6888                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6889        }
6890
6891        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6892        populateAccessibilityNodeInfoDrawingOrderInParent(info);
6893    }
6894
6895    /**
6896     * Determine the order in which this view will be drawn relative to its siblings for a11y
6897     *
6898     * @param info The info whose drawing order should be populated
6899     */
6900    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
6901        /*
6902         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
6903         * drawing order may not be well-defined, and some Views with custom drawing order may
6904         * not be initialized sufficiently to respond properly getChildDrawingOrder.
6905         */
6906        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
6907            info.setDrawingOrder(0);
6908            return;
6909        }
6910        int drawingOrderInParent = 1;
6911        // Iterate up the hierarchy if parents are not important for a11y
6912        View viewAtDrawingLevel = this;
6913        final ViewParent parent = getParentForAccessibility();
6914        while (viewAtDrawingLevel != parent) {
6915            final ViewParent currentParent = viewAtDrawingLevel.getParent();
6916            if (!(currentParent instanceof ViewGroup)) {
6917                // Should only happen for the Decor
6918                drawingOrderInParent = 0;
6919                break;
6920            } else {
6921                final ViewGroup parentGroup = (ViewGroup) currentParent;
6922                final int childCount = parentGroup.getChildCount();
6923                if (childCount > 1) {
6924                    List<View> preorderedList = parentGroup.buildOrderedChildList();
6925                    if (preorderedList != null) {
6926                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
6927                        for (int i = 0; i < childDrawIndex; i++) {
6928                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
6929                        }
6930                    } else {
6931                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
6932                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
6933                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
6934                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
6935                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
6936                        if (childDrawIndex != 0) {
6937                            for (int i = 0; i < numChildrenToIterate; i++) {
6938                                final int otherDrawIndex = (customOrder ?
6939                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
6940                                if (otherDrawIndex < childDrawIndex) {
6941                                    drawingOrderInParent +=
6942                                            numViewsForAccessibility(parentGroup.getChildAt(i));
6943                                }
6944                            }
6945                        }
6946                    }
6947                }
6948            }
6949            viewAtDrawingLevel = (View) currentParent;
6950        }
6951        info.setDrawingOrder(drawingOrderInParent);
6952    }
6953
6954    private static int numViewsForAccessibility(View view) {
6955        if (view != null) {
6956            if (view.includeForAccessibility()) {
6957                return 1;
6958            } else if (view instanceof ViewGroup) {
6959                return ((ViewGroup) view).getNumChildrenForAccessibility();
6960            }
6961        }
6962        return 0;
6963    }
6964
6965    private View findLabelForView(View view, int labeledId) {
6966        if (mMatchLabelForPredicate == null) {
6967            mMatchLabelForPredicate = new MatchLabelForPredicate();
6968        }
6969        mMatchLabelForPredicate.mLabeledId = labeledId;
6970        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
6971    }
6972
6973    /**
6974     * Computes whether this view is visible to the user. Such a view is
6975     * attached, visible, all its predecessors are visible, it is not clipped
6976     * entirely by its predecessors, and has an alpha greater than zero.
6977     *
6978     * @return Whether the view is visible on the screen.
6979     *
6980     * @hide
6981     */
6982    protected boolean isVisibleToUser() {
6983        return isVisibleToUser(null);
6984    }
6985
6986    /**
6987     * Computes whether the given portion of this view is visible to the user.
6988     * Such a view is attached, visible, all its predecessors are visible,
6989     * has an alpha greater than zero, and the specified portion is not
6990     * clipped entirely by its predecessors.
6991     *
6992     * @param boundInView the portion of the view to test; coordinates should be relative; may be
6993     *                    <code>null</code>, and the entire view will be tested in this case.
6994     *                    When <code>true</code> is returned by the function, the actual visible
6995     *                    region will be stored in this parameter; that is, if boundInView is fully
6996     *                    contained within the view, no modification will be made, otherwise regions
6997     *                    outside of the visible area of the view will be clipped.
6998     *
6999     * @return Whether the specified portion of the view is visible on the screen.
7000     *
7001     * @hide
7002     */
7003    protected boolean isVisibleToUser(Rect boundInView) {
7004        if (mAttachInfo != null) {
7005            // Attached to invisible window means this view is not visible.
7006            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7007                return false;
7008            }
7009            // An invisible predecessor or one with alpha zero means
7010            // that this view is not visible to the user.
7011            Object current = this;
7012            while (current instanceof View) {
7013                View view = (View) current;
7014                // We have attach info so this view is attached and there is no
7015                // need to check whether we reach to ViewRootImpl on the way up.
7016                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7017                        view.getVisibility() != VISIBLE) {
7018                    return false;
7019                }
7020                current = view.mParent;
7021            }
7022            // Check if the view is entirely covered by its predecessors.
7023            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7024            Point offset = mAttachInfo.mPoint;
7025            if (!getGlobalVisibleRect(visibleRect, offset)) {
7026                return false;
7027            }
7028            // Check if the visible portion intersects the rectangle of interest.
7029            if (boundInView != null) {
7030                visibleRect.offset(-offset.x, -offset.y);
7031                return boundInView.intersect(visibleRect);
7032            }
7033            return true;
7034        }
7035        return false;
7036    }
7037
7038    /**
7039     * Returns the delegate for implementing accessibility support via
7040     * composition. For more details see {@link AccessibilityDelegate}.
7041     *
7042     * @return The delegate, or null if none set.
7043     *
7044     * @hide
7045     */
7046    public AccessibilityDelegate getAccessibilityDelegate() {
7047        return mAccessibilityDelegate;
7048    }
7049
7050    /**
7051     * Sets a delegate for implementing accessibility support via composition
7052     * (as opposed to inheritance). For more details, see
7053     * {@link AccessibilityDelegate}.
7054     * <p>
7055     * <strong>Note:</strong> On platform versions prior to
7056     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7057     * views in the {@code android.widget.*} package are called <i>before</i>
7058     * host methods. This prevents certain properties such as class name from
7059     * being modified by overriding
7060     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7061     * as any changes will be overwritten by the host class.
7062     * <p>
7063     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7064     * methods are called <i>after</i> host methods, which all properties to be
7065     * modified without being overwritten by the host class.
7066     *
7067     * @param delegate the object to which accessibility method calls should be
7068     *                 delegated
7069     * @see AccessibilityDelegate
7070     */
7071    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7072        mAccessibilityDelegate = delegate;
7073    }
7074
7075    /**
7076     * Gets the provider for managing a virtual view hierarchy rooted at this View
7077     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7078     * that explore the window content.
7079     * <p>
7080     * If this method returns an instance, this instance is responsible for managing
7081     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7082     * View including the one representing the View itself. Similarly the returned
7083     * instance is responsible for performing accessibility actions on any virtual
7084     * view or the root view itself.
7085     * </p>
7086     * <p>
7087     * If an {@link AccessibilityDelegate} has been specified via calling
7088     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7089     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7090     * is responsible for handling this call.
7091     * </p>
7092     *
7093     * @return The provider.
7094     *
7095     * @see AccessibilityNodeProvider
7096     */
7097    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7098        if (mAccessibilityDelegate != null) {
7099            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7100        } else {
7101            return null;
7102        }
7103    }
7104
7105    /**
7106     * Gets the unique identifier of this view on the screen for accessibility purposes.
7107     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
7108     *
7109     * @return The view accessibility id.
7110     *
7111     * @hide
7112     */
7113    public int getAccessibilityViewId() {
7114        if (mAccessibilityViewId == NO_ID) {
7115            mAccessibilityViewId = sNextAccessibilityViewId++;
7116        }
7117        return mAccessibilityViewId;
7118    }
7119
7120    /**
7121     * Gets the unique identifier of the window in which this View reseides.
7122     *
7123     * @return The window accessibility id.
7124     *
7125     * @hide
7126     */
7127    public int getAccessibilityWindowId() {
7128        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7129                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7130    }
7131
7132    /**
7133     * Returns the {@link View}'s content description.
7134     * <p>
7135     * <strong>Note:</strong> Do not override this method, as it will have no
7136     * effect on the content description presented to accessibility services.
7137     * You must call {@link #setContentDescription(CharSequence)} to modify the
7138     * content description.
7139     *
7140     * @return the content description
7141     * @see #setContentDescription(CharSequence)
7142     * @attr ref android.R.styleable#View_contentDescription
7143     */
7144    @ViewDebug.ExportedProperty(category = "accessibility")
7145    public CharSequence getContentDescription() {
7146        return mContentDescription;
7147    }
7148
7149    /**
7150     * Sets the {@link View}'s content description.
7151     * <p>
7152     * A content description briefly describes the view and is primarily used
7153     * for accessibility support to determine how a view should be presented to
7154     * the user. In the case of a view with no textual representation, such as
7155     * {@link android.widget.ImageButton}, a useful content description
7156     * explains what the view does. For example, an image button with a phone
7157     * icon that is used to place a call may use "Call" as its content
7158     * description. An image of a floppy disk that is used to save a file may
7159     * use "Save".
7160     *
7161     * @param contentDescription The content description.
7162     * @see #getContentDescription()
7163     * @attr ref android.R.styleable#View_contentDescription
7164     */
7165    @RemotableViewMethod
7166    public void setContentDescription(CharSequence contentDescription) {
7167        if (mContentDescription == null) {
7168            if (contentDescription == null) {
7169                return;
7170            }
7171        } else if (mContentDescription.equals(contentDescription)) {
7172            return;
7173        }
7174        mContentDescription = contentDescription;
7175        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7176        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7177            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7178            notifySubtreeAccessibilityStateChangedIfNeeded();
7179        } else {
7180            notifyViewAccessibilityStateChangedIfNeeded(
7181                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7182        }
7183    }
7184
7185    /**
7186     * Sets the id of a view before which this one is visited in accessibility traversal.
7187     * A screen-reader must visit the content of this view before the content of the one
7188     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7189     * will traverse the entire content of B before traversing the entire content of A,
7190     * regardles of what traversal strategy it is using.
7191     * <p>
7192     * Views that do not have specified before/after relationships are traversed in order
7193     * determined by the screen-reader.
7194     * </p>
7195     * <p>
7196     * Setting that this view is before a view that is not important for accessibility
7197     * or if this view is not important for accessibility will have no effect as the
7198     * screen-reader is not aware of unimportant views.
7199     * </p>
7200     *
7201     * @param beforeId The id of a view this one precedes in accessibility traversal.
7202     *
7203     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7204     *
7205     * @see #setImportantForAccessibility(int)
7206     */
7207    @RemotableViewMethod
7208    public void setAccessibilityTraversalBefore(int beforeId) {
7209        if (mAccessibilityTraversalBeforeId == beforeId) {
7210            return;
7211        }
7212        mAccessibilityTraversalBeforeId = beforeId;
7213        notifyViewAccessibilityStateChangedIfNeeded(
7214                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7215    }
7216
7217    /**
7218     * Gets the id of a view before which this one is visited in accessibility traversal.
7219     *
7220     * @return The id of a view this one precedes in accessibility traversal if
7221     *         specified, otherwise {@link #NO_ID}.
7222     *
7223     * @see #setAccessibilityTraversalBefore(int)
7224     */
7225    public int getAccessibilityTraversalBefore() {
7226        return mAccessibilityTraversalBeforeId;
7227    }
7228
7229    /**
7230     * Sets the id of a view after which this one is visited in accessibility traversal.
7231     * A screen-reader must visit the content of the other view before the content of this
7232     * one. For example, if view B is set to be after view A, then a screen-reader
7233     * will traverse the entire content of A before traversing the entire content of B,
7234     * regardles of what traversal strategy it is using.
7235     * <p>
7236     * Views that do not have specified before/after relationships are traversed in order
7237     * determined by the screen-reader.
7238     * </p>
7239     * <p>
7240     * Setting that this view is after a view that is not important for accessibility
7241     * or if this view is not important for accessibility will have no effect as the
7242     * screen-reader is not aware of unimportant views.
7243     * </p>
7244     *
7245     * @param afterId The id of a view this one succedees in accessibility traversal.
7246     *
7247     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7248     *
7249     * @see #setImportantForAccessibility(int)
7250     */
7251    @RemotableViewMethod
7252    public void setAccessibilityTraversalAfter(int afterId) {
7253        if (mAccessibilityTraversalAfterId == afterId) {
7254            return;
7255        }
7256        mAccessibilityTraversalAfterId = afterId;
7257        notifyViewAccessibilityStateChangedIfNeeded(
7258                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7259    }
7260
7261    /**
7262     * Gets the id of a view after which this one is visited in accessibility traversal.
7263     *
7264     * @return The id of a view this one succeedes in accessibility traversal if
7265     *         specified, otherwise {@link #NO_ID}.
7266     *
7267     * @see #setAccessibilityTraversalAfter(int)
7268     */
7269    public int getAccessibilityTraversalAfter() {
7270        return mAccessibilityTraversalAfterId;
7271    }
7272
7273    /**
7274     * Gets the id of a view for which this view serves as a label for
7275     * accessibility purposes.
7276     *
7277     * @return The labeled view id.
7278     */
7279    @ViewDebug.ExportedProperty(category = "accessibility")
7280    public int getLabelFor() {
7281        return mLabelForId;
7282    }
7283
7284    /**
7285     * Sets the id of a view for which this view serves as a label for
7286     * accessibility purposes.
7287     *
7288     * @param id The labeled view id.
7289     */
7290    @RemotableViewMethod
7291    public void setLabelFor(@IdRes int id) {
7292        if (mLabelForId == id) {
7293            return;
7294        }
7295        mLabelForId = id;
7296        if (mLabelForId != View.NO_ID
7297                && mID == View.NO_ID) {
7298            mID = generateViewId();
7299        }
7300        notifyViewAccessibilityStateChangedIfNeeded(
7301                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7302    }
7303
7304    /**
7305     * Invoked whenever this view loses focus, either by losing window focus or by losing
7306     * focus within its window. This method can be used to clear any state tied to the
7307     * focus. For instance, if a button is held pressed with the trackball and the window
7308     * loses focus, this method can be used to cancel the press.
7309     *
7310     * Subclasses of View overriding this method should always call super.onFocusLost().
7311     *
7312     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7313     * @see #onWindowFocusChanged(boolean)
7314     *
7315     * @hide pending API council approval
7316     */
7317    @CallSuper
7318    protected void onFocusLost() {
7319        resetPressedState();
7320    }
7321
7322    private void resetPressedState() {
7323        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7324            return;
7325        }
7326
7327        if (isPressed()) {
7328            setPressed(false);
7329
7330            if (!mHasPerformedLongPress) {
7331                removeLongPressCallback();
7332            }
7333        }
7334    }
7335
7336    /**
7337     * Returns true if this view has focus
7338     *
7339     * @return True if this view has focus, false otherwise.
7340     */
7341    @ViewDebug.ExportedProperty(category = "focus")
7342    public boolean isFocused() {
7343        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7344    }
7345
7346    /**
7347     * Find the view in the hierarchy rooted at this view that currently has
7348     * focus.
7349     *
7350     * @return The view that currently has focus, or null if no focused view can
7351     *         be found.
7352     */
7353    public View findFocus() {
7354        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7355    }
7356
7357    /**
7358     * Indicates whether this view is one of the set of scrollable containers in
7359     * its window.
7360     *
7361     * @return whether this view is one of the set of scrollable containers in
7362     * its window
7363     *
7364     * @attr ref android.R.styleable#View_isScrollContainer
7365     */
7366    public boolean isScrollContainer() {
7367        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7368    }
7369
7370    /**
7371     * Change whether this view is one of the set of scrollable containers in
7372     * its window.  This will be used to determine whether the window can
7373     * resize or must pan when a soft input area is open -- scrollable
7374     * containers allow the window to use resize mode since the container
7375     * will appropriately shrink.
7376     *
7377     * @attr ref android.R.styleable#View_isScrollContainer
7378     */
7379    public void setScrollContainer(boolean isScrollContainer) {
7380        if (isScrollContainer) {
7381            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7382                mAttachInfo.mScrollContainers.add(this);
7383                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7384            }
7385            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7386        } else {
7387            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7388                mAttachInfo.mScrollContainers.remove(this);
7389            }
7390            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7391        }
7392    }
7393
7394    /**
7395     * Returns the quality of the drawing cache.
7396     *
7397     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7398     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7399     *
7400     * @see #setDrawingCacheQuality(int)
7401     * @see #setDrawingCacheEnabled(boolean)
7402     * @see #isDrawingCacheEnabled()
7403     *
7404     * @attr ref android.R.styleable#View_drawingCacheQuality
7405     */
7406    @DrawingCacheQuality
7407    public int getDrawingCacheQuality() {
7408        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7409    }
7410
7411    /**
7412     * Set the drawing cache quality of this view. This value is used only when the
7413     * drawing cache is enabled
7414     *
7415     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7416     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7417     *
7418     * @see #getDrawingCacheQuality()
7419     * @see #setDrawingCacheEnabled(boolean)
7420     * @see #isDrawingCacheEnabled()
7421     *
7422     * @attr ref android.R.styleable#View_drawingCacheQuality
7423     */
7424    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7425        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7426    }
7427
7428    /**
7429     * Returns whether the screen should remain on, corresponding to the current
7430     * value of {@link #KEEP_SCREEN_ON}.
7431     *
7432     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7433     *
7434     * @see #setKeepScreenOn(boolean)
7435     *
7436     * @attr ref android.R.styleable#View_keepScreenOn
7437     */
7438    public boolean getKeepScreenOn() {
7439        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7440    }
7441
7442    /**
7443     * Controls whether the screen should remain on, modifying the
7444     * value of {@link #KEEP_SCREEN_ON}.
7445     *
7446     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7447     *
7448     * @see #getKeepScreenOn()
7449     *
7450     * @attr ref android.R.styleable#View_keepScreenOn
7451     */
7452    public void setKeepScreenOn(boolean keepScreenOn) {
7453        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7454    }
7455
7456    /**
7457     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7458     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7459     *
7460     * @attr ref android.R.styleable#View_nextFocusLeft
7461     */
7462    public int getNextFocusLeftId() {
7463        return mNextFocusLeftId;
7464    }
7465
7466    /**
7467     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7468     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7469     * decide automatically.
7470     *
7471     * @attr ref android.R.styleable#View_nextFocusLeft
7472     */
7473    public void setNextFocusLeftId(int nextFocusLeftId) {
7474        mNextFocusLeftId = nextFocusLeftId;
7475    }
7476
7477    /**
7478     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7479     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7480     *
7481     * @attr ref android.R.styleable#View_nextFocusRight
7482     */
7483    public int getNextFocusRightId() {
7484        return mNextFocusRightId;
7485    }
7486
7487    /**
7488     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7489     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7490     * decide automatically.
7491     *
7492     * @attr ref android.R.styleable#View_nextFocusRight
7493     */
7494    public void setNextFocusRightId(int nextFocusRightId) {
7495        mNextFocusRightId = nextFocusRightId;
7496    }
7497
7498    /**
7499     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7500     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7501     *
7502     * @attr ref android.R.styleable#View_nextFocusUp
7503     */
7504    public int getNextFocusUpId() {
7505        return mNextFocusUpId;
7506    }
7507
7508    /**
7509     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7510     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7511     * decide automatically.
7512     *
7513     * @attr ref android.R.styleable#View_nextFocusUp
7514     */
7515    public void setNextFocusUpId(int nextFocusUpId) {
7516        mNextFocusUpId = nextFocusUpId;
7517    }
7518
7519    /**
7520     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7521     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7522     *
7523     * @attr ref android.R.styleable#View_nextFocusDown
7524     */
7525    public int getNextFocusDownId() {
7526        return mNextFocusDownId;
7527    }
7528
7529    /**
7530     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7531     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7532     * decide automatically.
7533     *
7534     * @attr ref android.R.styleable#View_nextFocusDown
7535     */
7536    public void setNextFocusDownId(int nextFocusDownId) {
7537        mNextFocusDownId = nextFocusDownId;
7538    }
7539
7540    /**
7541     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7542     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7543     *
7544     * @attr ref android.R.styleable#View_nextFocusForward
7545     */
7546    public int getNextFocusForwardId() {
7547        return mNextFocusForwardId;
7548    }
7549
7550    /**
7551     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7552     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7553     * decide automatically.
7554     *
7555     * @attr ref android.R.styleable#View_nextFocusForward
7556     */
7557    public void setNextFocusForwardId(int nextFocusForwardId) {
7558        mNextFocusForwardId = nextFocusForwardId;
7559    }
7560
7561    /**
7562     * Returns the visibility of this view and all of its ancestors
7563     *
7564     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7565     */
7566    public boolean isShown() {
7567        View current = this;
7568        //noinspection ConstantConditions
7569        do {
7570            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7571                return false;
7572            }
7573            ViewParent parent = current.mParent;
7574            if (parent == null) {
7575                return false; // We are not attached to the view root
7576            }
7577            if (!(parent instanceof View)) {
7578                return true;
7579            }
7580            current = (View) parent;
7581        } while (current != null);
7582
7583        return false;
7584    }
7585
7586    /**
7587     * Called by the view hierarchy when the content insets for a window have
7588     * changed, to allow it to adjust its content to fit within those windows.
7589     * The content insets tell you the space that the status bar, input method,
7590     * and other system windows infringe on the application's window.
7591     *
7592     * <p>You do not normally need to deal with this function, since the default
7593     * window decoration given to applications takes care of applying it to the
7594     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7595     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7596     * and your content can be placed under those system elements.  You can then
7597     * use this method within your view hierarchy if you have parts of your UI
7598     * which you would like to ensure are not being covered.
7599     *
7600     * <p>The default implementation of this method simply applies the content
7601     * insets to the view's padding, consuming that content (modifying the
7602     * insets to be 0), and returning true.  This behavior is off by default, but can
7603     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7604     *
7605     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7606     * insets object is propagated down the hierarchy, so any changes made to it will
7607     * be seen by all following views (including potentially ones above in
7608     * the hierarchy since this is a depth-first traversal).  The first view
7609     * that returns true will abort the entire traversal.
7610     *
7611     * <p>The default implementation works well for a situation where it is
7612     * used with a container that covers the entire window, allowing it to
7613     * apply the appropriate insets to its content on all edges.  If you need
7614     * a more complicated layout (such as two different views fitting system
7615     * windows, one on the top of the window, and one on the bottom),
7616     * you can override the method and handle the insets however you would like.
7617     * Note that the insets provided by the framework are always relative to the
7618     * far edges of the window, not accounting for the location of the called view
7619     * within that window.  (In fact when this method is called you do not yet know
7620     * where the layout will place the view, as it is done before layout happens.)
7621     *
7622     * <p>Note: unlike many View methods, there is no dispatch phase to this
7623     * call.  If you are overriding it in a ViewGroup and want to allow the
7624     * call to continue to your children, you must be sure to call the super
7625     * implementation.
7626     *
7627     * <p>Here is a sample layout that makes use of fitting system windows
7628     * to have controls for a video view placed inside of the window decorations
7629     * that it hides and shows.  This can be used with code like the second
7630     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7631     *
7632     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7633     *
7634     * @param insets Current content insets of the window.  Prior to
7635     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7636     * the insets or else you and Android will be unhappy.
7637     *
7638     * @return {@code true} if this view applied the insets and it should not
7639     * continue propagating further down the hierarchy, {@code false} otherwise.
7640     * @see #getFitsSystemWindows()
7641     * @see #setFitsSystemWindows(boolean)
7642     * @see #setSystemUiVisibility(int)
7643     *
7644     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7645     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7646     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7647     * to implement handling their own insets.
7648     */
7649    protected boolean fitSystemWindows(Rect insets) {
7650        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7651            if (insets == null) {
7652                // Null insets by definition have already been consumed.
7653                // This call cannot apply insets since there are none to apply,
7654                // so return false.
7655                return false;
7656            }
7657            // If we're not in the process of dispatching the newer apply insets call,
7658            // that means we're not in the compatibility path. Dispatch into the newer
7659            // apply insets path and take things from there.
7660            try {
7661                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7662                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7663            } finally {
7664                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7665            }
7666        } else {
7667            // We're being called from the newer apply insets path.
7668            // Perform the standard fallback behavior.
7669            return fitSystemWindowsInt(insets);
7670        }
7671    }
7672
7673    private boolean fitSystemWindowsInt(Rect insets) {
7674        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7675            mUserPaddingStart = UNDEFINED_PADDING;
7676            mUserPaddingEnd = UNDEFINED_PADDING;
7677            Rect localInsets = sThreadLocal.get();
7678            if (localInsets == null) {
7679                localInsets = new Rect();
7680                sThreadLocal.set(localInsets);
7681            }
7682            boolean res = computeFitSystemWindows(insets, localInsets);
7683            mUserPaddingLeftInitial = localInsets.left;
7684            mUserPaddingRightInitial = localInsets.right;
7685            internalSetPadding(localInsets.left, localInsets.top,
7686                    localInsets.right, localInsets.bottom);
7687            return res;
7688        }
7689        return false;
7690    }
7691
7692    /**
7693     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7694     *
7695     * <p>This method should be overridden by views that wish to apply a policy different from or
7696     * in addition to the default behavior. Clients that wish to force a view subtree
7697     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7698     *
7699     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7700     * it will be called during dispatch instead of this method. The listener may optionally
7701     * call this method from its own implementation if it wishes to apply the view's default
7702     * insets policy in addition to its own.</p>
7703     *
7704     * <p>Implementations of this method should either return the insets parameter unchanged
7705     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7706     * that this view applied itself. This allows new inset types added in future platform
7707     * versions to pass through existing implementations unchanged without being erroneously
7708     * consumed.</p>
7709     *
7710     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7711     * property is set then the view will consume the system window insets and apply them
7712     * as padding for the view.</p>
7713     *
7714     * @param insets Insets to apply
7715     * @return The supplied insets with any applied insets consumed
7716     */
7717    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7718        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7719            // We weren't called from within a direct call to fitSystemWindows,
7720            // call into it as a fallback in case we're in a class that overrides it
7721            // and has logic to perform.
7722            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7723                return insets.consumeSystemWindowInsets();
7724            }
7725        } else {
7726            // We were called from within a direct call to fitSystemWindows.
7727            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7728                return insets.consumeSystemWindowInsets();
7729            }
7730        }
7731        return insets;
7732    }
7733
7734    /**
7735     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7736     * window insets to this view. The listener's
7737     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7738     * method will be called instead of the view's
7739     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7740     *
7741     * @param listener Listener to set
7742     *
7743     * @see #onApplyWindowInsets(WindowInsets)
7744     */
7745    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7746        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7747    }
7748
7749    /**
7750     * Request to apply the given window insets to this view or another view in its subtree.
7751     *
7752     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7753     * obscured by window decorations or overlays. This can include the status and navigation bars,
7754     * action bars, input methods and more. New inset categories may be added in the future.
7755     * The method returns the insets provided minus any that were applied by this view or its
7756     * children.</p>
7757     *
7758     * <p>Clients wishing to provide custom behavior should override the
7759     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7760     * {@link OnApplyWindowInsetsListener} via the
7761     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7762     * method.</p>
7763     *
7764     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7765     * </p>
7766     *
7767     * @param insets Insets to apply
7768     * @return The provided insets minus the insets that were consumed
7769     */
7770    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7771        try {
7772            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7773            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7774                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7775            } else {
7776                return onApplyWindowInsets(insets);
7777            }
7778        } finally {
7779            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7780        }
7781    }
7782
7783    /**
7784     * Compute the view's coordinate within the surface.
7785     *
7786     * <p>Computes the coordinates of this view in its surface. The argument
7787     * must be an array of two integers. After the method returns, the array
7788     * contains the x and y location in that order.</p>
7789     * @hide
7790     * @param location an array of two integers in which to hold the coordinates
7791     */
7792    public void getLocationInSurface(@Size(2) int[] location) {
7793        getLocationInWindow(location);
7794        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
7795            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
7796            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
7797        }
7798    }
7799
7800    /**
7801     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7802     * only available if the view is attached.
7803     *
7804     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7805     */
7806    public WindowInsets getRootWindowInsets() {
7807        if (mAttachInfo != null) {
7808            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7809        }
7810        return null;
7811    }
7812
7813    /**
7814     * @hide Compute the insets that should be consumed by this view and the ones
7815     * that should propagate to those under it.
7816     */
7817    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7818        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7819                || mAttachInfo == null
7820                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7821                        && !mAttachInfo.mOverscanRequested)) {
7822            outLocalInsets.set(inoutInsets);
7823            inoutInsets.set(0, 0, 0, 0);
7824            return true;
7825        } else {
7826            // The application wants to take care of fitting system window for
7827            // the content...  however we still need to take care of any overscan here.
7828            final Rect overscan = mAttachInfo.mOverscanInsets;
7829            outLocalInsets.set(overscan);
7830            inoutInsets.left -= overscan.left;
7831            inoutInsets.top -= overscan.top;
7832            inoutInsets.right -= overscan.right;
7833            inoutInsets.bottom -= overscan.bottom;
7834            return false;
7835        }
7836    }
7837
7838    /**
7839     * Compute insets that should be consumed by this view and the ones that should propagate
7840     * to those under it.
7841     *
7842     * @param in Insets currently being processed by this View, likely received as a parameter
7843     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7844     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7845     *                       by this view
7846     * @return Insets that should be passed along to views under this one
7847     */
7848    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7849        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7850                || mAttachInfo == null
7851                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7852            outLocalInsets.set(in.getSystemWindowInsets());
7853            return in.consumeSystemWindowInsets();
7854        } else {
7855            outLocalInsets.set(0, 0, 0, 0);
7856            return in;
7857        }
7858    }
7859
7860    /**
7861     * Sets whether or not this view should account for system screen decorations
7862     * such as the status bar and inset its content; that is, controlling whether
7863     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7864     * executed.  See that method for more details.
7865     *
7866     * <p>Note that if you are providing your own implementation of
7867     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7868     * flag to true -- your implementation will be overriding the default
7869     * implementation that checks this flag.
7870     *
7871     * @param fitSystemWindows If true, then the default implementation of
7872     * {@link #fitSystemWindows(Rect)} will be executed.
7873     *
7874     * @attr ref android.R.styleable#View_fitsSystemWindows
7875     * @see #getFitsSystemWindows()
7876     * @see #fitSystemWindows(Rect)
7877     * @see #setSystemUiVisibility(int)
7878     */
7879    public void setFitsSystemWindows(boolean fitSystemWindows) {
7880        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7881    }
7882
7883    /**
7884     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7885     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7886     * will be executed.
7887     *
7888     * @return {@code true} if the default implementation of
7889     * {@link #fitSystemWindows(Rect)} will be executed.
7890     *
7891     * @attr ref android.R.styleable#View_fitsSystemWindows
7892     * @see #setFitsSystemWindows(boolean)
7893     * @see #fitSystemWindows(Rect)
7894     * @see #setSystemUiVisibility(int)
7895     */
7896    @ViewDebug.ExportedProperty
7897    public boolean getFitsSystemWindows() {
7898        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
7899    }
7900
7901    /** @hide */
7902    public boolean fitsSystemWindows() {
7903        return getFitsSystemWindows();
7904    }
7905
7906    /**
7907     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
7908     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
7909     */
7910    public void requestFitSystemWindows() {
7911        if (mParent != null) {
7912            mParent.requestFitSystemWindows();
7913        }
7914    }
7915
7916    /**
7917     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
7918     */
7919    public void requestApplyInsets() {
7920        requestFitSystemWindows();
7921    }
7922
7923    /**
7924     * For use by PhoneWindow to make its own system window fitting optional.
7925     * @hide
7926     */
7927    public void makeOptionalFitsSystemWindows() {
7928        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
7929    }
7930
7931    /**
7932     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
7933     * treat them as such.
7934     * @hide
7935     */
7936    public void getOutsets(Rect outOutsetRect) {
7937        if (mAttachInfo != null) {
7938            outOutsetRect.set(mAttachInfo.mOutsets);
7939        } else {
7940            outOutsetRect.setEmpty();
7941        }
7942    }
7943
7944    /**
7945     * Returns the visibility status for this view.
7946     *
7947     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7948     * @attr ref android.R.styleable#View_visibility
7949     */
7950    @ViewDebug.ExportedProperty(mapping = {
7951        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
7952        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
7953        @ViewDebug.IntToString(from = GONE,      to = "GONE")
7954    })
7955    @Visibility
7956    public int getVisibility() {
7957        return mViewFlags & VISIBILITY_MASK;
7958    }
7959
7960    /**
7961     * Set the enabled state of this view.
7962     *
7963     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7964     * @attr ref android.R.styleable#View_visibility
7965     */
7966    @RemotableViewMethod
7967    public void setVisibility(@Visibility int visibility) {
7968        setFlags(visibility, VISIBILITY_MASK);
7969    }
7970
7971    /**
7972     * Returns the enabled status for this view. The interpretation of the
7973     * enabled state varies by subclass.
7974     *
7975     * @return True if this view is enabled, false otherwise.
7976     */
7977    @ViewDebug.ExportedProperty
7978    public boolean isEnabled() {
7979        return (mViewFlags & ENABLED_MASK) == ENABLED;
7980    }
7981
7982    /**
7983     * Set the enabled state of this view. The interpretation of the enabled
7984     * state varies by subclass.
7985     *
7986     * @param enabled True if this view is enabled, false otherwise.
7987     */
7988    @RemotableViewMethod
7989    public void setEnabled(boolean enabled) {
7990        if (enabled == isEnabled()) return;
7991
7992        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
7993
7994        /*
7995         * The View most likely has to change its appearance, so refresh
7996         * the drawable state.
7997         */
7998        refreshDrawableState();
7999
8000        // Invalidate too, since the default behavior for views is to be
8001        // be drawn at 50% alpha rather than to change the drawable.
8002        invalidate(true);
8003
8004        if (!enabled) {
8005            cancelPendingInputEvents();
8006        }
8007    }
8008
8009    /**
8010     * Set whether this view can receive the focus.
8011     *
8012     * Setting this to false will also ensure that this view is not focusable
8013     * in touch mode.
8014     *
8015     * @param focusable If true, this view can receive the focus.
8016     *
8017     * @see #setFocusableInTouchMode(boolean)
8018     * @attr ref android.R.styleable#View_focusable
8019     */
8020    public void setFocusable(boolean focusable) {
8021        if (!focusable) {
8022            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8023        }
8024        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8025    }
8026
8027    /**
8028     * Set whether this view can receive focus while in touch mode.
8029     *
8030     * Setting this to true will also ensure that this view is focusable.
8031     *
8032     * @param focusableInTouchMode If true, this view can receive the focus while
8033     *   in touch mode.
8034     *
8035     * @see #setFocusable(boolean)
8036     * @attr ref android.R.styleable#View_focusableInTouchMode
8037     */
8038    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8039        // Focusable in touch mode should always be set before the focusable flag
8040        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8041        // which, in touch mode, will not successfully request focus on this view
8042        // because the focusable in touch mode flag is not set
8043        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8044        if (focusableInTouchMode) {
8045            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8046        }
8047    }
8048
8049    /**
8050     * Set whether this view should have sound effects enabled for events such as
8051     * clicking and touching.
8052     *
8053     * <p>You may wish to disable sound effects for a view if you already play sounds,
8054     * for instance, a dial key that plays dtmf tones.
8055     *
8056     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8057     * @see #isSoundEffectsEnabled()
8058     * @see #playSoundEffect(int)
8059     * @attr ref android.R.styleable#View_soundEffectsEnabled
8060     */
8061    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8062        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8063    }
8064
8065    /**
8066     * @return whether this view should have sound effects enabled for events such as
8067     *     clicking and touching.
8068     *
8069     * @see #setSoundEffectsEnabled(boolean)
8070     * @see #playSoundEffect(int)
8071     * @attr ref android.R.styleable#View_soundEffectsEnabled
8072     */
8073    @ViewDebug.ExportedProperty
8074    public boolean isSoundEffectsEnabled() {
8075        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8076    }
8077
8078    /**
8079     * Set whether this view should have haptic feedback for events such as
8080     * long presses.
8081     *
8082     * <p>You may wish to disable haptic feedback if your view already controls
8083     * its own haptic feedback.
8084     *
8085     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8086     * @see #isHapticFeedbackEnabled()
8087     * @see #performHapticFeedback(int)
8088     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8089     */
8090    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8091        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8092    }
8093
8094    /**
8095     * @return whether this view should have haptic feedback enabled for events
8096     * long presses.
8097     *
8098     * @see #setHapticFeedbackEnabled(boolean)
8099     * @see #performHapticFeedback(int)
8100     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8101     */
8102    @ViewDebug.ExportedProperty
8103    public boolean isHapticFeedbackEnabled() {
8104        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8105    }
8106
8107    /**
8108     * Returns the layout direction for this view.
8109     *
8110     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8111     *   {@link #LAYOUT_DIRECTION_RTL},
8112     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8113     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8114     *
8115     * @attr ref android.R.styleable#View_layoutDirection
8116     *
8117     * @hide
8118     */
8119    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8120        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8121        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8122        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8123        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8124    })
8125    @LayoutDir
8126    public int getRawLayoutDirection() {
8127        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8128    }
8129
8130    /**
8131     * Set the layout direction for this view. This will propagate a reset of layout direction
8132     * resolution to the view's children and resolve layout direction for this view.
8133     *
8134     * @param layoutDirection the layout direction to set. Should be one of:
8135     *
8136     * {@link #LAYOUT_DIRECTION_LTR},
8137     * {@link #LAYOUT_DIRECTION_RTL},
8138     * {@link #LAYOUT_DIRECTION_INHERIT},
8139     * {@link #LAYOUT_DIRECTION_LOCALE}.
8140     *
8141     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8142     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8143     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8144     *
8145     * @attr ref android.R.styleable#View_layoutDirection
8146     */
8147    @RemotableViewMethod
8148    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8149        if (getRawLayoutDirection() != layoutDirection) {
8150            // Reset the current layout direction and the resolved one
8151            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8152            resetRtlProperties();
8153            // Set the new layout direction (filtered)
8154            mPrivateFlags2 |=
8155                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8156            // We need to resolve all RTL properties as they all depend on layout direction
8157            resolveRtlPropertiesIfNeeded();
8158            requestLayout();
8159            invalidate(true);
8160        }
8161    }
8162
8163    /**
8164     * Returns the resolved layout direction for this view.
8165     *
8166     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8167     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8168     *
8169     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8170     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8171     *
8172     * @attr ref android.R.styleable#View_layoutDirection
8173     */
8174    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8175        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8176        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8177    })
8178    @ResolvedLayoutDir
8179    public int getLayoutDirection() {
8180        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8181        if (targetSdkVersion < JELLY_BEAN_MR1) {
8182            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8183            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8184        }
8185        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8186                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8187    }
8188
8189    /**
8190     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8191     * layout attribute and/or the inherited value from the parent
8192     *
8193     * @return true if the layout is right-to-left.
8194     *
8195     * @hide
8196     */
8197    @ViewDebug.ExportedProperty(category = "layout")
8198    public boolean isLayoutRtl() {
8199        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8200    }
8201
8202    /**
8203     * Indicates whether the view is currently tracking transient state that the
8204     * app should not need to concern itself with saving and restoring, but that
8205     * the framework should take special note to preserve when possible.
8206     *
8207     * <p>A view with transient state cannot be trivially rebound from an external
8208     * data source, such as an adapter binding item views in a list. This may be
8209     * because the view is performing an animation, tracking user selection
8210     * of content, or similar.</p>
8211     *
8212     * @return true if the view has transient state
8213     */
8214    @ViewDebug.ExportedProperty(category = "layout")
8215    public boolean hasTransientState() {
8216        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8217    }
8218
8219    /**
8220     * Set whether this view is currently tracking transient state that the
8221     * framework should attempt to preserve when possible. This flag is reference counted,
8222     * so every call to setHasTransientState(true) should be paired with a later call
8223     * to setHasTransientState(false).
8224     *
8225     * <p>A view with transient state cannot be trivially rebound from an external
8226     * data source, such as an adapter binding item views in a list. This may be
8227     * because the view is performing an animation, tracking user selection
8228     * of content, or similar.</p>
8229     *
8230     * @param hasTransientState true if this view has transient state
8231     */
8232    public void setHasTransientState(boolean hasTransientState) {
8233        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8234                mTransientStateCount - 1;
8235        if (mTransientStateCount < 0) {
8236            mTransientStateCount = 0;
8237            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8238                    "unmatched pair of setHasTransientState calls");
8239        } else if ((hasTransientState && mTransientStateCount == 1) ||
8240                (!hasTransientState && mTransientStateCount == 0)) {
8241            // update flag if we've just incremented up from 0 or decremented down to 0
8242            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8243                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8244            if (mParent != null) {
8245                try {
8246                    mParent.childHasTransientStateChanged(this, hasTransientState);
8247                } catch (AbstractMethodError e) {
8248                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8249                            " does not fully implement ViewParent", e);
8250                }
8251            }
8252        }
8253    }
8254
8255    /**
8256     * Returns true if this view is currently attached to a window.
8257     */
8258    public boolean isAttachedToWindow() {
8259        return mAttachInfo != null;
8260    }
8261
8262    /**
8263     * Returns true if this view has been through at least one layout since it
8264     * was last attached to or detached from a window.
8265     */
8266    public boolean isLaidOut() {
8267        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8268    }
8269
8270    /**
8271     * If this view doesn't do any drawing on its own, set this flag to
8272     * allow further optimizations. By default, this flag is not set on
8273     * View, but could be set on some View subclasses such as ViewGroup.
8274     *
8275     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8276     * you should clear this flag.
8277     *
8278     * @param willNotDraw whether or not this View draw on its own
8279     */
8280    public void setWillNotDraw(boolean willNotDraw) {
8281        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8282    }
8283
8284    /**
8285     * Returns whether or not this View draws on its own.
8286     *
8287     * @return true if this view has nothing to draw, false otherwise
8288     */
8289    @ViewDebug.ExportedProperty(category = "drawing")
8290    public boolean willNotDraw() {
8291        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8292    }
8293
8294    /**
8295     * When a View's drawing cache is enabled, drawing is redirected to an
8296     * offscreen bitmap. Some views, like an ImageView, must be able to
8297     * bypass this mechanism if they already draw a single bitmap, to avoid
8298     * unnecessary usage of the memory.
8299     *
8300     * @param willNotCacheDrawing true if this view does not cache its
8301     *        drawing, false otherwise
8302     */
8303    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8304        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8305    }
8306
8307    /**
8308     * Returns whether or not this View can cache its drawing or not.
8309     *
8310     * @return true if this view does not cache its drawing, false otherwise
8311     */
8312    @ViewDebug.ExportedProperty(category = "drawing")
8313    public boolean willNotCacheDrawing() {
8314        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8315    }
8316
8317    /**
8318     * Indicates whether this view reacts to click events or not.
8319     *
8320     * @return true if the view is clickable, false otherwise
8321     *
8322     * @see #setClickable(boolean)
8323     * @attr ref android.R.styleable#View_clickable
8324     */
8325    @ViewDebug.ExportedProperty
8326    public boolean isClickable() {
8327        return (mViewFlags & CLICKABLE) == CLICKABLE;
8328    }
8329
8330    /**
8331     * Enables or disables click events for this view. When a view
8332     * is clickable it will change its state to "pressed" on every click.
8333     * Subclasses should set the view clickable to visually react to
8334     * user's clicks.
8335     *
8336     * @param clickable true to make the view clickable, false otherwise
8337     *
8338     * @see #isClickable()
8339     * @attr ref android.R.styleable#View_clickable
8340     */
8341    public void setClickable(boolean clickable) {
8342        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8343    }
8344
8345    /**
8346     * Indicates whether this view reacts to long click events or not.
8347     *
8348     * @return true if the view is long clickable, false otherwise
8349     *
8350     * @see #setLongClickable(boolean)
8351     * @attr ref android.R.styleable#View_longClickable
8352     */
8353    public boolean isLongClickable() {
8354        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8355    }
8356
8357    /**
8358     * Enables or disables long click events for this view. When a view is long
8359     * clickable it reacts to the user holding down the button for a longer
8360     * duration than a tap. This event can either launch the listener or a
8361     * context menu.
8362     *
8363     * @param longClickable true to make the view long clickable, false otherwise
8364     * @see #isLongClickable()
8365     * @attr ref android.R.styleable#View_longClickable
8366     */
8367    public void setLongClickable(boolean longClickable) {
8368        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8369    }
8370
8371    /**
8372     * Indicates whether this view reacts to context clicks or not.
8373     *
8374     * @return true if the view is context clickable, false otherwise
8375     * @see #setContextClickable(boolean)
8376     * @attr ref android.R.styleable#View_contextClickable
8377     */
8378    public boolean isContextClickable() {
8379        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8380    }
8381
8382    /**
8383     * Enables or disables context clicking for this view. This event can launch the listener.
8384     *
8385     * @param contextClickable true to make the view react to a context click, false otherwise
8386     * @see #isContextClickable()
8387     * @attr ref android.R.styleable#View_contextClickable
8388     */
8389    public void setContextClickable(boolean contextClickable) {
8390        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8391    }
8392
8393    /**
8394     * Sets the pressed state for this view and provides a touch coordinate for
8395     * animation hinting.
8396     *
8397     * @param pressed Pass true to set the View's internal state to "pressed",
8398     *            or false to reverts the View's internal state from a
8399     *            previously set "pressed" state.
8400     * @param x The x coordinate of the touch that caused the press
8401     * @param y The y coordinate of the touch that caused the press
8402     */
8403    private void setPressed(boolean pressed, float x, float y) {
8404        if (pressed) {
8405            drawableHotspotChanged(x, y);
8406        }
8407
8408        setPressed(pressed);
8409    }
8410
8411    /**
8412     * Sets the pressed state for this view.
8413     *
8414     * @see #isClickable()
8415     * @see #setClickable(boolean)
8416     *
8417     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8418     *        the View's internal state from a previously set "pressed" state.
8419     */
8420    public void setPressed(boolean pressed) {
8421        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8422
8423        if (pressed) {
8424            mPrivateFlags |= PFLAG_PRESSED;
8425        } else {
8426            mPrivateFlags &= ~PFLAG_PRESSED;
8427        }
8428
8429        if (needsRefresh) {
8430            refreshDrawableState();
8431        }
8432        dispatchSetPressed(pressed);
8433    }
8434
8435    /**
8436     * Dispatch setPressed to all of this View's children.
8437     *
8438     * @see #setPressed(boolean)
8439     *
8440     * @param pressed The new pressed state
8441     */
8442    protected void dispatchSetPressed(boolean pressed) {
8443    }
8444
8445    /**
8446     * Indicates whether the view is currently in pressed state. Unless
8447     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8448     * the pressed state.
8449     *
8450     * @see #setPressed(boolean)
8451     * @see #isClickable()
8452     * @see #setClickable(boolean)
8453     *
8454     * @return true if the view is currently pressed, false otherwise
8455     */
8456    @ViewDebug.ExportedProperty
8457    public boolean isPressed() {
8458        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8459    }
8460
8461    /**
8462     * @hide
8463     * Indicates whether this view will participate in data collection through
8464     * {@link ViewStructure}.  If true, it will not provide any data
8465     * for itself or its children.  If false, the normal data collection will be allowed.
8466     *
8467     * @return Returns false if assist data collection is not blocked, else true.
8468     *
8469     * @see #setAssistBlocked(boolean)
8470     * @attr ref android.R.styleable#View_assistBlocked
8471     */
8472    public boolean isAssistBlocked() {
8473        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8474    }
8475
8476    /**
8477     * @hide
8478     * Controls whether assist data collection from this view and its children is enabled
8479     * (that is, whether {@link #onProvideStructure} and
8480     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8481     * allowing normal assist collection.  Setting this to false will disable assist collection.
8482     *
8483     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8484     * (the default) to allow it.
8485     *
8486     * @see #isAssistBlocked()
8487     * @see #onProvideStructure
8488     * @see #onProvideVirtualStructure
8489     * @attr ref android.R.styleable#View_assistBlocked
8490     */
8491    public void setAssistBlocked(boolean enabled) {
8492        if (enabled) {
8493            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8494        } else {
8495            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
8496        }
8497    }
8498
8499    /**
8500     * Indicates whether this view will save its state (that is,
8501     * whether its {@link #onSaveInstanceState} method will be called).
8502     *
8503     * @return Returns true if the view state saving is enabled, else false.
8504     *
8505     * @see #setSaveEnabled(boolean)
8506     * @attr ref android.R.styleable#View_saveEnabled
8507     */
8508    public boolean isSaveEnabled() {
8509        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
8510    }
8511
8512    /**
8513     * Controls whether the saving of this view's state is
8514     * enabled (that is, whether its {@link #onSaveInstanceState} method
8515     * will be called).  Note that even if freezing is enabled, the
8516     * view still must have an id assigned to it (via {@link #setId(int)})
8517     * for its state to be saved.  This flag can only disable the
8518     * saving of this view; any child views may still have their state saved.
8519     *
8520     * @param enabled Set to false to <em>disable</em> state saving, or true
8521     * (the default) to allow it.
8522     *
8523     * @see #isSaveEnabled()
8524     * @see #setId(int)
8525     * @see #onSaveInstanceState()
8526     * @attr ref android.R.styleable#View_saveEnabled
8527     */
8528    public void setSaveEnabled(boolean enabled) {
8529        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
8530    }
8531
8532    /**
8533     * Gets whether the framework should discard touches when the view's
8534     * window is obscured by another visible window.
8535     * Refer to the {@link View} security documentation for more details.
8536     *
8537     * @return True if touch filtering is enabled.
8538     *
8539     * @see #setFilterTouchesWhenObscured(boolean)
8540     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8541     */
8542    @ViewDebug.ExportedProperty
8543    public boolean getFilterTouchesWhenObscured() {
8544        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8545    }
8546
8547    /**
8548     * Sets whether the framework should discard touches when the view's
8549     * window is obscured by another visible window.
8550     * Refer to the {@link View} security documentation for more details.
8551     *
8552     * @param enabled True if touch filtering should be enabled.
8553     *
8554     * @see #getFilterTouchesWhenObscured
8555     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8556     */
8557    public void setFilterTouchesWhenObscured(boolean enabled) {
8558        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8559                FILTER_TOUCHES_WHEN_OBSCURED);
8560    }
8561
8562    /**
8563     * Indicates whether the entire hierarchy under this view will save its
8564     * state when a state saving traversal occurs from its parent.  The default
8565     * is true; if false, these views will not be saved unless
8566     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8567     *
8568     * @return Returns true if the view state saving from parent is enabled, else false.
8569     *
8570     * @see #setSaveFromParentEnabled(boolean)
8571     */
8572    public boolean isSaveFromParentEnabled() {
8573        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8574    }
8575
8576    /**
8577     * Controls whether the entire hierarchy under this view will save its
8578     * state when a state saving traversal occurs from its parent.  The default
8579     * is true; if false, these views will not be saved unless
8580     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8581     *
8582     * @param enabled Set to false to <em>disable</em> state saving, or true
8583     * (the default) to allow it.
8584     *
8585     * @see #isSaveFromParentEnabled()
8586     * @see #setId(int)
8587     * @see #onSaveInstanceState()
8588     */
8589    public void setSaveFromParentEnabled(boolean enabled) {
8590        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8591    }
8592
8593
8594    /**
8595     * Returns whether this View is able to take focus.
8596     *
8597     * @return True if this view can take focus, or false otherwise.
8598     * @attr ref android.R.styleable#View_focusable
8599     */
8600    @ViewDebug.ExportedProperty(category = "focus")
8601    public final boolean isFocusable() {
8602        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8603    }
8604
8605    /**
8606     * When a view is focusable, it may not want to take focus when in touch mode.
8607     * For example, a button would like focus when the user is navigating via a D-pad
8608     * so that the user can click on it, but once the user starts touching the screen,
8609     * the button shouldn't take focus
8610     * @return Whether the view is focusable in touch mode.
8611     * @attr ref android.R.styleable#View_focusableInTouchMode
8612     */
8613    @ViewDebug.ExportedProperty
8614    public final boolean isFocusableInTouchMode() {
8615        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8616    }
8617
8618    /**
8619     * Find the nearest view in the specified direction that can take focus.
8620     * This does not actually give focus to that view.
8621     *
8622     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8623     *
8624     * @return The nearest focusable in the specified direction, or null if none
8625     *         can be found.
8626     */
8627    public View focusSearch(@FocusRealDirection int direction) {
8628        if (mParent != null) {
8629            return mParent.focusSearch(this, direction);
8630        } else {
8631            return null;
8632        }
8633    }
8634
8635    /**
8636     * This method is the last chance for the focused view and its ancestors to
8637     * respond to an arrow key. This is called when the focused view did not
8638     * consume the key internally, nor could the view system find a new view in
8639     * the requested direction to give focus to.
8640     *
8641     * @param focused The currently focused view.
8642     * @param direction The direction focus wants to move. One of FOCUS_UP,
8643     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8644     * @return True if the this view consumed this unhandled move.
8645     */
8646    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8647        return false;
8648    }
8649
8650    /**
8651     * If a user manually specified the next view id for a particular direction,
8652     * use the root to look up the view.
8653     * @param root The root view of the hierarchy containing this view.
8654     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8655     * or FOCUS_BACKWARD.
8656     * @return The user specified next view, or null if there is none.
8657     */
8658    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8659        switch (direction) {
8660            case FOCUS_LEFT:
8661                if (mNextFocusLeftId == View.NO_ID) return null;
8662                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8663            case FOCUS_RIGHT:
8664                if (mNextFocusRightId == View.NO_ID) return null;
8665                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8666            case FOCUS_UP:
8667                if (mNextFocusUpId == View.NO_ID) return null;
8668                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8669            case FOCUS_DOWN:
8670                if (mNextFocusDownId == View.NO_ID) return null;
8671                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8672            case FOCUS_FORWARD:
8673                if (mNextFocusForwardId == View.NO_ID) return null;
8674                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8675            case FOCUS_BACKWARD: {
8676                if (mID == View.NO_ID) return null;
8677                final int id = mID;
8678                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8679                    @Override
8680                    public boolean apply(View t) {
8681                        return t.mNextFocusForwardId == id;
8682                    }
8683                });
8684            }
8685        }
8686        return null;
8687    }
8688
8689    private View findViewInsideOutShouldExist(View root, int id) {
8690        if (mMatchIdPredicate == null) {
8691            mMatchIdPredicate = new MatchIdPredicate();
8692        }
8693        mMatchIdPredicate.mId = id;
8694        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8695        if (result == null) {
8696            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8697        }
8698        return result;
8699    }
8700
8701    /**
8702     * Find and return all focusable views that are descendants of this view,
8703     * possibly including this view if it is focusable itself.
8704     *
8705     * @param direction The direction of the focus
8706     * @return A list of focusable views
8707     */
8708    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8709        ArrayList<View> result = new ArrayList<View>(24);
8710        addFocusables(result, direction);
8711        return result;
8712    }
8713
8714    /**
8715     * Add any focusable views that are descendants of this view (possibly
8716     * including this view if it is focusable itself) to views.  If we are in touch mode,
8717     * only add views that are also focusable in touch mode.
8718     *
8719     * @param views Focusable views found so far
8720     * @param direction The direction of the focus
8721     */
8722    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8723        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
8724    }
8725
8726    /**
8727     * Adds any focusable views that are descendants of this view (possibly
8728     * including this view if it is focusable itself) to views. This method
8729     * adds all focusable views regardless if we are in touch mode or
8730     * only views focusable in touch mode if we are in touch mode or
8731     * only views that can take accessibility focus if accessibility is enabled
8732     * depending on the focusable mode parameter.
8733     *
8734     * @param views Focusable views found so far or null if all we are interested is
8735     *        the number of focusables.
8736     * @param direction The direction of the focus.
8737     * @param focusableMode The type of focusables to be added.
8738     *
8739     * @see #FOCUSABLES_ALL
8740     * @see #FOCUSABLES_TOUCH_MODE
8741     */
8742    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8743            @FocusableMode int focusableMode) {
8744        if (views == null) {
8745            return;
8746        }
8747        if (!isFocusable()) {
8748            return;
8749        }
8750        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8751                && isInTouchMode() && !isFocusableInTouchMode()) {
8752            return;
8753        }
8754        views.add(this);
8755    }
8756
8757    /**
8758     * Finds the Views that contain given text. The containment is case insensitive.
8759     * The search is performed by either the text that the View renders or the content
8760     * description that describes the view for accessibility purposes and the view does
8761     * not render or both. Clients can specify how the search is to be performed via
8762     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8763     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8764     *
8765     * @param outViews The output list of matching Views.
8766     * @param searched The text to match against.
8767     *
8768     * @see #FIND_VIEWS_WITH_TEXT
8769     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8770     * @see #setContentDescription(CharSequence)
8771     */
8772    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8773            @FindViewFlags int flags) {
8774        if (getAccessibilityNodeProvider() != null) {
8775            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8776                outViews.add(this);
8777            }
8778        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8779                && (searched != null && searched.length() > 0)
8780                && (mContentDescription != null && mContentDescription.length() > 0)) {
8781            String searchedLowerCase = searched.toString().toLowerCase();
8782            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8783            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8784                outViews.add(this);
8785            }
8786        }
8787    }
8788
8789    /**
8790     * Find and return all touchable views that are descendants of this view,
8791     * possibly including this view if it is touchable itself.
8792     *
8793     * @return A list of touchable views
8794     */
8795    public ArrayList<View> getTouchables() {
8796        ArrayList<View> result = new ArrayList<View>();
8797        addTouchables(result);
8798        return result;
8799    }
8800
8801    /**
8802     * Add any touchable views that are descendants of this view (possibly
8803     * including this view if it is touchable itself) to views.
8804     *
8805     * @param views Touchable views found so far
8806     */
8807    public void addTouchables(ArrayList<View> views) {
8808        final int viewFlags = mViewFlags;
8809
8810        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8811                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8812                && (viewFlags & ENABLED_MASK) == ENABLED) {
8813            views.add(this);
8814        }
8815    }
8816
8817    /**
8818     * Returns whether this View is accessibility focused.
8819     *
8820     * @return True if this View is accessibility focused.
8821     */
8822    public boolean isAccessibilityFocused() {
8823        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8824    }
8825
8826    /**
8827     * Call this to try to give accessibility focus to this view.
8828     *
8829     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8830     * returns false or the view is no visible or the view already has accessibility
8831     * focus.
8832     *
8833     * See also {@link #focusSearch(int)}, which is what you call to say that you
8834     * have focus, and you want your parent to look for the next one.
8835     *
8836     * @return Whether this view actually took accessibility focus.
8837     *
8838     * @hide
8839     */
8840    public boolean requestAccessibilityFocus() {
8841        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8842        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8843            return false;
8844        }
8845        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8846            return false;
8847        }
8848        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8849            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8850            ViewRootImpl viewRootImpl = getViewRootImpl();
8851            if (viewRootImpl != null) {
8852                viewRootImpl.setAccessibilityFocus(this, null);
8853            }
8854            invalidate();
8855            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8856            return true;
8857        }
8858        return false;
8859    }
8860
8861    /**
8862     * Call this to try to clear accessibility focus of this view.
8863     *
8864     * See also {@link #focusSearch(int)}, which is what you call to say that you
8865     * have focus, and you want your parent to look for the next one.
8866     *
8867     * @hide
8868     */
8869    public void clearAccessibilityFocus() {
8870        clearAccessibilityFocusNoCallbacks();
8871
8872        // Clear the global reference of accessibility focus if this view or
8873        // any of its descendants had accessibility focus. This will NOT send
8874        // an event or update internal state if focus is cleared from a
8875        // descendant view, which may leave views in inconsistent states.
8876        final ViewRootImpl viewRootImpl = getViewRootImpl();
8877        if (viewRootImpl != null) {
8878            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8879            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8880                viewRootImpl.setAccessibilityFocus(null, null);
8881            }
8882        }
8883    }
8884
8885    private void sendAccessibilityHoverEvent(int eventType) {
8886        // Since we are not delivering to a client accessibility events from not
8887        // important views (unless the clinet request that) we need to fire the
8888        // event from the deepest view exposed to the client. As a consequence if
8889        // the user crosses a not exposed view the client will see enter and exit
8890        // of the exposed predecessor followed by and enter and exit of that same
8891        // predecessor when entering and exiting the not exposed descendant. This
8892        // is fine since the client has a clear idea which view is hovered at the
8893        // price of a couple more events being sent. This is a simple and
8894        // working solution.
8895        View source = this;
8896        while (true) {
8897            if (source.includeForAccessibility()) {
8898                source.sendAccessibilityEvent(eventType);
8899                return;
8900            }
8901            ViewParent parent = source.getParent();
8902            if (parent instanceof View) {
8903                source = (View) parent;
8904            } else {
8905                return;
8906            }
8907        }
8908    }
8909
8910    /**
8911     * Clears accessibility focus without calling any callback methods
8912     * normally invoked in {@link #clearAccessibilityFocus()}. This method
8913     * is used for clearing accessibility focus when giving this focus to
8914     * another view.
8915     */
8916    void clearAccessibilityFocusNoCallbacks() {
8917        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
8918            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
8919            invalidate();
8920            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
8921        }
8922    }
8923
8924    /**
8925     * Call this to try to give focus to a specific view or to one of its
8926     * descendants.
8927     *
8928     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8929     * false), or if it is focusable and it is not focusable in touch mode
8930     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8931     *
8932     * See also {@link #focusSearch(int)}, which is what you call to say that you
8933     * have focus, and you want your parent to look for the next one.
8934     *
8935     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
8936     * {@link #FOCUS_DOWN} and <code>null</code>.
8937     *
8938     * @return Whether this view or one of its descendants actually took focus.
8939     */
8940    public final boolean requestFocus() {
8941        return requestFocus(View.FOCUS_DOWN);
8942    }
8943
8944    /**
8945     * Call this to try to give focus to a specific view or to one of its
8946     * descendants and give it a hint about what direction focus is heading.
8947     *
8948     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8949     * false), or if it is focusable and it is not focusable in touch mode
8950     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8951     *
8952     * See also {@link #focusSearch(int)}, which is what you call to say that you
8953     * have focus, and you want your parent to look for the next one.
8954     *
8955     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
8956     * <code>null</code> set for the previously focused rectangle.
8957     *
8958     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8959     * @return Whether this view or one of its descendants actually took focus.
8960     */
8961    public final boolean requestFocus(int direction) {
8962        return requestFocus(direction, null);
8963    }
8964
8965    /**
8966     * Call this to try to give focus to a specific view or to one of its descendants
8967     * and give it hints about the direction and a specific rectangle that the focus
8968     * is coming from.  The rectangle can help give larger views a finer grained hint
8969     * about where focus is coming from, and therefore, where to show selection, or
8970     * forward focus change internally.
8971     *
8972     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8973     * false), or if it is focusable and it is not focusable in touch mode
8974     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8975     *
8976     * A View will not take focus if it is not visible.
8977     *
8978     * A View will not take focus if one of its parents has
8979     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
8980     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
8981     *
8982     * See also {@link #focusSearch(int)}, which is what you call to say that you
8983     * have focus, and you want your parent to look for the next one.
8984     *
8985     * You may wish to override this method if your custom {@link View} has an internal
8986     * {@link View} that it wishes to forward the request to.
8987     *
8988     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8989     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
8990     *        to give a finer grained hint about where focus is coming from.  May be null
8991     *        if there is no hint.
8992     * @return Whether this view or one of its descendants actually took focus.
8993     */
8994    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
8995        return requestFocusNoSearch(direction, previouslyFocusedRect);
8996    }
8997
8998    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
8999        // need to be focusable
9000        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9001                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9002            return false;
9003        }
9004
9005        // need to be focusable in touch mode if in touch mode
9006        if (isInTouchMode() &&
9007            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9008               return false;
9009        }
9010
9011        // need to not have any parents blocking us
9012        if (hasAncestorThatBlocksDescendantFocus()) {
9013            return false;
9014        }
9015
9016        handleFocusGainInternal(direction, previouslyFocusedRect);
9017        return true;
9018    }
9019
9020    /**
9021     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9022     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9023     * touch mode to request focus when they are touched.
9024     *
9025     * @return Whether this view or one of its descendants actually took focus.
9026     *
9027     * @see #isInTouchMode()
9028     *
9029     */
9030    public final boolean requestFocusFromTouch() {
9031        // Leave touch mode if we need to
9032        if (isInTouchMode()) {
9033            ViewRootImpl viewRoot = getViewRootImpl();
9034            if (viewRoot != null) {
9035                viewRoot.ensureTouchMode(false);
9036            }
9037        }
9038        return requestFocus(View.FOCUS_DOWN);
9039    }
9040
9041    /**
9042     * @return Whether any ancestor of this view blocks descendant focus.
9043     */
9044    private boolean hasAncestorThatBlocksDescendantFocus() {
9045        final boolean focusableInTouchMode = isFocusableInTouchMode();
9046        ViewParent ancestor = mParent;
9047        while (ancestor instanceof ViewGroup) {
9048            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9049            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9050                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9051                return true;
9052            } else {
9053                ancestor = vgAncestor.getParent();
9054            }
9055        }
9056        return false;
9057    }
9058
9059    /**
9060     * Gets the mode for determining whether this View is important for accessibility
9061     * which is if it fires accessibility events and if it is reported to
9062     * accessibility services that query the screen.
9063     *
9064     * @return The mode for determining whether a View is important for accessibility.
9065     *
9066     * @attr ref android.R.styleable#View_importantForAccessibility
9067     *
9068     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9069     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9070     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9071     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9072     */
9073    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9074            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9075            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9076            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9077            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9078                    to = "noHideDescendants")
9079        })
9080    public int getImportantForAccessibility() {
9081        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9082                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9083    }
9084
9085    /**
9086     * Sets the live region mode for this view. This indicates to accessibility
9087     * services whether they should automatically notify the user about changes
9088     * to the view's content description or text, or to the content descriptions
9089     * or text of the view's children (where applicable).
9090     * <p>
9091     * For example, in a login screen with a TextView that displays an "incorrect
9092     * password" notification, that view should be marked as a live region with
9093     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9094     * <p>
9095     * To disable change notifications for this view, use
9096     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9097     * mode for most views.
9098     * <p>
9099     * To indicate that the user should be notified of changes, use
9100     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9101     * <p>
9102     * If the view's changes should interrupt ongoing speech and notify the user
9103     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9104     *
9105     * @param mode The live region mode for this view, one of:
9106     *        <ul>
9107     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9108     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9109     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9110     *        </ul>
9111     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9112     */
9113    public void setAccessibilityLiveRegion(int mode) {
9114        if (mode != getAccessibilityLiveRegion()) {
9115            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9116            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9117                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9118            notifyViewAccessibilityStateChangedIfNeeded(
9119                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9120        }
9121    }
9122
9123    /**
9124     * Gets the live region mode for this View.
9125     *
9126     * @return The live region mode for the view.
9127     *
9128     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9129     *
9130     * @see #setAccessibilityLiveRegion(int)
9131     */
9132    public int getAccessibilityLiveRegion() {
9133        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9134                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9135    }
9136
9137    /**
9138     * Sets how to determine whether this view is important for accessibility
9139     * which is if it fires accessibility events and if it is reported to
9140     * accessibility services that query the screen.
9141     *
9142     * @param mode How to determine whether this view is important for accessibility.
9143     *
9144     * @attr ref android.R.styleable#View_importantForAccessibility
9145     *
9146     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9147     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9148     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9149     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9150     */
9151    public void setImportantForAccessibility(int mode) {
9152        final int oldMode = getImportantForAccessibility();
9153        if (mode != oldMode) {
9154            final boolean hideDescendants =
9155                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9156
9157            // If this node or its descendants are no longer important, try to
9158            // clear accessibility focus.
9159            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9160                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9161                if (focusHost != null) {
9162                    focusHost.clearAccessibilityFocus();
9163                }
9164            }
9165
9166            // If we're moving between AUTO and another state, we might not need
9167            // to send a subtree changed notification. We'll store the computed
9168            // importance, since we'll need to check it later to make sure.
9169            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9170                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9171            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9172            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9173            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9174                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9175            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9176                notifySubtreeAccessibilityStateChangedIfNeeded();
9177            } else {
9178                notifyViewAccessibilityStateChangedIfNeeded(
9179                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9180            }
9181        }
9182    }
9183
9184    /**
9185     * Returns the view within this view's hierarchy that is hosting
9186     * accessibility focus.
9187     *
9188     * @param searchDescendants whether to search for focus in descendant views
9189     * @return the view hosting accessibility focus, or {@code null}
9190     */
9191    private View findAccessibilityFocusHost(boolean searchDescendants) {
9192        if (isAccessibilityFocusedViewOrHost()) {
9193            return this;
9194        }
9195
9196        if (searchDescendants) {
9197            final ViewRootImpl viewRoot = getViewRootImpl();
9198            if (viewRoot != null) {
9199                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9200                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9201                    return focusHost;
9202                }
9203            }
9204        }
9205
9206        return null;
9207    }
9208
9209    /**
9210     * Computes whether this view should be exposed for accessibility. In
9211     * general, views that are interactive or provide information are exposed
9212     * while views that serve only as containers are hidden.
9213     * <p>
9214     * If an ancestor of this view has importance
9215     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9216     * returns <code>false</code>.
9217     * <p>
9218     * Otherwise, the value is computed according to the view's
9219     * {@link #getImportantForAccessibility()} value:
9220     * <ol>
9221     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9222     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9223     * </code>
9224     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9225     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9226     * view satisfies any of the following:
9227     * <ul>
9228     * <li>Is actionable, e.g. {@link #isClickable()},
9229     * {@link #isLongClickable()}, or {@link #isFocusable()}
9230     * <li>Has an {@link AccessibilityDelegate}
9231     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9232     * {@link OnKeyListener}, etc.
9233     * <li>Is an accessibility live region, e.g.
9234     * {@link #getAccessibilityLiveRegion()} is not
9235     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9236     * </ul>
9237     * </ol>
9238     *
9239     * @return Whether the view is exposed for accessibility.
9240     * @see #setImportantForAccessibility(int)
9241     * @see #getImportantForAccessibility()
9242     */
9243    public boolean isImportantForAccessibility() {
9244        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9245                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9246        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9247                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9248            return false;
9249        }
9250
9251        // Check parent mode to ensure we're not hidden.
9252        ViewParent parent = mParent;
9253        while (parent instanceof View) {
9254            if (((View) parent).getImportantForAccessibility()
9255                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9256                return false;
9257            }
9258            parent = parent.getParent();
9259        }
9260
9261        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9262                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9263                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9264    }
9265
9266    /**
9267     * Gets the parent for accessibility purposes. Note that the parent for
9268     * accessibility is not necessary the immediate parent. It is the first
9269     * predecessor that is important for accessibility.
9270     *
9271     * @return The parent for accessibility purposes.
9272     */
9273    public ViewParent getParentForAccessibility() {
9274        if (mParent instanceof View) {
9275            View parentView = (View) mParent;
9276            if (parentView.includeForAccessibility()) {
9277                return mParent;
9278            } else {
9279                return mParent.getParentForAccessibility();
9280            }
9281        }
9282        return null;
9283    }
9284
9285    /**
9286     * Adds the children of this View relevant for accessibility to the given list
9287     * as output. Since some Views are not important for accessibility the added
9288     * child views are not necessarily direct children of this view, rather they are
9289     * the first level of descendants important for accessibility.
9290     *
9291     * @param outChildren The output list that will receive children for accessibility.
9292     */
9293    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9294
9295    }
9296
9297    /**
9298     * Whether to regard this view for accessibility. A view is regarded for
9299     * accessibility if it is important for accessibility or the querying
9300     * accessibility service has explicitly requested that view not
9301     * important for accessibility are regarded.
9302     *
9303     * @return Whether to regard the view for accessibility.
9304     *
9305     * @hide
9306     */
9307    public boolean includeForAccessibility() {
9308        if (mAttachInfo != null) {
9309            return (mAttachInfo.mAccessibilityFetchFlags
9310                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9311                    || isImportantForAccessibility();
9312        }
9313        return false;
9314    }
9315
9316    /**
9317     * Returns whether the View is considered actionable from
9318     * accessibility perspective. Such view are important for
9319     * accessibility.
9320     *
9321     * @return True if the view is actionable for accessibility.
9322     *
9323     * @hide
9324     */
9325    public boolean isActionableForAccessibility() {
9326        return (isClickable() || isLongClickable() || isFocusable());
9327    }
9328
9329    /**
9330     * Returns whether the View has registered callbacks which makes it
9331     * important for accessibility.
9332     *
9333     * @return True if the view is actionable for accessibility.
9334     */
9335    private boolean hasListenersForAccessibility() {
9336        ListenerInfo info = getListenerInfo();
9337        return mTouchDelegate != null || info.mOnKeyListener != null
9338                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
9339                || info.mOnHoverListener != null || info.mOnDragListener != null;
9340    }
9341
9342    /**
9343     * Notifies that the accessibility state of this view changed. The change
9344     * is local to this view and does not represent structural changes such
9345     * as children and parent. For example, the view became focusable. The
9346     * notification is at at most once every
9347     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9348     * to avoid unnecessary load to the system. Also once a view has a pending
9349     * notification this method is a NOP until the notification has been sent.
9350     *
9351     * @hide
9352     */
9353    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
9354        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9355            return;
9356        }
9357        if (mSendViewStateChangedAccessibilityEvent == null) {
9358            mSendViewStateChangedAccessibilityEvent =
9359                    new SendViewStateChangedAccessibilityEvent();
9360        }
9361        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
9362    }
9363
9364    /**
9365     * Notifies that the accessibility state of this view changed. The change
9366     * is *not* local to this view and does represent structural changes such
9367     * as children and parent. For example, the view size changed. The
9368     * notification is at at most once every
9369     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9370     * to avoid unnecessary load to the system. Also once a view has a pending
9371     * notification this method is a NOP until the notification has been sent.
9372     *
9373     * @hide
9374     */
9375    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
9376        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9377            return;
9378        }
9379        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
9380            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9381            if (mParent != null) {
9382                try {
9383                    mParent.notifySubtreeAccessibilityStateChanged(
9384                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
9385                } catch (AbstractMethodError e) {
9386                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9387                            " does not fully implement ViewParent", e);
9388                }
9389            }
9390        }
9391    }
9392
9393    /**
9394     * Change the visibility of the View without triggering any other changes. This is
9395     * important for transitions, where visibility changes should not adjust focus or
9396     * trigger a new layout. This is only used when the visibility has already been changed
9397     * and we need a transient value during an animation. When the animation completes,
9398     * the original visibility value is always restored.
9399     *
9400     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9401     * @hide
9402     */
9403    public void setTransitionVisibility(@Visibility int visibility) {
9404        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
9405    }
9406
9407    /**
9408     * Reset the flag indicating the accessibility state of the subtree rooted
9409     * at this view changed.
9410     */
9411    void resetSubtreeAccessibilityStateChanged() {
9412        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9413    }
9414
9415    /**
9416     * Report an accessibility action to this view's parents for delegated processing.
9417     *
9418     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
9419     * call this method to delegate an accessibility action to a supporting parent. If the parent
9420     * returns true from its
9421     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
9422     * method this method will return true to signify that the action was consumed.</p>
9423     *
9424     * <p>This method is useful for implementing nested scrolling child views. If
9425     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
9426     * a custom view implementation may invoke this method to allow a parent to consume the
9427     * scroll first. If this method returns true the custom view should skip its own scrolling
9428     * behavior.</p>
9429     *
9430     * @param action Accessibility action to delegate
9431     * @param arguments Optional action arguments
9432     * @return true if the action was consumed by a parent
9433     */
9434    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
9435        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
9436            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
9437                return true;
9438            }
9439        }
9440        return false;
9441    }
9442
9443    /**
9444     * Performs the specified accessibility action on the view. For
9445     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
9446     * <p>
9447     * If an {@link AccessibilityDelegate} has been specified via calling
9448     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9449     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
9450     * is responsible for handling this call.
9451     * </p>
9452     *
9453     * <p>The default implementation will delegate
9454     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
9455     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
9456     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
9457     *
9458     * @param action The action to perform.
9459     * @param arguments Optional action arguments.
9460     * @return Whether the action was performed.
9461     */
9462    public boolean performAccessibilityAction(int action, Bundle arguments) {
9463      if (mAccessibilityDelegate != null) {
9464          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
9465      } else {
9466          return performAccessibilityActionInternal(action, arguments);
9467      }
9468    }
9469
9470   /**
9471    * @see #performAccessibilityAction(int, Bundle)
9472    *
9473    * Note: Called from the default {@link AccessibilityDelegate}.
9474    *
9475    * @hide
9476    */
9477    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9478        if (isNestedScrollingEnabled()
9479                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
9480                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
9481                || action == R.id.accessibilityActionScrollUp
9482                || action == R.id.accessibilityActionScrollLeft
9483                || action == R.id.accessibilityActionScrollDown
9484                || action == R.id.accessibilityActionScrollRight)) {
9485            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
9486                return true;
9487            }
9488        }
9489
9490        switch (action) {
9491            case AccessibilityNodeInfo.ACTION_CLICK: {
9492                if (isClickable()) {
9493                    performClick();
9494                    return true;
9495                }
9496            } break;
9497            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
9498                if (isLongClickable()) {
9499                    performLongClick();
9500                    return true;
9501                }
9502            } break;
9503            case AccessibilityNodeInfo.ACTION_FOCUS: {
9504                if (!hasFocus()) {
9505                    // Get out of touch mode since accessibility
9506                    // wants to move focus around.
9507                    getViewRootImpl().ensureTouchMode(false);
9508                    return requestFocus();
9509                }
9510            } break;
9511            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
9512                if (hasFocus()) {
9513                    clearFocus();
9514                    return !isFocused();
9515                }
9516            } break;
9517            case AccessibilityNodeInfo.ACTION_SELECT: {
9518                if (!isSelected()) {
9519                    setSelected(true);
9520                    return isSelected();
9521                }
9522            } break;
9523            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
9524                if (isSelected()) {
9525                    setSelected(false);
9526                    return !isSelected();
9527                }
9528            } break;
9529            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
9530                if (!isAccessibilityFocused()) {
9531                    return requestAccessibilityFocus();
9532                }
9533            } break;
9534            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
9535                if (isAccessibilityFocused()) {
9536                    clearAccessibilityFocus();
9537                    return true;
9538                }
9539            } break;
9540            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
9541                if (arguments != null) {
9542                    final int granularity = arguments.getInt(
9543                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9544                    final boolean extendSelection = arguments.getBoolean(
9545                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9546                    return traverseAtGranularity(granularity, true, extendSelection);
9547                }
9548            } break;
9549            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
9550                if (arguments != null) {
9551                    final int granularity = arguments.getInt(
9552                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9553                    final boolean extendSelection = arguments.getBoolean(
9554                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9555                    return traverseAtGranularity(granularity, false, extendSelection);
9556                }
9557            } break;
9558            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
9559                CharSequence text = getIterableTextForAccessibility();
9560                if (text == null) {
9561                    return false;
9562                }
9563                final int start = (arguments != null) ? arguments.getInt(
9564                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
9565                final int end = (arguments != null) ? arguments.getInt(
9566                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
9567                // Only cursor position can be specified (selection length == 0)
9568                if ((getAccessibilitySelectionStart() != start
9569                        || getAccessibilitySelectionEnd() != end)
9570                        && (start == end)) {
9571                    setAccessibilitySelection(start, end);
9572                    notifyViewAccessibilityStateChangedIfNeeded(
9573                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9574                    return true;
9575                }
9576            } break;
9577            case R.id.accessibilityActionShowOnScreen: {
9578                if (mAttachInfo != null) {
9579                    final Rect r = mAttachInfo.mTmpInvalRect;
9580                    getDrawingRect(r);
9581                    return requestRectangleOnScreen(r, true);
9582                }
9583            } break;
9584            case R.id.accessibilityActionContextClick: {
9585                if (isContextClickable()) {
9586                    performContextClick();
9587                    return true;
9588                }
9589            } break;
9590        }
9591        return false;
9592    }
9593
9594    private boolean traverseAtGranularity(int granularity, boolean forward,
9595            boolean extendSelection) {
9596        CharSequence text = getIterableTextForAccessibility();
9597        if (text == null || text.length() == 0) {
9598            return false;
9599        }
9600        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9601        if (iterator == null) {
9602            return false;
9603        }
9604        int current = getAccessibilitySelectionEnd();
9605        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9606            current = forward ? 0 : text.length();
9607        }
9608        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9609        if (range == null) {
9610            return false;
9611        }
9612        final int segmentStart = range[0];
9613        final int segmentEnd = range[1];
9614        int selectionStart;
9615        int selectionEnd;
9616        if (extendSelection && isAccessibilitySelectionExtendable()) {
9617            selectionStart = getAccessibilitySelectionStart();
9618            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9619                selectionStart = forward ? segmentStart : segmentEnd;
9620            }
9621            selectionEnd = forward ? segmentEnd : segmentStart;
9622        } else {
9623            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9624        }
9625        setAccessibilitySelection(selectionStart, selectionEnd);
9626        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9627                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9628        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9629        return true;
9630    }
9631
9632    /**
9633     * Gets the text reported for accessibility purposes.
9634     *
9635     * @return The accessibility text.
9636     *
9637     * @hide
9638     */
9639    public CharSequence getIterableTextForAccessibility() {
9640        return getContentDescription();
9641    }
9642
9643    /**
9644     * Gets whether accessibility selection can be extended.
9645     *
9646     * @return If selection is extensible.
9647     *
9648     * @hide
9649     */
9650    public boolean isAccessibilitySelectionExtendable() {
9651        return false;
9652    }
9653
9654    /**
9655     * @hide
9656     */
9657    public int getAccessibilitySelectionStart() {
9658        return mAccessibilityCursorPosition;
9659    }
9660
9661    /**
9662     * @hide
9663     */
9664    public int getAccessibilitySelectionEnd() {
9665        return getAccessibilitySelectionStart();
9666    }
9667
9668    /**
9669     * @hide
9670     */
9671    public void setAccessibilitySelection(int start, int end) {
9672        if (start ==  end && end == mAccessibilityCursorPosition) {
9673            return;
9674        }
9675        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9676            mAccessibilityCursorPosition = start;
9677        } else {
9678            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9679        }
9680        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9681    }
9682
9683    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9684            int fromIndex, int toIndex) {
9685        if (mParent == null) {
9686            return;
9687        }
9688        AccessibilityEvent event = AccessibilityEvent.obtain(
9689                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9690        onInitializeAccessibilityEvent(event);
9691        onPopulateAccessibilityEvent(event);
9692        event.setFromIndex(fromIndex);
9693        event.setToIndex(toIndex);
9694        event.setAction(action);
9695        event.setMovementGranularity(granularity);
9696        mParent.requestSendAccessibilityEvent(this, event);
9697    }
9698
9699    /**
9700     * @hide
9701     */
9702    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9703        switch (granularity) {
9704            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9705                CharSequence text = getIterableTextForAccessibility();
9706                if (text != null && text.length() > 0) {
9707                    CharacterTextSegmentIterator iterator =
9708                        CharacterTextSegmentIterator.getInstance(
9709                                mContext.getResources().getConfiguration().locale);
9710                    iterator.initialize(text.toString());
9711                    return iterator;
9712                }
9713            } break;
9714            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9715                CharSequence text = getIterableTextForAccessibility();
9716                if (text != null && text.length() > 0) {
9717                    WordTextSegmentIterator iterator =
9718                        WordTextSegmentIterator.getInstance(
9719                                mContext.getResources().getConfiguration().locale);
9720                    iterator.initialize(text.toString());
9721                    return iterator;
9722                }
9723            } break;
9724            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9725                CharSequence text = getIterableTextForAccessibility();
9726                if (text != null && text.length() > 0) {
9727                    ParagraphTextSegmentIterator iterator =
9728                        ParagraphTextSegmentIterator.getInstance();
9729                    iterator.initialize(text.toString());
9730                    return iterator;
9731                }
9732            } break;
9733        }
9734        return null;
9735    }
9736
9737    /**
9738     * @hide
9739     */
9740    public void dispatchStartTemporaryDetach() {
9741        onStartTemporaryDetach();
9742    }
9743
9744    /**
9745     * This is called when a container is going to temporarily detach a child, with
9746     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9747     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9748     * {@link #onDetachedFromWindow()} when the container is done.
9749     */
9750    public void onStartTemporaryDetach() {
9751        removeUnsetPressCallback();
9752        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9753    }
9754
9755    /**
9756     * @hide
9757     */
9758    public void dispatchFinishTemporaryDetach() {
9759        onFinishTemporaryDetach();
9760    }
9761
9762    /**
9763     * Called after {@link #onStartTemporaryDetach} when the container is done
9764     * changing the view.
9765     */
9766    public void onFinishTemporaryDetach() {
9767    }
9768
9769    /**
9770     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9771     * for this view's window.  Returns null if the view is not currently attached
9772     * to the window.  Normally you will not need to use this directly, but
9773     * just use the standard high-level event callbacks like
9774     * {@link #onKeyDown(int, KeyEvent)}.
9775     */
9776    public KeyEvent.DispatcherState getKeyDispatcherState() {
9777        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9778    }
9779
9780    /**
9781     * Dispatch a key event before it is processed by any input method
9782     * associated with the view hierarchy.  This can be used to intercept
9783     * key events in special situations before the IME consumes them; a
9784     * typical example would be handling the BACK key to update the application's
9785     * UI instead of allowing the IME to see it and close itself.
9786     *
9787     * @param event The key event to be dispatched.
9788     * @return True if the event was handled, false otherwise.
9789     */
9790    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9791        return onKeyPreIme(event.getKeyCode(), event);
9792    }
9793
9794    /**
9795     * Dispatch a key event to the next view on the focus path. This path runs
9796     * from the top of the view tree down to the currently focused view. If this
9797     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9798     * the next node down the focus path. This method also fires any key
9799     * listeners.
9800     *
9801     * @param event The key event to be dispatched.
9802     * @return True if the event was handled, false otherwise.
9803     */
9804    public boolean dispatchKeyEvent(KeyEvent event) {
9805        if (mInputEventConsistencyVerifier != null) {
9806            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9807        }
9808
9809        // Give any attached key listener a first crack at the event.
9810        //noinspection SimplifiableIfStatement
9811        ListenerInfo li = mListenerInfo;
9812        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9813                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9814            return true;
9815        }
9816
9817        if (event.dispatch(this, mAttachInfo != null
9818                ? mAttachInfo.mKeyDispatchState : null, this)) {
9819            return true;
9820        }
9821
9822        if (mInputEventConsistencyVerifier != null) {
9823            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9824        }
9825        return false;
9826    }
9827
9828    /**
9829     * Dispatches a key shortcut event.
9830     *
9831     * @param event The key event to be dispatched.
9832     * @return True if the event was handled by the view, false otherwise.
9833     */
9834    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9835        return onKeyShortcut(event.getKeyCode(), event);
9836    }
9837
9838    /**
9839     * Pass the touch screen motion event down to the target view, or this
9840     * view if it is the target.
9841     *
9842     * @param event The motion event to be dispatched.
9843     * @return True if the event was handled by the view, false otherwise.
9844     */
9845    public boolean dispatchTouchEvent(MotionEvent event) {
9846        // If the event should be handled by accessibility focus first.
9847        if (event.isTargetAccessibilityFocus()) {
9848            // We don't have focus or no virtual descendant has it, do not handle the event.
9849            if (!isAccessibilityFocusedViewOrHost()) {
9850                return false;
9851            }
9852            // We have focus and got the event, then use normal event dispatch.
9853            event.setTargetAccessibilityFocus(false);
9854        }
9855
9856        boolean result = false;
9857
9858        if (mInputEventConsistencyVerifier != null) {
9859            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
9860        }
9861
9862        final int actionMasked = event.getActionMasked();
9863        if (actionMasked == MotionEvent.ACTION_DOWN) {
9864            // Defensive cleanup for new gesture
9865            stopNestedScroll();
9866        }
9867
9868        if (onFilterTouchEventForSecurity(event)) {
9869            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
9870                result = true;
9871            }
9872            //noinspection SimplifiableIfStatement
9873            ListenerInfo li = mListenerInfo;
9874            if (li != null && li.mOnTouchListener != null
9875                    && (mViewFlags & ENABLED_MASK) == ENABLED
9876                    && li.mOnTouchListener.onTouch(this, event)) {
9877                result = true;
9878            }
9879
9880            if (!result && onTouchEvent(event)) {
9881                result = true;
9882            }
9883        }
9884
9885        if (!result && mInputEventConsistencyVerifier != null) {
9886            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9887        }
9888
9889        // Clean up after nested scrolls if this is the end of a gesture;
9890        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
9891        // of the gesture.
9892        if (actionMasked == MotionEvent.ACTION_UP ||
9893                actionMasked == MotionEvent.ACTION_CANCEL ||
9894                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
9895            stopNestedScroll();
9896        }
9897
9898        return result;
9899    }
9900
9901    boolean isAccessibilityFocusedViewOrHost() {
9902        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
9903                .getAccessibilityFocusedHost() == this);
9904    }
9905
9906    /**
9907     * Filter the touch event to apply security policies.
9908     *
9909     * @param event The motion event to be filtered.
9910     * @return True if the event should be dispatched, false if the event should be dropped.
9911     *
9912     * @see #getFilterTouchesWhenObscured
9913     */
9914    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
9915        //noinspection RedundantIfStatement
9916        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
9917                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
9918            // Window is obscured, drop this touch.
9919            return false;
9920        }
9921        return true;
9922    }
9923
9924    /**
9925     * Pass a trackball motion event down to the focused view.
9926     *
9927     * @param event The motion event to be dispatched.
9928     * @return True if the event was handled by the view, false otherwise.
9929     */
9930    public boolean dispatchTrackballEvent(MotionEvent event) {
9931        if (mInputEventConsistencyVerifier != null) {
9932            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
9933        }
9934
9935        return onTrackballEvent(event);
9936    }
9937
9938    /**
9939     * Dispatch a generic motion event.
9940     * <p>
9941     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9942     * are delivered to the view under the pointer.  All other generic motion events are
9943     * delivered to the focused view.  Hover events are handled specially and are delivered
9944     * to {@link #onHoverEvent(MotionEvent)}.
9945     * </p>
9946     *
9947     * @param event The motion event to be dispatched.
9948     * @return True if the event was handled by the view, false otherwise.
9949     */
9950    public boolean dispatchGenericMotionEvent(MotionEvent event) {
9951        if (mInputEventConsistencyVerifier != null) {
9952            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
9953        }
9954
9955        final int source = event.getSource();
9956        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
9957            final int action = event.getAction();
9958            if (action == MotionEvent.ACTION_HOVER_ENTER
9959                    || action == MotionEvent.ACTION_HOVER_MOVE
9960                    || action == MotionEvent.ACTION_HOVER_EXIT) {
9961                if (dispatchHoverEvent(event)) {
9962                    return true;
9963                }
9964            } else if (dispatchGenericPointerEvent(event)) {
9965                return true;
9966            }
9967        } else if (dispatchGenericFocusedEvent(event)) {
9968            return true;
9969        }
9970
9971        if (dispatchGenericMotionEventInternal(event)) {
9972            return true;
9973        }
9974
9975        if (mInputEventConsistencyVerifier != null) {
9976            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9977        }
9978        return false;
9979    }
9980
9981    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
9982        //noinspection SimplifiableIfStatement
9983        ListenerInfo li = mListenerInfo;
9984        if (li != null && li.mOnGenericMotionListener != null
9985                && (mViewFlags & ENABLED_MASK) == ENABLED
9986                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
9987            return true;
9988        }
9989
9990        if (onGenericMotionEvent(event)) {
9991            return true;
9992        }
9993
9994        final int actionButton = event.getActionButton();
9995        switch (event.getActionMasked()) {
9996            case MotionEvent.ACTION_BUTTON_PRESS:
9997                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
9998                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
9999                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10000                    if (performContextClick()) {
10001                        mInContextButtonPress = true;
10002                        setPressed(true, event.getX(), event.getY());
10003                        removeTapCallback();
10004                        removeLongPressCallback();
10005                        return true;
10006                    }
10007                }
10008                break;
10009
10010            case MotionEvent.ACTION_BUTTON_RELEASE:
10011                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10012                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10013                    mInContextButtonPress = false;
10014                    mIgnoreNextUpEvent = true;
10015                }
10016                break;
10017        }
10018
10019        if (mInputEventConsistencyVerifier != null) {
10020            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10021        }
10022        return false;
10023    }
10024
10025    /**
10026     * Dispatch a hover event.
10027     * <p>
10028     * Do not call this method directly.
10029     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10030     * </p>
10031     *
10032     * @param event The motion event to be dispatched.
10033     * @return True if the event was handled by the view, false otherwise.
10034     */
10035    protected boolean dispatchHoverEvent(MotionEvent event) {
10036        ListenerInfo li = mListenerInfo;
10037        //noinspection SimplifiableIfStatement
10038        if (li != null && li.mOnHoverListener != null
10039                && (mViewFlags & ENABLED_MASK) == ENABLED
10040                && li.mOnHoverListener.onHover(this, event)) {
10041            return true;
10042        }
10043
10044        return onHoverEvent(event);
10045    }
10046
10047    /**
10048     * Returns true if the view has a child to which it has recently sent
10049     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10050     * it does not have a hovered child, then it must be the innermost hovered view.
10051     * @hide
10052     */
10053    protected boolean hasHoveredChild() {
10054        return false;
10055    }
10056
10057    /**
10058     * Dispatch a generic motion event to the view under the first pointer.
10059     * <p>
10060     * Do not call this method directly.
10061     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10062     * </p>
10063     *
10064     * @param event The motion event to be dispatched.
10065     * @return True if the event was handled by the view, false otherwise.
10066     */
10067    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10068        return false;
10069    }
10070
10071    /**
10072     * Dispatch a generic motion event to the currently focused view.
10073     * <p>
10074     * Do not call this method directly.
10075     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10076     * </p>
10077     *
10078     * @param event The motion event to be dispatched.
10079     * @return True if the event was handled by the view, false otherwise.
10080     */
10081    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10082        return false;
10083    }
10084
10085    /**
10086     * Dispatch a pointer event.
10087     * <p>
10088     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10089     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10090     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10091     * and should not be expected to handle other pointing device features.
10092     * </p>
10093     *
10094     * @param event The motion event to be dispatched.
10095     * @return True if the event was handled by the view, false otherwise.
10096     * @hide
10097     */
10098    public final boolean dispatchPointerEvent(MotionEvent event) {
10099        if (event.isTouchEvent()) {
10100            return dispatchTouchEvent(event);
10101        } else {
10102            return dispatchGenericMotionEvent(event);
10103        }
10104    }
10105
10106    /**
10107     * Called when the window containing this view gains or loses window focus.
10108     * ViewGroups should override to route to their children.
10109     *
10110     * @param hasFocus True if the window containing this view now has focus,
10111     *        false otherwise.
10112     */
10113    public void dispatchWindowFocusChanged(boolean hasFocus) {
10114        onWindowFocusChanged(hasFocus);
10115    }
10116
10117    /**
10118     * Called when the window containing this view gains or loses focus.  Note
10119     * that this is separate from view focus: to receive key events, both
10120     * your view and its window must have focus.  If a window is displayed
10121     * on top of yours that takes input focus, then your own window will lose
10122     * focus but the view focus will remain unchanged.
10123     *
10124     * @param hasWindowFocus True if the window containing this view now has
10125     *        focus, false otherwise.
10126     */
10127    public void onWindowFocusChanged(boolean hasWindowFocus) {
10128        InputMethodManager imm = InputMethodManager.peekInstance();
10129        if (!hasWindowFocus) {
10130            if (isPressed()) {
10131                setPressed(false);
10132            }
10133            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10134                imm.focusOut(this);
10135            }
10136            removeLongPressCallback();
10137            removeTapCallback();
10138            onFocusLost();
10139        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10140            imm.focusIn(this);
10141        }
10142        refreshDrawableState();
10143    }
10144
10145    /**
10146     * Returns true if this view is in a window that currently has window focus.
10147     * Note that this is not the same as the view itself having focus.
10148     *
10149     * @return True if this view is in a window that currently has window focus.
10150     */
10151    public boolean hasWindowFocus() {
10152        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10153    }
10154
10155    /**
10156     * Dispatch a view visibility change down the view hierarchy.
10157     * ViewGroups should override to route to their children.
10158     * @param changedView The view whose visibility changed. Could be 'this' or
10159     * an ancestor view.
10160     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10161     * {@link #INVISIBLE} or {@link #GONE}.
10162     */
10163    protected void dispatchVisibilityChanged(@NonNull View changedView,
10164            @Visibility int visibility) {
10165        onVisibilityChanged(changedView, visibility);
10166    }
10167
10168    /**
10169     * Called when the visibility of the view or an ancestor of the view has
10170     * changed.
10171     *
10172     * @param changedView The view whose visibility changed. May be
10173     *                    {@code this} or an ancestor view.
10174     * @param visibility The new visibility, one of {@link #VISIBLE},
10175     *                   {@link #INVISIBLE} or {@link #GONE}.
10176     */
10177    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10178    }
10179
10180    /**
10181     * Dispatch a hint about whether this view is displayed. For instance, when
10182     * a View moves out of the screen, it might receives a display hint indicating
10183     * the view is not displayed. Applications should not <em>rely</em> on this hint
10184     * as there is no guarantee that they will receive one.
10185     *
10186     * @param hint A hint about whether or not this view is displayed:
10187     * {@link #VISIBLE} or {@link #INVISIBLE}.
10188     */
10189    public void dispatchDisplayHint(@Visibility int hint) {
10190        onDisplayHint(hint);
10191    }
10192
10193    /**
10194     * Gives this view a hint about whether is displayed or not. For instance, when
10195     * a View moves out of the screen, it might receives a display hint indicating
10196     * the view is not displayed. Applications should not <em>rely</em> on this hint
10197     * as there is no guarantee that they will receive one.
10198     *
10199     * @param hint A hint about whether or not this view is displayed:
10200     * {@link #VISIBLE} or {@link #INVISIBLE}.
10201     */
10202    protected void onDisplayHint(@Visibility int hint) {
10203    }
10204
10205    /**
10206     * Dispatch a window visibility change down the view hierarchy.
10207     * ViewGroups should override to route to their children.
10208     *
10209     * @param visibility The new visibility of the window.
10210     *
10211     * @see #onWindowVisibilityChanged(int)
10212     */
10213    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10214        onWindowVisibilityChanged(visibility);
10215    }
10216
10217    /**
10218     * Called when the window containing has change its visibility
10219     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10220     * that this tells you whether or not your window is being made visible
10221     * to the window manager; this does <em>not</em> tell you whether or not
10222     * your window is obscured by other windows on the screen, even if it
10223     * is itself visible.
10224     *
10225     * @param visibility The new visibility of the window.
10226     */
10227    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10228        if (visibility == VISIBLE) {
10229            initialAwakenScrollBars();
10230        }
10231    }
10232
10233    /**
10234     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10235     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10236     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10237     *
10238     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10239     *                  ancestors or by window visibility
10240     * @return true if this view is visible to the user, not counting clipping or overlapping
10241     */
10242    @Visibility boolean dispatchVisibilityAggregated(boolean isVisible) {
10243        final boolean thisVisible = getVisibility() == VISIBLE;
10244        if (thisVisible) {
10245            onVisibilityAggregated(isVisible);
10246        }
10247        return thisVisible && isVisible;
10248    }
10249
10250    /**
10251     * Called when the user-visibility of this View is potentially affected by a change
10252     * to this view itself, an ancestor view or the window this view is attached to.
10253     *
10254     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10255     *                  and this view's window is also visible
10256     */
10257    @CallSuper
10258    public void onVisibilityAggregated(boolean isVisible) {
10259        if (isVisible && mAttachInfo != null) {
10260            initialAwakenScrollBars();
10261        }
10262
10263        final Drawable dr = mBackground;
10264        if (dr != null && isVisible != dr.isVisible()) {
10265            dr.setVisible(isVisible, false);
10266        }
10267        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10268        if (fg != null && isVisible != fg.isVisible()) {
10269            fg.setVisible(isVisible, false);
10270        }
10271    }
10272
10273    /**
10274     * Returns the current visibility of the window this view is attached to
10275     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10276     *
10277     * @return Returns the current visibility of the view's window.
10278     */
10279    @Visibility
10280    public int getWindowVisibility() {
10281        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10282    }
10283
10284    /**
10285     * Retrieve the overall visible display size in which the window this view is
10286     * attached to has been positioned in.  This takes into account screen
10287     * decorations above the window, for both cases where the window itself
10288     * is being position inside of them or the window is being placed under
10289     * then and covered insets are used for the window to position its content
10290     * inside.  In effect, this tells you the available area where content can
10291     * be placed and remain visible to users.
10292     *
10293     * <p>This function requires an IPC back to the window manager to retrieve
10294     * the requested information, so should not be used in performance critical
10295     * code like drawing.
10296     *
10297     * @param outRect Filled in with the visible display frame.  If the view
10298     * is not attached to a window, this is simply the raw display size.
10299     */
10300    public void getWindowVisibleDisplayFrame(Rect outRect) {
10301        if (mAttachInfo != null) {
10302            try {
10303                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10304            } catch (RemoteException e) {
10305                return;
10306            }
10307            // XXX This is really broken, and probably all needs to be done
10308            // in the window manager, and we need to know more about whether
10309            // we want the area behind or in front of the IME.
10310            final Rect insets = mAttachInfo.mVisibleInsets;
10311            outRect.left += insets.left;
10312            outRect.top += insets.top;
10313            outRect.right -= insets.right;
10314            outRect.bottom -= insets.bottom;
10315            return;
10316        }
10317        // The view is not attached to a display so we don't have a context.
10318        // Make a best guess about the display size.
10319        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10320        d.getRectSize(outRect);
10321    }
10322
10323    /**
10324     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
10325     * is currently in without any insets.
10326     *
10327     * @hide
10328     */
10329    public void getWindowDisplayFrame(Rect outRect) {
10330        if (mAttachInfo != null) {
10331            try {
10332                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10333            } catch (RemoteException e) {
10334                return;
10335            }
10336            return;
10337        }
10338        // The view is not attached to a display so we don't have a context.
10339        // Make a best guess about the display size.
10340        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10341        d.getRectSize(outRect);
10342    }
10343
10344    /**
10345     * Dispatch a notification about a resource configuration change down
10346     * the view hierarchy.
10347     * ViewGroups should override to route to their children.
10348     *
10349     * @param newConfig The new resource configuration.
10350     *
10351     * @see #onConfigurationChanged(android.content.res.Configuration)
10352     */
10353    public void dispatchConfigurationChanged(Configuration newConfig) {
10354        onConfigurationChanged(newConfig);
10355    }
10356
10357    /**
10358     * Called when the current configuration of the resources being used
10359     * by the application have changed.  You can use this to decide when
10360     * to reload resources that can changed based on orientation and other
10361     * configuration characteristics.  You only need to use this if you are
10362     * not relying on the normal {@link android.app.Activity} mechanism of
10363     * recreating the activity instance upon a configuration change.
10364     *
10365     * @param newConfig The new resource configuration.
10366     */
10367    protected void onConfigurationChanged(Configuration newConfig) {
10368    }
10369
10370    /**
10371     * Private function to aggregate all per-view attributes in to the view
10372     * root.
10373     */
10374    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10375        performCollectViewAttributes(attachInfo, visibility);
10376    }
10377
10378    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10379        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
10380            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
10381                attachInfo.mKeepScreenOn = true;
10382            }
10383            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
10384            ListenerInfo li = mListenerInfo;
10385            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
10386                attachInfo.mHasSystemUiListeners = true;
10387            }
10388        }
10389    }
10390
10391    void needGlobalAttributesUpdate(boolean force) {
10392        final AttachInfo ai = mAttachInfo;
10393        if (ai != null && !ai.mRecomputeGlobalAttributes) {
10394            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
10395                    || ai.mHasSystemUiListeners) {
10396                ai.mRecomputeGlobalAttributes = true;
10397            }
10398        }
10399    }
10400
10401    /**
10402     * Returns whether the device is currently in touch mode.  Touch mode is entered
10403     * once the user begins interacting with the device by touch, and affects various
10404     * things like whether focus is always visible to the user.
10405     *
10406     * @return Whether the device is in touch mode.
10407     */
10408    @ViewDebug.ExportedProperty
10409    public boolean isInTouchMode() {
10410        if (mAttachInfo != null) {
10411            return mAttachInfo.mInTouchMode;
10412        } else {
10413            return ViewRootImpl.isInTouchMode();
10414        }
10415    }
10416
10417    /**
10418     * Returns the context the view is running in, through which it can
10419     * access the current theme, resources, etc.
10420     *
10421     * @return The view's Context.
10422     */
10423    @ViewDebug.CapturedViewProperty
10424    public final Context getContext() {
10425        return mContext;
10426    }
10427
10428    /**
10429     * Handle a key event before it is processed by any input method
10430     * associated with the view hierarchy.  This can be used to intercept
10431     * key events in special situations before the IME consumes them; a
10432     * typical example would be handling the BACK key to update the application's
10433     * UI instead of allowing the IME to see it and close itself.
10434     *
10435     * @param keyCode The value in event.getKeyCode().
10436     * @param event Description of the key event.
10437     * @return If you handled the event, return true. If you want to allow the
10438     *         event to be handled by the next receiver, return false.
10439     */
10440    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
10441        return false;
10442    }
10443
10444    /**
10445     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
10446     * KeyEvent.Callback.onKeyDown()}: perform press of the view
10447     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
10448     * is released, if the view is enabled and clickable.
10449     * <p>
10450     * Key presses in software keyboards will generally NOT trigger this
10451     * listener, although some may elect to do so in some situations. Do not
10452     * rely on this to catch software key presses.
10453     *
10454     * @param keyCode a key code that represents the button pressed, from
10455     *                {@link android.view.KeyEvent}
10456     * @param event the KeyEvent object that defines the button action
10457     */
10458    public boolean onKeyDown(int keyCode, KeyEvent event) {
10459        if (KeyEvent.isConfirmKey(keyCode)) {
10460            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10461                return true;
10462            }
10463
10464            // Long clickable items don't necessarily have to be clickable.
10465            if (((mViewFlags & CLICKABLE) == CLICKABLE
10466                    || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10467                    && (event.getRepeatCount() == 0)) {
10468                // For the purposes of menu anchoring and drawable hotspots,
10469                // key events are considered to be at the center of the view.
10470                final float x = getWidth() / 2f;
10471                final float y = getHeight() / 2f;
10472                setPressed(true, x, y);
10473                checkForLongClick(0, x, y);
10474                return true;
10475            }
10476        }
10477
10478        return false;
10479    }
10480
10481    /**
10482     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
10483     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
10484     * the event).
10485     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10486     * although some may elect to do so in some situations. Do not rely on this to
10487     * catch software key presses.
10488     */
10489    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
10490        return false;
10491    }
10492
10493    /**
10494     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
10495     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
10496     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
10497     * or {@link KeyEvent#KEYCODE_SPACE} is released.
10498     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10499     * although some may elect to do so in some situations. Do not rely on this to
10500     * catch software key presses.
10501     *
10502     * @param keyCode A key code that represents the button pressed, from
10503     *                {@link android.view.KeyEvent}.
10504     * @param event   The KeyEvent object that defines the button action.
10505     */
10506    public boolean onKeyUp(int keyCode, KeyEvent event) {
10507        if (KeyEvent.isConfirmKey(keyCode)) {
10508            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10509                return true;
10510            }
10511            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
10512                setPressed(false);
10513
10514                if (!mHasPerformedLongPress) {
10515                    // This is a tap, so remove the longpress check
10516                    removeLongPressCallback();
10517                    return performClick();
10518                }
10519            }
10520        }
10521        return false;
10522    }
10523
10524    /**
10525     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
10526     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
10527     * the event).
10528     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10529     * although some may elect to do so in some situations. Do not rely on this to
10530     * catch software key presses.
10531     *
10532     * @param keyCode     A key code that represents the button pressed, from
10533     *                    {@link android.view.KeyEvent}.
10534     * @param repeatCount The number of times the action was made.
10535     * @param event       The KeyEvent object that defines the button action.
10536     */
10537    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
10538        return false;
10539    }
10540
10541    /**
10542     * Called on the focused view when a key shortcut event is not handled.
10543     * Override this method to implement local key shortcuts for the View.
10544     * Key shortcuts can also be implemented by setting the
10545     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
10546     *
10547     * @param keyCode The value in event.getKeyCode().
10548     * @param event Description of the key event.
10549     * @return If you handled the event, return true. If you want to allow the
10550     *         event to be handled by the next receiver, return false.
10551     */
10552    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
10553        return false;
10554    }
10555
10556    /**
10557     * Check whether the called view is a text editor, in which case it
10558     * would make sense to automatically display a soft input window for
10559     * it.  Subclasses should override this if they implement
10560     * {@link #onCreateInputConnection(EditorInfo)} to return true if
10561     * a call on that method would return a non-null InputConnection, and
10562     * they are really a first-class editor that the user would normally
10563     * start typing on when the go into a window containing your view.
10564     *
10565     * <p>The default implementation always returns false.  This does
10566     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
10567     * will not be called or the user can not otherwise perform edits on your
10568     * view; it is just a hint to the system that this is not the primary
10569     * purpose of this view.
10570     *
10571     * @return Returns true if this view is a text editor, else false.
10572     */
10573    public boolean onCheckIsTextEditor() {
10574        return false;
10575    }
10576
10577    /**
10578     * Create a new InputConnection for an InputMethod to interact
10579     * with the view.  The default implementation returns null, since it doesn't
10580     * support input methods.  You can override this to implement such support.
10581     * This is only needed for views that take focus and text input.
10582     *
10583     * <p>When implementing this, you probably also want to implement
10584     * {@link #onCheckIsTextEditor()} to indicate you will return a
10585     * non-null InputConnection.</p>
10586     *
10587     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
10588     * object correctly and in its entirety, so that the connected IME can rely
10589     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
10590     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
10591     * must be filled in with the correct cursor position for IMEs to work correctly
10592     * with your application.</p>
10593     *
10594     * @param outAttrs Fill in with attribute information about the connection.
10595     */
10596    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
10597        return null;
10598    }
10599
10600    /**
10601     * Called by the {@link android.view.inputmethod.InputMethodManager}
10602     * when a view who is not the current
10603     * input connection target is trying to make a call on the manager.  The
10604     * default implementation returns false; you can override this to return
10605     * true for certain views if you are performing InputConnection proxying
10606     * to them.
10607     * @param view The View that is making the InputMethodManager call.
10608     * @return Return true to allow the call, false to reject.
10609     */
10610    public boolean checkInputConnectionProxy(View view) {
10611        return false;
10612    }
10613
10614    /**
10615     * Show the context menu for this view. It is not safe to hold on to the
10616     * menu after returning from this method.
10617     *
10618     * You should normally not overload this method. Overload
10619     * {@link #onCreateContextMenu(ContextMenu)} or define an
10620     * {@link OnCreateContextMenuListener} to add items to the context menu.
10621     *
10622     * @param menu The context menu to populate
10623     */
10624    public void createContextMenu(ContextMenu menu) {
10625        ContextMenuInfo menuInfo = getContextMenuInfo();
10626
10627        // Sets the current menu info so all items added to menu will have
10628        // my extra info set.
10629        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10630
10631        onCreateContextMenu(menu);
10632        ListenerInfo li = mListenerInfo;
10633        if (li != null && li.mOnCreateContextMenuListener != null) {
10634            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10635        }
10636
10637        // Clear the extra information so subsequent items that aren't mine don't
10638        // have my extra info.
10639        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10640
10641        if (mParent != null) {
10642            mParent.createContextMenu(menu);
10643        }
10644    }
10645
10646    /**
10647     * Views should implement this if they have extra information to associate
10648     * with the context menu. The return result is supplied as a parameter to
10649     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10650     * callback.
10651     *
10652     * @return Extra information about the item for which the context menu
10653     *         should be shown. This information will vary across different
10654     *         subclasses of View.
10655     */
10656    protected ContextMenuInfo getContextMenuInfo() {
10657        return null;
10658    }
10659
10660    /**
10661     * Views should implement this if the view itself is going to add items to
10662     * the context menu.
10663     *
10664     * @param menu the context menu to populate
10665     */
10666    protected void onCreateContextMenu(ContextMenu menu) {
10667    }
10668
10669    /**
10670     * Implement this method to handle trackball motion events.  The
10671     * <em>relative</em> movement of the trackball since the last event
10672     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10673     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10674     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10675     * they will often be fractional values, representing the more fine-grained
10676     * movement information available from a trackball).
10677     *
10678     * @param event The motion event.
10679     * @return True if the event was handled, false otherwise.
10680     */
10681    public boolean onTrackballEvent(MotionEvent event) {
10682        return false;
10683    }
10684
10685    /**
10686     * Implement this method to handle generic motion events.
10687     * <p>
10688     * Generic motion events describe joystick movements, mouse hovers, track pad
10689     * touches, scroll wheel movements and other input events.  The
10690     * {@link MotionEvent#getSource() source} of the motion event specifies
10691     * the class of input that was received.  Implementations of this method
10692     * must examine the bits in the source before processing the event.
10693     * The following code example shows how this is done.
10694     * </p><p>
10695     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10696     * are delivered to the view under the pointer.  All other generic motion events are
10697     * delivered to the focused view.
10698     * </p>
10699     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10700     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10701     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10702     *             // process the joystick movement...
10703     *             return true;
10704     *         }
10705     *     }
10706     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10707     *         switch (event.getAction()) {
10708     *             case MotionEvent.ACTION_HOVER_MOVE:
10709     *                 // process the mouse hover movement...
10710     *                 return true;
10711     *             case MotionEvent.ACTION_SCROLL:
10712     *                 // process the scroll wheel movement...
10713     *                 return true;
10714     *         }
10715     *     }
10716     *     return super.onGenericMotionEvent(event);
10717     * }</pre>
10718     *
10719     * @param event The generic motion event being processed.
10720     * @return True if the event was handled, false otherwise.
10721     */
10722    public boolean onGenericMotionEvent(MotionEvent event) {
10723        return false;
10724    }
10725
10726    /**
10727     * Implement this method to handle hover events.
10728     * <p>
10729     * This method is called whenever a pointer is hovering into, over, or out of the
10730     * bounds of a view and the view is not currently being touched.
10731     * Hover events are represented as pointer events with action
10732     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10733     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10734     * </p>
10735     * <ul>
10736     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10737     * when the pointer enters the bounds of the view.</li>
10738     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10739     * when the pointer has already entered the bounds of the view and has moved.</li>
10740     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10741     * when the pointer has exited the bounds of the view or when the pointer is
10742     * about to go down due to a button click, tap, or similar user action that
10743     * causes the view to be touched.</li>
10744     * </ul>
10745     * <p>
10746     * The view should implement this method to return true to indicate that it is
10747     * handling the hover event, such as by changing its drawable state.
10748     * </p><p>
10749     * The default implementation calls {@link #setHovered} to update the hovered state
10750     * of the view when a hover enter or hover exit event is received, if the view
10751     * is enabled and is clickable.  The default implementation also sends hover
10752     * accessibility events.
10753     * </p>
10754     *
10755     * @param event The motion event that describes the hover.
10756     * @return True if the view handled the hover event.
10757     *
10758     * @see #isHovered
10759     * @see #setHovered
10760     * @see #onHoverChanged
10761     */
10762    public boolean onHoverEvent(MotionEvent event) {
10763        // The root view may receive hover (or touch) events that are outside the bounds of
10764        // the window.  This code ensures that we only send accessibility events for
10765        // hovers that are actually within the bounds of the root view.
10766        final int action = event.getActionMasked();
10767        if (!mSendingHoverAccessibilityEvents) {
10768            if ((action == MotionEvent.ACTION_HOVER_ENTER
10769                    || action == MotionEvent.ACTION_HOVER_MOVE)
10770                    && !hasHoveredChild()
10771                    && pointInView(event.getX(), event.getY())) {
10772                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10773                mSendingHoverAccessibilityEvents = true;
10774            }
10775        } else {
10776            if (action == MotionEvent.ACTION_HOVER_EXIT
10777                    || (action == MotionEvent.ACTION_MOVE
10778                            && !pointInView(event.getX(), event.getY()))) {
10779                mSendingHoverAccessibilityEvents = false;
10780                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10781            }
10782        }
10783
10784        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
10785                && event.isFromSource(InputDevice.SOURCE_MOUSE)
10786                && isOnScrollbar(event.getX(), event.getY())) {
10787            awakenScrollBars();
10788        }
10789        if (isHoverable()) {
10790            switch (action) {
10791                case MotionEvent.ACTION_HOVER_ENTER:
10792                    setHovered(true);
10793                    break;
10794                case MotionEvent.ACTION_HOVER_EXIT:
10795                    setHovered(false);
10796                    break;
10797            }
10798
10799            // Dispatch the event to onGenericMotionEvent before returning true.
10800            // This is to provide compatibility with existing applications that
10801            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10802            // break because of the new default handling for hoverable views
10803            // in onHoverEvent.
10804            // Note that onGenericMotionEvent will be called by default when
10805            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10806            dispatchGenericMotionEventInternal(event);
10807            // The event was already handled by calling setHovered(), so always
10808            // return true.
10809            return true;
10810        }
10811
10812        return false;
10813    }
10814
10815    /**
10816     * Returns true if the view should handle {@link #onHoverEvent}
10817     * by calling {@link #setHovered} to change its hovered state.
10818     *
10819     * @return True if the view is hoverable.
10820     */
10821    private boolean isHoverable() {
10822        final int viewFlags = mViewFlags;
10823        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10824            return false;
10825        }
10826
10827        return (viewFlags & CLICKABLE) == CLICKABLE
10828                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10829                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10830    }
10831
10832    /**
10833     * Returns true if the view is currently hovered.
10834     *
10835     * @return True if the view is currently hovered.
10836     *
10837     * @see #setHovered
10838     * @see #onHoverChanged
10839     */
10840    @ViewDebug.ExportedProperty
10841    public boolean isHovered() {
10842        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10843    }
10844
10845    /**
10846     * Sets whether the view is currently hovered.
10847     * <p>
10848     * Calling this method also changes the drawable state of the view.  This
10849     * enables the view to react to hover by using different drawable resources
10850     * to change its appearance.
10851     * </p><p>
10852     * The {@link #onHoverChanged} method is called when the hovered state changes.
10853     * </p>
10854     *
10855     * @param hovered True if the view is hovered.
10856     *
10857     * @see #isHovered
10858     * @see #onHoverChanged
10859     */
10860    public void setHovered(boolean hovered) {
10861        if (hovered) {
10862            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
10863                mPrivateFlags |= PFLAG_HOVERED;
10864                refreshDrawableState();
10865                onHoverChanged(true);
10866            }
10867        } else {
10868            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
10869                mPrivateFlags &= ~PFLAG_HOVERED;
10870                refreshDrawableState();
10871                onHoverChanged(false);
10872            }
10873        }
10874    }
10875
10876    /**
10877     * Implement this method to handle hover state changes.
10878     * <p>
10879     * This method is called whenever the hover state changes as a result of a
10880     * call to {@link #setHovered}.
10881     * </p>
10882     *
10883     * @param hovered The current hover state, as returned by {@link #isHovered}.
10884     *
10885     * @see #isHovered
10886     * @see #setHovered
10887     */
10888    public void onHoverChanged(boolean hovered) {
10889    }
10890
10891    /**
10892     * Handles scroll bar dragging by mouse input.
10893     *
10894     * @hide
10895     * @param event The motion event.
10896     *
10897     * @return true if the event was handled as a scroll bar dragging, false otherwise.
10898     */
10899    protected boolean handleScrollBarDragging(MotionEvent event) {
10900        if (mScrollCache == null) {
10901            return false;
10902        }
10903        final float x = event.getX();
10904        final float y = event.getY();
10905        final int action = event.getAction();
10906        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
10907                && action != MotionEvent.ACTION_DOWN)
10908                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
10909                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
10910            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
10911            return false;
10912        }
10913
10914        switch (action) {
10915            case MotionEvent.ACTION_MOVE:
10916                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
10917                    return false;
10918                }
10919                if (mScrollCache.mScrollBarDraggingState
10920                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
10921                    final Rect bounds = mScrollCache.mScrollBarBounds;
10922                    getVerticalScrollBarBounds(bounds);
10923                    final int range = computeVerticalScrollRange();
10924                    final int offset = computeVerticalScrollOffset();
10925                    final int extent = computeVerticalScrollExtent();
10926
10927                    final int thumbLength = ScrollBarUtils.getThumbLength(
10928                            bounds.height(), bounds.width(), extent, range);
10929                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
10930                            bounds.height(), thumbLength, extent, range, offset);
10931
10932                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
10933                    final float maxThumbOffset = bounds.height() - thumbLength;
10934                    final float newThumbOffset =
10935                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
10936                    final int height = getHeight();
10937                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
10938                            && height > 0 && extent > 0) {
10939                        final int newY = Math.round((range - extent)
10940                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
10941                        if (newY != getScrollY()) {
10942                            mScrollCache.mScrollBarDraggingPos = y;
10943                            setScrollY(newY);
10944                        }
10945                    }
10946                    return true;
10947                }
10948                if (mScrollCache.mScrollBarDraggingState
10949                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
10950                    final Rect bounds = mScrollCache.mScrollBarBounds;
10951                    getHorizontalScrollBarBounds(bounds);
10952                    final int range = computeHorizontalScrollRange();
10953                    final int offset = computeHorizontalScrollOffset();
10954                    final int extent = computeHorizontalScrollExtent();
10955
10956                    final int thumbLength = ScrollBarUtils.getThumbLength(
10957                            bounds.width(), bounds.height(), extent, range);
10958                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
10959                            bounds.width(), thumbLength, extent, range, offset);
10960
10961                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
10962                    final float maxThumbOffset = bounds.width() - thumbLength;
10963                    final float newThumbOffset =
10964                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
10965                    final int width = getWidth();
10966                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
10967                            && width > 0 && extent > 0) {
10968                        final int newX = Math.round((range - extent)
10969                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
10970                        if (newX != getScrollX()) {
10971                            mScrollCache.mScrollBarDraggingPos = x;
10972                            setScrollX(newX);
10973                        }
10974                    }
10975                    return true;
10976                }
10977            case MotionEvent.ACTION_DOWN:
10978                if (mScrollCache.state == ScrollabilityCache.OFF) {
10979                    return false;
10980                }
10981                if (isOnVerticalScrollbarThumb(x, y)) {
10982                    mScrollCache.mScrollBarDraggingState =
10983                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
10984                    mScrollCache.mScrollBarDraggingPos = y;
10985                    return true;
10986                }
10987                if (isOnHorizontalScrollbarThumb(x, y)) {
10988                    mScrollCache.mScrollBarDraggingState =
10989                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
10990                    mScrollCache.mScrollBarDraggingPos = x;
10991                    return true;
10992                }
10993        }
10994        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
10995        return false;
10996    }
10997
10998    /**
10999     * Implement this method to handle touch screen motion events.
11000     * <p>
11001     * If this method is used to detect click actions, it is recommended that
11002     * the actions be performed by implementing and calling
11003     * {@link #performClick()}. This will ensure consistent system behavior,
11004     * including:
11005     * <ul>
11006     * <li>obeying click sound preferences
11007     * <li>dispatching OnClickListener calls
11008     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11009     * accessibility features are enabled
11010     * </ul>
11011     *
11012     * @param event The motion event.
11013     * @return True if the event was handled, false otherwise.
11014     */
11015    public boolean onTouchEvent(MotionEvent event) {
11016        final float x = event.getX();
11017        final float y = event.getY();
11018        final int viewFlags = mViewFlags;
11019        final int action = event.getAction();
11020
11021        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11022            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11023                setPressed(false);
11024            }
11025            // A disabled view that is clickable still consumes the touch
11026            // events, it just doesn't respond to them.
11027            return (((viewFlags & CLICKABLE) == CLICKABLE
11028                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11029                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
11030        }
11031        if (mTouchDelegate != null) {
11032            if (mTouchDelegate.onTouchEvent(event)) {
11033                return true;
11034            }
11035        }
11036
11037        if (((viewFlags & CLICKABLE) == CLICKABLE ||
11038                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
11039                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
11040            switch (action) {
11041                case MotionEvent.ACTION_UP:
11042                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11043                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11044                        // take focus if we don't have it already and we should in
11045                        // touch mode.
11046                        boolean focusTaken = false;
11047                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11048                            focusTaken = requestFocus();
11049                        }
11050
11051                        if (prepressed) {
11052                            // The button is being released before we actually
11053                            // showed it as pressed.  Make it show the pressed
11054                            // state now (before scheduling the click) to ensure
11055                            // the user sees it.
11056                            setPressed(true, x, y);
11057                       }
11058
11059                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11060                            // This is a tap, so remove the longpress check
11061                            removeLongPressCallback();
11062
11063                            // Only perform take click actions if we were in the pressed state
11064                            if (!focusTaken) {
11065                                // Use a Runnable and post this rather than calling
11066                                // performClick directly. This lets other visual state
11067                                // of the view update before click actions start.
11068                                if (mPerformClick == null) {
11069                                    mPerformClick = new PerformClick();
11070                                }
11071                                if (!post(mPerformClick)) {
11072                                    performClick();
11073                                }
11074                            }
11075                        }
11076
11077                        if (mUnsetPressedState == null) {
11078                            mUnsetPressedState = new UnsetPressedState();
11079                        }
11080
11081                        if (prepressed) {
11082                            postDelayed(mUnsetPressedState,
11083                                    ViewConfiguration.getPressedStateDuration());
11084                        } else if (!post(mUnsetPressedState)) {
11085                            // If the post failed, unpress right now
11086                            mUnsetPressedState.run();
11087                        }
11088
11089                        removeTapCallback();
11090                    }
11091                    mIgnoreNextUpEvent = false;
11092                    break;
11093
11094                case MotionEvent.ACTION_DOWN:
11095                    mHasPerformedLongPress = false;
11096
11097                    if (performButtonActionOnTouchDown(event)) {
11098                        break;
11099                    }
11100
11101                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11102                    boolean isInScrollingContainer = isInScrollingContainer();
11103
11104                    // For views inside a scrolling container, delay the pressed feedback for
11105                    // a short period in case this is a scroll.
11106                    if (isInScrollingContainer) {
11107                        mPrivateFlags |= PFLAG_PREPRESSED;
11108                        if (mPendingCheckForTap == null) {
11109                            mPendingCheckForTap = new CheckForTap();
11110                        }
11111                        mPendingCheckForTap.x = event.getX();
11112                        mPendingCheckForTap.y = event.getY();
11113                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11114                    } else {
11115                        // Not inside a scrolling container, so show the feedback right away
11116                        setPressed(true, x, y);
11117                        checkForLongClick(0, x, y);
11118                    }
11119                    break;
11120
11121                case MotionEvent.ACTION_CANCEL:
11122                    setPressed(false);
11123                    removeTapCallback();
11124                    removeLongPressCallback();
11125                    mInContextButtonPress = false;
11126                    mHasPerformedLongPress = false;
11127                    mIgnoreNextUpEvent = false;
11128                    break;
11129
11130                case MotionEvent.ACTION_MOVE:
11131                    drawableHotspotChanged(x, y);
11132
11133                    // Be lenient about moving outside of buttons
11134                    if (!pointInView(x, y, mTouchSlop)) {
11135                        // Outside button
11136                        removeTapCallback();
11137                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11138                            // Remove any future long press/tap checks
11139                            removeLongPressCallback();
11140
11141                            setPressed(false);
11142                        }
11143                    }
11144                    break;
11145            }
11146
11147            return true;
11148        }
11149
11150        return false;
11151    }
11152
11153    /**
11154     * @hide
11155     */
11156    public boolean isInScrollingContainer() {
11157        ViewParent p = getParent();
11158        while (p != null && p instanceof ViewGroup) {
11159            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11160                return true;
11161            }
11162            p = p.getParent();
11163        }
11164        return false;
11165    }
11166
11167    /**
11168     * Remove the longpress detection timer.
11169     */
11170    private void removeLongPressCallback() {
11171        if (mPendingCheckForLongPress != null) {
11172          removeCallbacks(mPendingCheckForLongPress);
11173        }
11174    }
11175
11176    /**
11177     * Remove the pending click action
11178     */
11179    private void removePerformClickCallback() {
11180        if (mPerformClick != null) {
11181            removeCallbacks(mPerformClick);
11182        }
11183    }
11184
11185    /**
11186     * Remove the prepress detection timer.
11187     */
11188    private void removeUnsetPressCallback() {
11189        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11190            setPressed(false);
11191            removeCallbacks(mUnsetPressedState);
11192        }
11193    }
11194
11195    /**
11196     * Remove the tap detection timer.
11197     */
11198    private void removeTapCallback() {
11199        if (mPendingCheckForTap != null) {
11200            mPrivateFlags &= ~PFLAG_PREPRESSED;
11201            removeCallbacks(mPendingCheckForTap);
11202        }
11203    }
11204
11205    /**
11206     * Cancels a pending long press.  Your subclass can use this if you
11207     * want the context menu to come up if the user presses and holds
11208     * at the same place, but you don't want it to come up if they press
11209     * and then move around enough to cause scrolling.
11210     */
11211    public void cancelLongPress() {
11212        removeLongPressCallback();
11213
11214        /*
11215         * The prepressed state handled by the tap callback is a display
11216         * construct, but the tap callback will post a long press callback
11217         * less its own timeout. Remove it here.
11218         */
11219        removeTapCallback();
11220    }
11221
11222    /**
11223     * Remove the pending callback for sending a
11224     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11225     */
11226    private void removeSendViewScrolledAccessibilityEventCallback() {
11227        if (mSendViewScrolledAccessibilityEvent != null) {
11228            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11229            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11230        }
11231    }
11232
11233    /**
11234     * Sets the TouchDelegate for this View.
11235     */
11236    public void setTouchDelegate(TouchDelegate delegate) {
11237        mTouchDelegate = delegate;
11238    }
11239
11240    /**
11241     * Gets the TouchDelegate for this View.
11242     */
11243    public TouchDelegate getTouchDelegate() {
11244        return mTouchDelegate;
11245    }
11246
11247    /**
11248     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11249     *
11250     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11251     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11252     * available. This method should only be called for touch events.
11253     *
11254     * <p class="note">This api is not intended for most applications. Buffered dispatch
11255     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11256     * streams will not improve your input latency. Side effects include: increased latency,
11257     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11258     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11259     * you.</p>
11260     */
11261    public final void requestUnbufferedDispatch(MotionEvent event) {
11262        final int action = event.getAction();
11263        if (mAttachInfo == null
11264                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
11265                || !event.isTouchEvent()) {
11266            return;
11267        }
11268        mAttachInfo.mUnbufferedDispatchRequested = true;
11269    }
11270
11271    /**
11272     * Set flags controlling behavior of this view.
11273     *
11274     * @param flags Constant indicating the value which should be set
11275     * @param mask Constant indicating the bit range that should be changed
11276     */
11277    void setFlags(int flags, int mask) {
11278        final boolean accessibilityEnabled =
11279                AccessibilityManager.getInstance(mContext).isEnabled();
11280        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
11281
11282        int old = mViewFlags;
11283        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
11284
11285        int changed = mViewFlags ^ old;
11286        if (changed == 0) {
11287            return;
11288        }
11289        int privateFlags = mPrivateFlags;
11290
11291        /* Check if the FOCUSABLE bit has changed */
11292        if (((changed & FOCUSABLE_MASK) != 0) &&
11293                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
11294            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
11295                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
11296                /* Give up focus if we are no longer focusable */
11297                clearFocus();
11298            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
11299                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
11300                /*
11301                 * Tell the view system that we are now available to take focus
11302                 * if no one else already has it.
11303                 */
11304                if (mParent != null) mParent.focusableViewAvailable(this);
11305            }
11306        }
11307
11308        final int newVisibility = flags & VISIBILITY_MASK;
11309        if (newVisibility == VISIBLE) {
11310            if ((changed & VISIBILITY_MASK) != 0) {
11311                /*
11312                 * If this view is becoming visible, invalidate it in case it changed while
11313                 * it was not visible. Marking it drawn ensures that the invalidation will
11314                 * go through.
11315                 */
11316                mPrivateFlags |= PFLAG_DRAWN;
11317                invalidate(true);
11318
11319                needGlobalAttributesUpdate(true);
11320
11321                // a view becoming visible is worth notifying the parent
11322                // about in case nothing has focus.  even if this specific view
11323                // isn't focusable, it may contain something that is, so let
11324                // the root view try to give this focus if nothing else does.
11325                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
11326                    mParent.focusableViewAvailable(this);
11327                }
11328            }
11329        }
11330
11331        /* Check if the GONE bit has changed */
11332        if ((changed & GONE) != 0) {
11333            needGlobalAttributesUpdate(false);
11334            requestLayout();
11335
11336            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
11337                if (hasFocus()) clearFocus();
11338                clearAccessibilityFocus();
11339                destroyDrawingCache();
11340                if (mParent instanceof View) {
11341                    // GONE views noop invalidation, so invalidate the parent
11342                    ((View) mParent).invalidate(true);
11343                }
11344                // Mark the view drawn to ensure that it gets invalidated properly the next
11345                // time it is visible and gets invalidated
11346                mPrivateFlags |= PFLAG_DRAWN;
11347            }
11348            if (mAttachInfo != null) {
11349                mAttachInfo.mViewVisibilityChanged = true;
11350            }
11351        }
11352
11353        /* Check if the VISIBLE bit has changed */
11354        if ((changed & INVISIBLE) != 0) {
11355            needGlobalAttributesUpdate(false);
11356            /*
11357             * If this view is becoming invisible, set the DRAWN flag so that
11358             * the next invalidate() will not be skipped.
11359             */
11360            mPrivateFlags |= PFLAG_DRAWN;
11361
11362            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
11363                // root view becoming invisible shouldn't clear focus and accessibility focus
11364                if (getRootView() != this) {
11365                    if (hasFocus()) clearFocus();
11366                    clearAccessibilityFocus();
11367                }
11368            }
11369            if (mAttachInfo != null) {
11370                mAttachInfo.mViewVisibilityChanged = true;
11371            }
11372        }
11373
11374        if ((changed & VISIBILITY_MASK) != 0) {
11375            // If the view is invisible, cleanup its display list to free up resources
11376            if (newVisibility != VISIBLE && mAttachInfo != null) {
11377                cleanupDraw();
11378            }
11379
11380            if (mParent instanceof ViewGroup) {
11381                ((ViewGroup) mParent).onChildVisibilityChanged(this,
11382                        (changed & VISIBILITY_MASK), newVisibility);
11383                ((View) mParent).invalidate(true);
11384            } else if (mParent != null) {
11385                mParent.invalidateChild(this, null);
11386            }
11387
11388            if (mAttachInfo != null) {
11389                dispatchVisibilityChanged(this, newVisibility);
11390
11391                // Aggregated visibility changes are dispatched to attached views
11392                // in visible windows where the parent is currently shown/drawn
11393                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
11394                // discounting clipping or overlapping. This makes it a good place
11395                // to change animation states.
11396                if (mParent != null && getWindowVisibility() == VISIBLE &&
11397                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
11398                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
11399                }
11400                notifySubtreeAccessibilityStateChangedIfNeeded();
11401            }
11402        }
11403
11404        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
11405            destroyDrawingCache();
11406        }
11407
11408        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
11409            destroyDrawingCache();
11410            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11411            invalidateParentCaches();
11412        }
11413
11414        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
11415            destroyDrawingCache();
11416            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11417        }
11418
11419        if ((changed & DRAW_MASK) != 0) {
11420            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
11421                if (mBackground != null
11422                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
11423                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11424                } else {
11425                    mPrivateFlags |= PFLAG_SKIP_DRAW;
11426                }
11427            } else {
11428                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11429            }
11430            requestLayout();
11431            invalidate(true);
11432        }
11433
11434        if ((changed & KEEP_SCREEN_ON) != 0) {
11435            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11436                mParent.recomputeViewAttributes(this);
11437            }
11438        }
11439
11440        if (accessibilityEnabled) {
11441            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
11442                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
11443                    || (changed & CONTEXT_CLICKABLE) != 0) {
11444                if (oldIncludeForAccessibility != includeForAccessibility()) {
11445                    notifySubtreeAccessibilityStateChangedIfNeeded();
11446                } else {
11447                    notifyViewAccessibilityStateChangedIfNeeded(
11448                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11449                }
11450            } else if ((changed & ENABLED_MASK) != 0) {
11451                notifyViewAccessibilityStateChangedIfNeeded(
11452                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11453            }
11454        }
11455    }
11456
11457    /**
11458     * Change the view's z order in the tree, so it's on top of other sibling
11459     * views. This ordering change may affect layout, if the parent container
11460     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
11461     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
11462     * method should be followed by calls to {@link #requestLayout()} and
11463     * {@link View#invalidate()} on the view's parent to force the parent to redraw
11464     * with the new child ordering.
11465     *
11466     * @see ViewGroup#bringChildToFront(View)
11467     */
11468    public void bringToFront() {
11469        if (mParent != null) {
11470            mParent.bringChildToFront(this);
11471        }
11472    }
11473
11474    /**
11475     * This is called in response to an internal scroll in this view (i.e., the
11476     * view scrolled its own contents). This is typically as a result of
11477     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
11478     * called.
11479     *
11480     * @param l Current horizontal scroll origin.
11481     * @param t Current vertical scroll origin.
11482     * @param oldl Previous horizontal scroll origin.
11483     * @param oldt Previous vertical scroll origin.
11484     */
11485    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
11486        notifySubtreeAccessibilityStateChangedIfNeeded();
11487
11488        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11489            postSendViewScrolledAccessibilityEventCallback();
11490        }
11491
11492        mBackgroundSizeChanged = true;
11493        if (mForegroundInfo != null) {
11494            mForegroundInfo.mBoundsChanged = true;
11495        }
11496
11497        final AttachInfo ai = mAttachInfo;
11498        if (ai != null) {
11499            ai.mViewScrollChanged = true;
11500        }
11501
11502        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
11503            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
11504        }
11505    }
11506
11507    /**
11508     * Interface definition for a callback to be invoked when the scroll
11509     * X or Y positions of a view change.
11510     * <p>
11511     * <b>Note:</b> Some views handle scrolling independently from View and may
11512     * have their own separate listeners for scroll-type events. For example,
11513     * {@link android.widget.ListView ListView} allows clients to register an
11514     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
11515     * to listen for changes in list scroll position.
11516     *
11517     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
11518     */
11519    public interface OnScrollChangeListener {
11520        /**
11521         * Called when the scroll position of a view changes.
11522         *
11523         * @param v The view whose scroll position has changed.
11524         * @param scrollX Current horizontal scroll origin.
11525         * @param scrollY Current vertical scroll origin.
11526         * @param oldScrollX Previous horizontal scroll origin.
11527         * @param oldScrollY Previous vertical scroll origin.
11528         */
11529        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
11530    }
11531
11532    /**
11533     * Interface definition for a callback to be invoked when the layout bounds of a view
11534     * changes due to layout processing.
11535     */
11536    public interface OnLayoutChangeListener {
11537        /**
11538         * Called when the layout bounds of a view changes due to layout processing.
11539         *
11540         * @param v The view whose bounds have changed.
11541         * @param left The new value of the view's left property.
11542         * @param top The new value of the view's top property.
11543         * @param right The new value of the view's right property.
11544         * @param bottom The new value of the view's bottom property.
11545         * @param oldLeft The previous value of the view's left property.
11546         * @param oldTop The previous value of the view's top property.
11547         * @param oldRight The previous value of the view's right property.
11548         * @param oldBottom The previous value of the view's bottom property.
11549         */
11550        void onLayoutChange(View v, int left, int top, int right, int bottom,
11551            int oldLeft, int oldTop, int oldRight, int oldBottom);
11552    }
11553
11554    /**
11555     * This is called during layout when the size of this view has changed. If
11556     * you were just added to the view hierarchy, you're called with the old
11557     * values of 0.
11558     *
11559     * @param w Current width of this view.
11560     * @param h Current height of this view.
11561     * @param oldw Old width of this view.
11562     * @param oldh Old height of this view.
11563     */
11564    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
11565    }
11566
11567    /**
11568     * Called by draw to draw the child views. This may be overridden
11569     * by derived classes to gain control just before its children are drawn
11570     * (but after its own view has been drawn).
11571     * @param canvas the canvas on which to draw the view
11572     */
11573    protected void dispatchDraw(Canvas canvas) {
11574
11575    }
11576
11577    /**
11578     * Gets the parent of this view. Note that the parent is a
11579     * ViewParent and not necessarily a View.
11580     *
11581     * @return Parent of this view.
11582     */
11583    public final ViewParent getParent() {
11584        return mParent;
11585    }
11586
11587    /**
11588     * Set the horizontal scrolled position of your view. This will cause a call to
11589     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11590     * invalidated.
11591     * @param value the x position to scroll to
11592     */
11593    public void setScrollX(int value) {
11594        scrollTo(value, mScrollY);
11595    }
11596
11597    /**
11598     * Set the vertical scrolled position of your view. This will cause a call to
11599     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11600     * invalidated.
11601     * @param value the y position to scroll to
11602     */
11603    public void setScrollY(int value) {
11604        scrollTo(mScrollX, value);
11605    }
11606
11607    /**
11608     * Return the scrolled left position of this view. This is the left edge of
11609     * the displayed part of your view. You do not need to draw any pixels
11610     * farther left, since those are outside of the frame of your view on
11611     * screen.
11612     *
11613     * @return The left edge of the displayed part of your view, in pixels.
11614     */
11615    public final int getScrollX() {
11616        return mScrollX;
11617    }
11618
11619    /**
11620     * Return the scrolled top position of this view. This is the top edge of
11621     * the displayed part of your view. You do not need to draw any pixels above
11622     * it, since those are outside of the frame of your view on screen.
11623     *
11624     * @return The top edge of the displayed part of your view, in pixels.
11625     */
11626    public final int getScrollY() {
11627        return mScrollY;
11628    }
11629
11630    /**
11631     * Return the width of the your view.
11632     *
11633     * @return The width of your view, in pixels.
11634     */
11635    @ViewDebug.ExportedProperty(category = "layout")
11636    public final int getWidth() {
11637        return mRight - mLeft;
11638    }
11639
11640    /**
11641     * Return the height of your view.
11642     *
11643     * @return The height of your view, in pixels.
11644     */
11645    @ViewDebug.ExportedProperty(category = "layout")
11646    public final int getHeight() {
11647        return mBottom - mTop;
11648    }
11649
11650    /**
11651     * Return the visible drawing bounds of your view. Fills in the output
11652     * rectangle with the values from getScrollX(), getScrollY(),
11653     * getWidth(), and getHeight(). These bounds do not account for any
11654     * transformation properties currently set on the view, such as
11655     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
11656     *
11657     * @param outRect The (scrolled) drawing bounds of the view.
11658     */
11659    public void getDrawingRect(Rect outRect) {
11660        outRect.left = mScrollX;
11661        outRect.top = mScrollY;
11662        outRect.right = mScrollX + (mRight - mLeft);
11663        outRect.bottom = mScrollY + (mBottom - mTop);
11664    }
11665
11666    /**
11667     * Like {@link #getMeasuredWidthAndState()}, but only returns the
11668     * raw width component (that is the result is masked by
11669     * {@link #MEASURED_SIZE_MASK}).
11670     *
11671     * @return The raw measured width of this view.
11672     */
11673    public final int getMeasuredWidth() {
11674        return mMeasuredWidth & MEASURED_SIZE_MASK;
11675    }
11676
11677    /**
11678     * Return the full width measurement information for this view as computed
11679     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11680     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11681     * This should be used during measurement and layout calculations only. Use
11682     * {@link #getWidth()} to see how wide a view is after layout.
11683     *
11684     * @return The measured width of this view as a bit mask.
11685     */
11686    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11687            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11688                    name = "MEASURED_STATE_TOO_SMALL"),
11689    })
11690    public final int getMeasuredWidthAndState() {
11691        return mMeasuredWidth;
11692    }
11693
11694    /**
11695     * Like {@link #getMeasuredHeightAndState()}, but only returns the
11696     * raw height component (that is the result is masked by
11697     * {@link #MEASURED_SIZE_MASK}).
11698     *
11699     * @return The raw measured height of this view.
11700     */
11701    public final int getMeasuredHeight() {
11702        return mMeasuredHeight & MEASURED_SIZE_MASK;
11703    }
11704
11705    /**
11706     * Return the full height measurement information for this view as computed
11707     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11708     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11709     * This should be used during measurement and layout calculations only. Use
11710     * {@link #getHeight()} to see how wide a view is after layout.
11711     *
11712     * @return The measured height of this view as a bit mask.
11713     */
11714    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11715            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11716                    name = "MEASURED_STATE_TOO_SMALL"),
11717    })
11718    public final int getMeasuredHeightAndState() {
11719        return mMeasuredHeight;
11720    }
11721
11722    /**
11723     * Return only the state bits of {@link #getMeasuredWidthAndState()}
11724     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
11725     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
11726     * and the height component is at the shifted bits
11727     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
11728     */
11729    public final int getMeasuredState() {
11730        return (mMeasuredWidth&MEASURED_STATE_MASK)
11731                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
11732                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
11733    }
11734
11735    /**
11736     * The transform matrix of this view, which is calculated based on the current
11737     * rotation, scale, and pivot properties.
11738     *
11739     * @see #getRotation()
11740     * @see #getScaleX()
11741     * @see #getScaleY()
11742     * @see #getPivotX()
11743     * @see #getPivotY()
11744     * @return The current transform matrix for the view
11745     */
11746    public Matrix getMatrix() {
11747        ensureTransformationInfo();
11748        final Matrix matrix = mTransformationInfo.mMatrix;
11749        mRenderNode.getMatrix(matrix);
11750        return matrix;
11751    }
11752
11753    /**
11754     * Returns true if the transform matrix is the identity matrix.
11755     * Recomputes the matrix if necessary.
11756     *
11757     * @return True if the transform matrix is the identity matrix, false otherwise.
11758     */
11759    final boolean hasIdentityMatrix() {
11760        return mRenderNode.hasIdentityMatrix();
11761    }
11762
11763    void ensureTransformationInfo() {
11764        if (mTransformationInfo == null) {
11765            mTransformationInfo = new TransformationInfo();
11766        }
11767    }
11768
11769    /**
11770     * Utility method to retrieve the inverse of the current mMatrix property.
11771     * We cache the matrix to avoid recalculating it when transform properties
11772     * have not changed.
11773     *
11774     * @return The inverse of the current matrix of this view.
11775     * @hide
11776     */
11777    public final Matrix getInverseMatrix() {
11778        ensureTransformationInfo();
11779        if (mTransformationInfo.mInverseMatrix == null) {
11780            mTransformationInfo.mInverseMatrix = new Matrix();
11781        }
11782        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11783        mRenderNode.getInverseMatrix(matrix);
11784        return matrix;
11785    }
11786
11787    /**
11788     * Gets the distance along the Z axis from the camera to this view.
11789     *
11790     * @see #setCameraDistance(float)
11791     *
11792     * @return The distance along the Z axis.
11793     */
11794    public float getCameraDistance() {
11795        final float dpi = mResources.getDisplayMetrics().densityDpi;
11796        return -(mRenderNode.getCameraDistance() * dpi);
11797    }
11798
11799    /**
11800     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11801     * views are drawn) from the camera to this view. The camera's distance
11802     * affects 3D transformations, for instance rotations around the X and Y
11803     * axis. If the rotationX or rotationY properties are changed and this view is
11804     * large (more than half the size of the screen), it is recommended to always
11805     * use a camera distance that's greater than the height (X axis rotation) or
11806     * the width (Y axis rotation) of this view.</p>
11807     *
11808     * <p>The distance of the camera from the view plane can have an affect on the
11809     * perspective distortion of the view when it is rotated around the x or y axis.
11810     * For example, a large distance will result in a large viewing angle, and there
11811     * will not be much perspective distortion of the view as it rotates. A short
11812     * distance may cause much more perspective distortion upon rotation, and can
11813     * also result in some drawing artifacts if the rotated view ends up partially
11814     * behind the camera (which is why the recommendation is to use a distance at
11815     * least as far as the size of the view, if the view is to be rotated.)</p>
11816     *
11817     * <p>The distance is expressed in "depth pixels." The default distance depends
11818     * on the screen density. For instance, on a medium density display, the
11819     * default distance is 1280. On a high density display, the default distance
11820     * is 1920.</p>
11821     *
11822     * <p>If you want to specify a distance that leads to visually consistent
11823     * results across various densities, use the following formula:</p>
11824     * <pre>
11825     * float scale = context.getResources().getDisplayMetrics().density;
11826     * view.setCameraDistance(distance * scale);
11827     * </pre>
11828     *
11829     * <p>The density scale factor of a high density display is 1.5,
11830     * and 1920 = 1280 * 1.5.</p>
11831     *
11832     * @param distance The distance in "depth pixels", if negative the opposite
11833     *        value is used
11834     *
11835     * @see #setRotationX(float)
11836     * @see #setRotationY(float)
11837     */
11838    public void setCameraDistance(float distance) {
11839        final float dpi = mResources.getDisplayMetrics().densityDpi;
11840
11841        invalidateViewProperty(true, false);
11842        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11843        invalidateViewProperty(false, false);
11844
11845        invalidateParentIfNeededAndWasQuickRejected();
11846    }
11847
11848    /**
11849     * The degrees that the view is rotated around the pivot point.
11850     *
11851     * @see #setRotation(float)
11852     * @see #getPivotX()
11853     * @see #getPivotY()
11854     *
11855     * @return The degrees of rotation.
11856     */
11857    @ViewDebug.ExportedProperty(category = "drawing")
11858    public float getRotation() {
11859        return mRenderNode.getRotation();
11860    }
11861
11862    /**
11863     * Sets the degrees that the view is rotated around the pivot point. Increasing values
11864     * result in clockwise rotation.
11865     *
11866     * @param rotation The degrees of rotation.
11867     *
11868     * @see #getRotation()
11869     * @see #getPivotX()
11870     * @see #getPivotY()
11871     * @see #setRotationX(float)
11872     * @see #setRotationY(float)
11873     *
11874     * @attr ref android.R.styleable#View_rotation
11875     */
11876    public void setRotation(float rotation) {
11877        if (rotation != getRotation()) {
11878            // Double-invalidation is necessary to capture view's old and new areas
11879            invalidateViewProperty(true, false);
11880            mRenderNode.setRotation(rotation);
11881            invalidateViewProperty(false, true);
11882
11883            invalidateParentIfNeededAndWasQuickRejected();
11884            notifySubtreeAccessibilityStateChangedIfNeeded();
11885        }
11886    }
11887
11888    /**
11889     * The degrees that the view is rotated around the vertical axis through the pivot point.
11890     *
11891     * @see #getPivotX()
11892     * @see #getPivotY()
11893     * @see #setRotationY(float)
11894     *
11895     * @return The degrees of Y rotation.
11896     */
11897    @ViewDebug.ExportedProperty(category = "drawing")
11898    public float getRotationY() {
11899        return mRenderNode.getRotationY();
11900    }
11901
11902    /**
11903     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
11904     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
11905     * down the y axis.
11906     *
11907     * When rotating large views, it is recommended to adjust the camera distance
11908     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11909     *
11910     * @param rotationY The degrees of Y rotation.
11911     *
11912     * @see #getRotationY()
11913     * @see #getPivotX()
11914     * @see #getPivotY()
11915     * @see #setRotation(float)
11916     * @see #setRotationX(float)
11917     * @see #setCameraDistance(float)
11918     *
11919     * @attr ref android.R.styleable#View_rotationY
11920     */
11921    public void setRotationY(float rotationY) {
11922        if (rotationY != getRotationY()) {
11923            invalidateViewProperty(true, false);
11924            mRenderNode.setRotationY(rotationY);
11925            invalidateViewProperty(false, true);
11926
11927            invalidateParentIfNeededAndWasQuickRejected();
11928            notifySubtreeAccessibilityStateChangedIfNeeded();
11929        }
11930    }
11931
11932    /**
11933     * The degrees that the view is rotated around the horizontal axis through the pivot point.
11934     *
11935     * @see #getPivotX()
11936     * @see #getPivotY()
11937     * @see #setRotationX(float)
11938     *
11939     * @return The degrees of X rotation.
11940     */
11941    @ViewDebug.ExportedProperty(category = "drawing")
11942    public float getRotationX() {
11943        return mRenderNode.getRotationX();
11944    }
11945
11946    /**
11947     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
11948     * Increasing values result in clockwise rotation from the viewpoint of looking down the
11949     * x axis.
11950     *
11951     * When rotating large views, it is recommended to adjust the camera distance
11952     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11953     *
11954     * @param rotationX The degrees of X rotation.
11955     *
11956     * @see #getRotationX()
11957     * @see #getPivotX()
11958     * @see #getPivotY()
11959     * @see #setRotation(float)
11960     * @see #setRotationY(float)
11961     * @see #setCameraDistance(float)
11962     *
11963     * @attr ref android.R.styleable#View_rotationX
11964     */
11965    public void setRotationX(float rotationX) {
11966        if (rotationX != getRotationX()) {
11967            invalidateViewProperty(true, false);
11968            mRenderNode.setRotationX(rotationX);
11969            invalidateViewProperty(false, true);
11970
11971            invalidateParentIfNeededAndWasQuickRejected();
11972            notifySubtreeAccessibilityStateChangedIfNeeded();
11973        }
11974    }
11975
11976    /**
11977     * The amount that the view is scaled in x around the pivot point, as a proportion of
11978     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
11979     *
11980     * <p>By default, this is 1.0f.
11981     *
11982     * @see #getPivotX()
11983     * @see #getPivotY()
11984     * @return The scaling factor.
11985     */
11986    @ViewDebug.ExportedProperty(category = "drawing")
11987    public float getScaleX() {
11988        return mRenderNode.getScaleX();
11989    }
11990
11991    /**
11992     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
11993     * the view's unscaled width. A value of 1 means that no scaling is applied.
11994     *
11995     * @param scaleX The scaling factor.
11996     * @see #getPivotX()
11997     * @see #getPivotY()
11998     *
11999     * @attr ref android.R.styleable#View_scaleX
12000     */
12001    public void setScaleX(float scaleX) {
12002        if (scaleX != getScaleX()) {
12003            invalidateViewProperty(true, false);
12004            mRenderNode.setScaleX(scaleX);
12005            invalidateViewProperty(false, true);
12006
12007            invalidateParentIfNeededAndWasQuickRejected();
12008            notifySubtreeAccessibilityStateChangedIfNeeded();
12009        }
12010    }
12011
12012    /**
12013     * The amount that the view is scaled in y around the pivot point, as a proportion of
12014     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12015     *
12016     * <p>By default, this is 1.0f.
12017     *
12018     * @see #getPivotX()
12019     * @see #getPivotY()
12020     * @return The scaling factor.
12021     */
12022    @ViewDebug.ExportedProperty(category = "drawing")
12023    public float getScaleY() {
12024        return mRenderNode.getScaleY();
12025    }
12026
12027    /**
12028     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12029     * the view's unscaled width. A value of 1 means that no scaling is applied.
12030     *
12031     * @param scaleY The scaling factor.
12032     * @see #getPivotX()
12033     * @see #getPivotY()
12034     *
12035     * @attr ref android.R.styleable#View_scaleY
12036     */
12037    public void setScaleY(float scaleY) {
12038        if (scaleY != getScaleY()) {
12039            invalidateViewProperty(true, false);
12040            mRenderNode.setScaleY(scaleY);
12041            invalidateViewProperty(false, true);
12042
12043            invalidateParentIfNeededAndWasQuickRejected();
12044            notifySubtreeAccessibilityStateChangedIfNeeded();
12045        }
12046    }
12047
12048    /**
12049     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12050     * and {@link #setScaleX(float) scaled}.
12051     *
12052     * @see #getRotation()
12053     * @see #getScaleX()
12054     * @see #getScaleY()
12055     * @see #getPivotY()
12056     * @return The x location of the pivot point.
12057     *
12058     * @attr ref android.R.styleable#View_transformPivotX
12059     */
12060    @ViewDebug.ExportedProperty(category = "drawing")
12061    public float getPivotX() {
12062        return mRenderNode.getPivotX();
12063    }
12064
12065    /**
12066     * Sets the x location of the point around which the view is
12067     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12068     * By default, the pivot point is centered on the object.
12069     * Setting this property disables this behavior and causes the view to use only the
12070     * explicitly set pivotX and pivotY values.
12071     *
12072     * @param pivotX The x location of the pivot point.
12073     * @see #getRotation()
12074     * @see #getScaleX()
12075     * @see #getScaleY()
12076     * @see #getPivotY()
12077     *
12078     * @attr ref android.R.styleable#View_transformPivotX
12079     */
12080    public void setPivotX(float pivotX) {
12081        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12082            invalidateViewProperty(true, false);
12083            mRenderNode.setPivotX(pivotX);
12084            invalidateViewProperty(false, true);
12085
12086            invalidateParentIfNeededAndWasQuickRejected();
12087        }
12088    }
12089
12090    /**
12091     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12092     * and {@link #setScaleY(float) scaled}.
12093     *
12094     * @see #getRotation()
12095     * @see #getScaleX()
12096     * @see #getScaleY()
12097     * @see #getPivotY()
12098     * @return The y location of the pivot point.
12099     *
12100     * @attr ref android.R.styleable#View_transformPivotY
12101     */
12102    @ViewDebug.ExportedProperty(category = "drawing")
12103    public float getPivotY() {
12104        return mRenderNode.getPivotY();
12105    }
12106
12107    /**
12108     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12109     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12110     * Setting this property disables this behavior and causes the view to use only the
12111     * explicitly set pivotX and pivotY values.
12112     *
12113     * @param pivotY The y location of the pivot point.
12114     * @see #getRotation()
12115     * @see #getScaleX()
12116     * @see #getScaleY()
12117     * @see #getPivotY()
12118     *
12119     * @attr ref android.R.styleable#View_transformPivotY
12120     */
12121    public void setPivotY(float pivotY) {
12122        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12123            invalidateViewProperty(true, false);
12124            mRenderNode.setPivotY(pivotY);
12125            invalidateViewProperty(false, true);
12126
12127            invalidateParentIfNeededAndWasQuickRejected();
12128        }
12129    }
12130
12131    /**
12132     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12133     * completely transparent and 1 means the view is completely opaque.
12134     *
12135     * <p>By default this is 1.0f.
12136     * @return The opacity of the view.
12137     */
12138    @ViewDebug.ExportedProperty(category = "drawing")
12139    public float getAlpha() {
12140        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12141    }
12142
12143    /**
12144     * Sets the behavior for overlapping rendering for this view (see {@link
12145     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12146     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12147     * providing the value which is then used internally. That is, when {@link
12148     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12149     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12150     * instead.
12151     *
12152     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12153     * instead of that returned by {@link #hasOverlappingRendering()}.
12154     *
12155     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12156     */
12157    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12158        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12159        if (hasOverlappingRendering) {
12160            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12161        } else {
12162            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12163        }
12164    }
12165
12166    /**
12167     * Returns the value for overlapping rendering that is used internally. This is either
12168     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12169     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12170     *
12171     * @return The value for overlapping rendering being used internally.
12172     */
12173    public final boolean getHasOverlappingRendering() {
12174        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12175                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12176                hasOverlappingRendering();
12177    }
12178
12179    /**
12180     * Returns whether this View has content which overlaps.
12181     *
12182     * <p>This function, intended to be overridden by specific View types, is an optimization when
12183     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12184     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12185     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12186     * directly. An example of overlapping rendering is a TextView with a background image, such as
12187     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12188     * ImageView with only the foreground image. The default implementation returns true; subclasses
12189     * should override if they have cases which can be optimized.</p>
12190     *
12191     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12192     * necessitates that a View return true if it uses the methods internally without passing the
12193     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12194     *
12195     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12196     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12197     *
12198     * @return true if the content in this view might overlap, false otherwise.
12199     */
12200    @ViewDebug.ExportedProperty(category = "drawing")
12201    public boolean hasOverlappingRendering() {
12202        return true;
12203    }
12204
12205    /**
12206     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12207     * completely transparent and 1 means the view is completely opaque.
12208     *
12209     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12210     * can have significant performance implications, especially for large views. It is best to use
12211     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12212     *
12213     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12214     * strongly recommended for performance reasons to either override
12215     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12216     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12217     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12218     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12219     * of rendering cost, even for simple or small views. Starting with
12220     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12221     * applied to the view at the rendering level.</p>
12222     *
12223     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12224     * responsible for applying the opacity itself.</p>
12225     *
12226     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12227     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12228     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12229     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12230     *
12231     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12232     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12233     * {@link #hasOverlappingRendering}.</p>
12234     *
12235     * @param alpha The opacity of the view.
12236     *
12237     * @see #hasOverlappingRendering()
12238     * @see #setLayerType(int, android.graphics.Paint)
12239     *
12240     * @attr ref android.R.styleable#View_alpha
12241     */
12242    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12243        ensureTransformationInfo();
12244        if (mTransformationInfo.mAlpha != alpha) {
12245            mTransformationInfo.mAlpha = alpha;
12246            if (onSetAlpha((int) (alpha * 255))) {
12247                mPrivateFlags |= PFLAG_ALPHA_SET;
12248                // subclass is handling alpha - don't optimize rendering cache invalidation
12249                invalidateParentCaches();
12250                invalidate(true);
12251            } else {
12252                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12253                invalidateViewProperty(true, false);
12254                mRenderNode.setAlpha(getFinalAlpha());
12255                notifyViewAccessibilityStateChangedIfNeeded(
12256                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12257            }
12258        }
12259    }
12260
12261    /**
12262     * Faster version of setAlpha() which performs the same steps except there are
12263     * no calls to invalidate(). The caller of this function should perform proper invalidation
12264     * on the parent and this object. The return value indicates whether the subclass handles
12265     * alpha (the return value for onSetAlpha()).
12266     *
12267     * @param alpha The new value for the alpha property
12268     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
12269     *         the new value for the alpha property is different from the old value
12270     */
12271    boolean setAlphaNoInvalidation(float alpha) {
12272        ensureTransformationInfo();
12273        if (mTransformationInfo.mAlpha != alpha) {
12274            mTransformationInfo.mAlpha = alpha;
12275            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
12276            if (subclassHandlesAlpha) {
12277                mPrivateFlags |= PFLAG_ALPHA_SET;
12278                return true;
12279            } else {
12280                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12281                mRenderNode.setAlpha(getFinalAlpha());
12282            }
12283        }
12284        return false;
12285    }
12286
12287    /**
12288     * This property is hidden and intended only for use by the Fade transition, which
12289     * animates it to produce a visual translucency that does not side-effect (or get
12290     * affected by) the real alpha property. This value is composited with the other
12291     * alpha value (and the AlphaAnimation value, when that is present) to produce
12292     * a final visual translucency result, which is what is passed into the DisplayList.
12293     *
12294     * @hide
12295     */
12296    public void setTransitionAlpha(float alpha) {
12297        ensureTransformationInfo();
12298        if (mTransformationInfo.mTransitionAlpha != alpha) {
12299            mTransformationInfo.mTransitionAlpha = alpha;
12300            mPrivateFlags &= ~PFLAG_ALPHA_SET;
12301            invalidateViewProperty(true, false);
12302            mRenderNode.setAlpha(getFinalAlpha());
12303        }
12304    }
12305
12306    /**
12307     * Calculates the visual alpha of this view, which is a combination of the actual
12308     * alpha value and the transitionAlpha value (if set).
12309     */
12310    private float getFinalAlpha() {
12311        if (mTransformationInfo != null) {
12312            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
12313        }
12314        return 1;
12315    }
12316
12317    /**
12318     * This property is hidden and intended only for use by the Fade transition, which
12319     * animates it to produce a visual translucency that does not side-effect (or get
12320     * affected by) the real alpha property. This value is composited with the other
12321     * alpha value (and the AlphaAnimation value, when that is present) to produce
12322     * a final visual translucency result, which is what is passed into the DisplayList.
12323     *
12324     * @hide
12325     */
12326    @ViewDebug.ExportedProperty(category = "drawing")
12327    public float getTransitionAlpha() {
12328        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
12329    }
12330
12331    /**
12332     * Top position of this view relative to its parent.
12333     *
12334     * @return The top of this view, in pixels.
12335     */
12336    @ViewDebug.CapturedViewProperty
12337    public final int getTop() {
12338        return mTop;
12339    }
12340
12341    /**
12342     * Sets the top position of this view relative to its parent. This method is meant to be called
12343     * by the layout system and should not generally be called otherwise, because the property
12344     * may be changed at any time by the layout.
12345     *
12346     * @param top The top of this view, in pixels.
12347     */
12348    public final void setTop(int top) {
12349        if (top != mTop) {
12350            final boolean matrixIsIdentity = hasIdentityMatrix();
12351            if (matrixIsIdentity) {
12352                if (mAttachInfo != null) {
12353                    int minTop;
12354                    int yLoc;
12355                    if (top < mTop) {
12356                        minTop = top;
12357                        yLoc = top - mTop;
12358                    } else {
12359                        minTop = mTop;
12360                        yLoc = 0;
12361                    }
12362                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
12363                }
12364            } else {
12365                // Double-invalidation is necessary to capture view's old and new areas
12366                invalidate(true);
12367            }
12368
12369            int width = mRight - mLeft;
12370            int oldHeight = mBottom - mTop;
12371
12372            mTop = top;
12373            mRenderNode.setTop(mTop);
12374
12375            sizeChange(width, mBottom - mTop, width, oldHeight);
12376
12377            if (!matrixIsIdentity) {
12378                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12379                invalidate(true);
12380            }
12381            mBackgroundSizeChanged = true;
12382            if (mForegroundInfo != null) {
12383                mForegroundInfo.mBoundsChanged = true;
12384            }
12385            invalidateParentIfNeeded();
12386            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12387                // View was rejected last time it was drawn by its parent; this may have changed
12388                invalidateParentIfNeeded();
12389            }
12390        }
12391    }
12392
12393    /**
12394     * Bottom position of this view relative to its parent.
12395     *
12396     * @return The bottom of this view, in pixels.
12397     */
12398    @ViewDebug.CapturedViewProperty
12399    public final int getBottom() {
12400        return mBottom;
12401    }
12402
12403    /**
12404     * True if this view has changed since the last time being drawn.
12405     *
12406     * @return The dirty state of this view.
12407     */
12408    public boolean isDirty() {
12409        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
12410    }
12411
12412    /**
12413     * Sets the bottom position of this view relative to its parent. This method is meant to be
12414     * called by the layout system and should not generally be called otherwise, because the
12415     * property may be changed at any time by the layout.
12416     *
12417     * @param bottom The bottom of this view, in pixels.
12418     */
12419    public final void setBottom(int bottom) {
12420        if (bottom != mBottom) {
12421            final boolean matrixIsIdentity = hasIdentityMatrix();
12422            if (matrixIsIdentity) {
12423                if (mAttachInfo != null) {
12424                    int maxBottom;
12425                    if (bottom < mBottom) {
12426                        maxBottom = mBottom;
12427                    } else {
12428                        maxBottom = bottom;
12429                    }
12430                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
12431                }
12432            } else {
12433                // Double-invalidation is necessary to capture view's old and new areas
12434                invalidate(true);
12435            }
12436
12437            int width = mRight - mLeft;
12438            int oldHeight = mBottom - mTop;
12439
12440            mBottom = bottom;
12441            mRenderNode.setBottom(mBottom);
12442
12443            sizeChange(width, mBottom - mTop, width, oldHeight);
12444
12445            if (!matrixIsIdentity) {
12446                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12447                invalidate(true);
12448            }
12449            mBackgroundSizeChanged = true;
12450            if (mForegroundInfo != null) {
12451                mForegroundInfo.mBoundsChanged = true;
12452            }
12453            invalidateParentIfNeeded();
12454            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12455                // View was rejected last time it was drawn by its parent; this may have changed
12456                invalidateParentIfNeeded();
12457            }
12458        }
12459    }
12460
12461    /**
12462     * Left position of this view relative to its parent.
12463     *
12464     * @return The left edge of this view, in pixels.
12465     */
12466    @ViewDebug.CapturedViewProperty
12467    public final int getLeft() {
12468        return mLeft;
12469    }
12470
12471    /**
12472     * Sets the left position of this view relative to its parent. This method is meant to be called
12473     * by the layout system and should not generally be called otherwise, because the property
12474     * may be changed at any time by the layout.
12475     *
12476     * @param left The left of this view, in pixels.
12477     */
12478    public final void setLeft(int left) {
12479        if (left != mLeft) {
12480            final boolean matrixIsIdentity = hasIdentityMatrix();
12481            if (matrixIsIdentity) {
12482                if (mAttachInfo != null) {
12483                    int minLeft;
12484                    int xLoc;
12485                    if (left < mLeft) {
12486                        minLeft = left;
12487                        xLoc = left - mLeft;
12488                    } else {
12489                        minLeft = mLeft;
12490                        xLoc = 0;
12491                    }
12492                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
12493                }
12494            } else {
12495                // Double-invalidation is necessary to capture view's old and new areas
12496                invalidate(true);
12497            }
12498
12499            int oldWidth = mRight - mLeft;
12500            int height = mBottom - mTop;
12501
12502            mLeft = left;
12503            mRenderNode.setLeft(left);
12504
12505            sizeChange(mRight - mLeft, height, oldWidth, height);
12506
12507            if (!matrixIsIdentity) {
12508                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12509                invalidate(true);
12510            }
12511            mBackgroundSizeChanged = true;
12512            if (mForegroundInfo != null) {
12513                mForegroundInfo.mBoundsChanged = true;
12514            }
12515            invalidateParentIfNeeded();
12516            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12517                // View was rejected last time it was drawn by its parent; this may have changed
12518                invalidateParentIfNeeded();
12519            }
12520        }
12521    }
12522
12523    /**
12524     * Right position of this view relative to its parent.
12525     *
12526     * @return The right edge of this view, in pixels.
12527     */
12528    @ViewDebug.CapturedViewProperty
12529    public final int getRight() {
12530        return mRight;
12531    }
12532
12533    /**
12534     * Sets the right position of this view relative to its parent. This method is meant to be called
12535     * by the layout system and should not generally be called otherwise, because the property
12536     * may be changed at any time by the layout.
12537     *
12538     * @param right The right of this view, in pixels.
12539     */
12540    public final void setRight(int right) {
12541        if (right != mRight) {
12542            final boolean matrixIsIdentity = hasIdentityMatrix();
12543            if (matrixIsIdentity) {
12544                if (mAttachInfo != null) {
12545                    int maxRight;
12546                    if (right < mRight) {
12547                        maxRight = mRight;
12548                    } else {
12549                        maxRight = right;
12550                    }
12551                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
12552                }
12553            } else {
12554                // Double-invalidation is necessary to capture view's old and new areas
12555                invalidate(true);
12556            }
12557
12558            int oldWidth = mRight - mLeft;
12559            int height = mBottom - mTop;
12560
12561            mRight = right;
12562            mRenderNode.setRight(mRight);
12563
12564            sizeChange(mRight - mLeft, height, oldWidth, height);
12565
12566            if (!matrixIsIdentity) {
12567                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12568                invalidate(true);
12569            }
12570            mBackgroundSizeChanged = true;
12571            if (mForegroundInfo != null) {
12572                mForegroundInfo.mBoundsChanged = true;
12573            }
12574            invalidateParentIfNeeded();
12575            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12576                // View was rejected last time it was drawn by its parent; this may have changed
12577                invalidateParentIfNeeded();
12578            }
12579        }
12580    }
12581
12582    /**
12583     * The visual x position of this view, in pixels. This is equivalent to the
12584     * {@link #setTranslationX(float) translationX} property plus the current
12585     * {@link #getLeft() left} property.
12586     *
12587     * @return The visual x position of this view, in pixels.
12588     */
12589    @ViewDebug.ExportedProperty(category = "drawing")
12590    public float getX() {
12591        return mLeft + getTranslationX();
12592    }
12593
12594    /**
12595     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
12596     * {@link #setTranslationX(float) translationX} property to be the difference between
12597     * the x value passed in and the current {@link #getLeft() left} property.
12598     *
12599     * @param x The visual x position of this view, in pixels.
12600     */
12601    public void setX(float x) {
12602        setTranslationX(x - mLeft);
12603    }
12604
12605    /**
12606     * The visual y position of this view, in pixels. This is equivalent to the
12607     * {@link #setTranslationY(float) translationY} property plus the current
12608     * {@link #getTop() top} property.
12609     *
12610     * @return The visual y position of this view, in pixels.
12611     */
12612    @ViewDebug.ExportedProperty(category = "drawing")
12613    public float getY() {
12614        return mTop + getTranslationY();
12615    }
12616
12617    /**
12618     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
12619     * {@link #setTranslationY(float) translationY} property to be the difference between
12620     * the y value passed in and the current {@link #getTop() top} property.
12621     *
12622     * @param y The visual y position of this view, in pixels.
12623     */
12624    public void setY(float y) {
12625        setTranslationY(y - mTop);
12626    }
12627
12628    /**
12629     * The visual z position of this view, in pixels. This is equivalent to the
12630     * {@link #setTranslationZ(float) translationZ} property plus the current
12631     * {@link #getElevation() elevation} property.
12632     *
12633     * @return The visual z position of this view, in pixels.
12634     */
12635    @ViewDebug.ExportedProperty(category = "drawing")
12636    public float getZ() {
12637        return getElevation() + getTranslationZ();
12638    }
12639
12640    /**
12641     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
12642     * {@link #setTranslationZ(float) translationZ} property to be the difference between
12643     * the x value passed in and the current {@link #getElevation() elevation} property.
12644     *
12645     * @param z The visual z position of this view, in pixels.
12646     */
12647    public void setZ(float z) {
12648        setTranslationZ(z - getElevation());
12649    }
12650
12651    /**
12652     * The base elevation of this view relative to its parent, in pixels.
12653     *
12654     * @return The base depth position of the view, in pixels.
12655     */
12656    @ViewDebug.ExportedProperty(category = "drawing")
12657    public float getElevation() {
12658        return mRenderNode.getElevation();
12659    }
12660
12661    /**
12662     * Sets the base elevation of this view, in pixels.
12663     *
12664     * @attr ref android.R.styleable#View_elevation
12665     */
12666    public void setElevation(float elevation) {
12667        if (elevation != getElevation()) {
12668            invalidateViewProperty(true, false);
12669            mRenderNode.setElevation(elevation);
12670            invalidateViewProperty(false, true);
12671
12672            invalidateParentIfNeededAndWasQuickRejected();
12673        }
12674    }
12675
12676    /**
12677     * The horizontal location of this view relative to its {@link #getLeft() left} position.
12678     * This position is post-layout, in addition to wherever the object's
12679     * layout placed it.
12680     *
12681     * @return The horizontal position of this view relative to its left position, in pixels.
12682     */
12683    @ViewDebug.ExportedProperty(category = "drawing")
12684    public float getTranslationX() {
12685        return mRenderNode.getTranslationX();
12686    }
12687
12688    /**
12689     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
12690     * This effectively positions the object post-layout, in addition to wherever the object's
12691     * layout placed it.
12692     *
12693     * @param translationX The horizontal position of this view relative to its left position,
12694     * in pixels.
12695     *
12696     * @attr ref android.R.styleable#View_translationX
12697     */
12698    public void setTranslationX(float translationX) {
12699        if (translationX != getTranslationX()) {
12700            invalidateViewProperty(true, false);
12701            mRenderNode.setTranslationX(translationX);
12702            invalidateViewProperty(false, true);
12703
12704            invalidateParentIfNeededAndWasQuickRejected();
12705            notifySubtreeAccessibilityStateChangedIfNeeded();
12706        }
12707    }
12708
12709    /**
12710     * The vertical location of this view relative to its {@link #getTop() top} position.
12711     * This position is post-layout, in addition to wherever the object's
12712     * layout placed it.
12713     *
12714     * @return The vertical position of this view relative to its top position,
12715     * in pixels.
12716     */
12717    @ViewDebug.ExportedProperty(category = "drawing")
12718    public float getTranslationY() {
12719        return mRenderNode.getTranslationY();
12720    }
12721
12722    /**
12723     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
12724     * This effectively positions the object post-layout, in addition to wherever the object's
12725     * layout placed it.
12726     *
12727     * @param translationY The vertical position of this view relative to its top position,
12728     * in pixels.
12729     *
12730     * @attr ref android.R.styleable#View_translationY
12731     */
12732    public void setTranslationY(float translationY) {
12733        if (translationY != getTranslationY()) {
12734            invalidateViewProperty(true, false);
12735            mRenderNode.setTranslationY(translationY);
12736            invalidateViewProperty(false, true);
12737
12738            invalidateParentIfNeededAndWasQuickRejected();
12739            notifySubtreeAccessibilityStateChangedIfNeeded();
12740        }
12741    }
12742
12743    /**
12744     * The depth location of this view relative to its {@link #getElevation() elevation}.
12745     *
12746     * @return The depth of this view relative to its elevation.
12747     */
12748    @ViewDebug.ExportedProperty(category = "drawing")
12749    public float getTranslationZ() {
12750        return mRenderNode.getTranslationZ();
12751    }
12752
12753    /**
12754     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
12755     *
12756     * @attr ref android.R.styleable#View_translationZ
12757     */
12758    public void setTranslationZ(float translationZ) {
12759        if (translationZ != getTranslationZ()) {
12760            invalidateViewProperty(true, false);
12761            mRenderNode.setTranslationZ(translationZ);
12762            invalidateViewProperty(false, true);
12763
12764            invalidateParentIfNeededAndWasQuickRejected();
12765        }
12766    }
12767
12768    /** @hide */
12769    public void setAnimationMatrix(Matrix matrix) {
12770        invalidateViewProperty(true, false);
12771        mRenderNode.setAnimationMatrix(matrix);
12772        invalidateViewProperty(false, true);
12773
12774        invalidateParentIfNeededAndWasQuickRejected();
12775    }
12776
12777    /**
12778     * Returns the current StateListAnimator if exists.
12779     *
12780     * @return StateListAnimator or null if it does not exists
12781     * @see    #setStateListAnimator(android.animation.StateListAnimator)
12782     */
12783    public StateListAnimator getStateListAnimator() {
12784        return mStateListAnimator;
12785    }
12786
12787    /**
12788     * Attaches the provided StateListAnimator to this View.
12789     * <p>
12790     * Any previously attached StateListAnimator will be detached.
12791     *
12792     * @param stateListAnimator The StateListAnimator to update the view
12793     * @see {@link android.animation.StateListAnimator}
12794     */
12795    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12796        if (mStateListAnimator == stateListAnimator) {
12797            return;
12798        }
12799        if (mStateListAnimator != null) {
12800            mStateListAnimator.setTarget(null);
12801        }
12802        mStateListAnimator = stateListAnimator;
12803        if (stateListAnimator != null) {
12804            stateListAnimator.setTarget(this);
12805            if (isAttachedToWindow()) {
12806                stateListAnimator.setState(getDrawableState());
12807            }
12808        }
12809    }
12810
12811    /**
12812     * Returns whether the Outline should be used to clip the contents of the View.
12813     * <p>
12814     * Note that this flag will only be respected if the View's Outline returns true from
12815     * {@link Outline#canClip()}.
12816     *
12817     * @see #setOutlineProvider(ViewOutlineProvider)
12818     * @see #setClipToOutline(boolean)
12819     */
12820    public final boolean getClipToOutline() {
12821        return mRenderNode.getClipToOutline();
12822    }
12823
12824    /**
12825     * Sets whether the View's Outline should be used to clip the contents of the View.
12826     * <p>
12827     * Only a single non-rectangular clip can be applied on a View at any time.
12828     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12829     * circular reveal} animation take priority over Outline clipping, and
12830     * child Outline clipping takes priority over Outline clipping done by a
12831     * parent.
12832     * <p>
12833     * Note that this flag will only be respected if the View's Outline returns true from
12834     * {@link Outline#canClip()}.
12835     *
12836     * @see #setOutlineProvider(ViewOutlineProvider)
12837     * @see #getClipToOutline()
12838     */
12839    public void setClipToOutline(boolean clipToOutline) {
12840        damageInParent();
12841        if (getClipToOutline() != clipToOutline) {
12842            mRenderNode.setClipToOutline(clipToOutline);
12843        }
12844    }
12845
12846    // correspond to the enum values of View_outlineProvider
12847    private static final int PROVIDER_BACKGROUND = 0;
12848    private static final int PROVIDER_NONE = 1;
12849    private static final int PROVIDER_BOUNDS = 2;
12850    private static final int PROVIDER_PADDED_BOUNDS = 3;
12851    private void setOutlineProviderFromAttribute(int providerInt) {
12852        switch (providerInt) {
12853            case PROVIDER_BACKGROUND:
12854                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
12855                break;
12856            case PROVIDER_NONE:
12857                setOutlineProvider(null);
12858                break;
12859            case PROVIDER_BOUNDS:
12860                setOutlineProvider(ViewOutlineProvider.BOUNDS);
12861                break;
12862            case PROVIDER_PADDED_BOUNDS:
12863                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
12864                break;
12865        }
12866    }
12867
12868    /**
12869     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
12870     * the shape of the shadow it casts, and enables outline clipping.
12871     * <p>
12872     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
12873     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
12874     * outline provider with this method allows this behavior to be overridden.
12875     * <p>
12876     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
12877     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
12878     * <p>
12879     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
12880     *
12881     * @see #setClipToOutline(boolean)
12882     * @see #getClipToOutline()
12883     * @see #getOutlineProvider()
12884     */
12885    public void setOutlineProvider(ViewOutlineProvider provider) {
12886        mOutlineProvider = provider;
12887        invalidateOutline();
12888    }
12889
12890    /**
12891     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
12892     * that defines the shape of the shadow it casts, and enables outline clipping.
12893     *
12894     * @see #setOutlineProvider(ViewOutlineProvider)
12895     */
12896    public ViewOutlineProvider getOutlineProvider() {
12897        return mOutlineProvider;
12898    }
12899
12900    /**
12901     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
12902     *
12903     * @see #setOutlineProvider(ViewOutlineProvider)
12904     */
12905    public void invalidateOutline() {
12906        rebuildOutline();
12907
12908        notifySubtreeAccessibilityStateChangedIfNeeded();
12909        invalidateViewProperty(false, false);
12910    }
12911
12912    /**
12913     * Internal version of {@link #invalidateOutline()} which invalidates the
12914     * outline without invalidating the view itself. This is intended to be called from
12915     * within methods in the View class itself which are the result of the view being
12916     * invalidated already. For example, when we are drawing the background of a View,
12917     * we invalidate the outline in case it changed in the meantime, but we do not
12918     * need to invalidate the view because we're already drawing the background as part
12919     * of drawing the view in response to an earlier invalidation of the view.
12920     */
12921    private void rebuildOutline() {
12922        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
12923        if (mAttachInfo == null) return;
12924
12925        if (mOutlineProvider == null) {
12926            // no provider, remove outline
12927            mRenderNode.setOutline(null);
12928        } else {
12929            final Outline outline = mAttachInfo.mTmpOutline;
12930            outline.setEmpty();
12931            outline.setAlpha(1.0f);
12932
12933            mOutlineProvider.getOutline(this, outline);
12934            mRenderNode.setOutline(outline);
12935        }
12936    }
12937
12938    /**
12939     * HierarchyViewer only
12940     *
12941     * @hide
12942     */
12943    @ViewDebug.ExportedProperty(category = "drawing")
12944    public boolean hasShadow() {
12945        return mRenderNode.hasShadow();
12946    }
12947
12948
12949    /** @hide */
12950    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
12951        mRenderNode.setRevealClip(shouldClip, x, y, radius);
12952        invalidateViewProperty(false, false);
12953    }
12954
12955    /**
12956     * Hit rectangle in parent's coordinates
12957     *
12958     * @param outRect The hit rectangle of the view.
12959     */
12960    public void getHitRect(Rect outRect) {
12961        if (hasIdentityMatrix() || mAttachInfo == null) {
12962            outRect.set(mLeft, mTop, mRight, mBottom);
12963        } else {
12964            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
12965            tmpRect.set(0, 0, getWidth(), getHeight());
12966            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
12967            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
12968                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
12969        }
12970    }
12971
12972    /**
12973     * Determines whether the given point, in local coordinates is inside the view.
12974     */
12975    /*package*/ final boolean pointInView(float localX, float localY) {
12976        return pointInView(localX, localY, 0);
12977    }
12978
12979    /**
12980     * Utility method to determine whether the given point, in local coordinates,
12981     * is inside the view, where the area of the view is expanded by the slop factor.
12982     * This method is called while processing touch-move events to determine if the event
12983     * is still within the view.
12984     *
12985     * @hide
12986     */
12987    public boolean pointInView(float localX, float localY, float slop) {
12988        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
12989                localY < ((mBottom - mTop) + slop);
12990    }
12991
12992    /**
12993     * When a view has focus and the user navigates away from it, the next view is searched for
12994     * starting from the rectangle filled in by this method.
12995     *
12996     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
12997     * of the view.  However, if your view maintains some idea of internal selection,
12998     * such as a cursor, or a selected row or column, you should override this method and
12999     * fill in a more specific rectangle.
13000     *
13001     * @param r The rectangle to fill in, in this view's coordinates.
13002     */
13003    public void getFocusedRect(Rect r) {
13004        getDrawingRect(r);
13005    }
13006
13007    /**
13008     * If some part of this view is not clipped by any of its parents, then
13009     * return that area in r in global (root) coordinates. To convert r to local
13010     * coordinates (without taking possible View rotations into account), offset
13011     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13012     * If the view is completely clipped or translated out, return false.
13013     *
13014     * @param r If true is returned, r holds the global coordinates of the
13015     *        visible portion of this view.
13016     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13017     *        between this view and its root. globalOffet may be null.
13018     * @return true if r is non-empty (i.e. part of the view is visible at the
13019     *         root level.
13020     */
13021    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13022        int width = mRight - mLeft;
13023        int height = mBottom - mTop;
13024        if (width > 0 && height > 0) {
13025            r.set(0, 0, width, height);
13026            if (globalOffset != null) {
13027                globalOffset.set(-mScrollX, -mScrollY);
13028            }
13029            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13030        }
13031        return false;
13032    }
13033
13034    public final boolean getGlobalVisibleRect(Rect r) {
13035        return getGlobalVisibleRect(r, null);
13036    }
13037
13038    public final boolean getLocalVisibleRect(Rect r) {
13039        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13040        if (getGlobalVisibleRect(r, offset)) {
13041            r.offset(-offset.x, -offset.y); // make r local
13042            return true;
13043        }
13044        return false;
13045    }
13046
13047    /**
13048     * Offset this view's vertical location by the specified number of pixels.
13049     *
13050     * @param offset the number of pixels to offset the view by
13051     */
13052    public void offsetTopAndBottom(int offset) {
13053        if (offset != 0) {
13054            final boolean matrixIsIdentity = hasIdentityMatrix();
13055            if (matrixIsIdentity) {
13056                if (isHardwareAccelerated()) {
13057                    invalidateViewProperty(false, false);
13058                } else {
13059                    final ViewParent p = mParent;
13060                    if (p != null && mAttachInfo != null) {
13061                        final Rect r = mAttachInfo.mTmpInvalRect;
13062                        int minTop;
13063                        int maxBottom;
13064                        int yLoc;
13065                        if (offset < 0) {
13066                            minTop = mTop + offset;
13067                            maxBottom = mBottom;
13068                            yLoc = offset;
13069                        } else {
13070                            minTop = mTop;
13071                            maxBottom = mBottom + offset;
13072                            yLoc = 0;
13073                        }
13074                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13075                        p.invalidateChild(this, r);
13076                    }
13077                }
13078            } else {
13079                invalidateViewProperty(false, false);
13080            }
13081
13082            mTop += offset;
13083            mBottom += offset;
13084            mRenderNode.offsetTopAndBottom(offset);
13085            if (isHardwareAccelerated()) {
13086                invalidateViewProperty(false, false);
13087                invalidateParentIfNeededAndWasQuickRejected();
13088            } else {
13089                if (!matrixIsIdentity) {
13090                    invalidateViewProperty(false, true);
13091                }
13092                invalidateParentIfNeeded();
13093            }
13094            notifySubtreeAccessibilityStateChangedIfNeeded();
13095        }
13096    }
13097
13098    /**
13099     * Offset this view's horizontal location by the specified amount of pixels.
13100     *
13101     * @param offset the number of pixels to offset the view by
13102     */
13103    public void offsetLeftAndRight(int offset) {
13104        if (offset != 0) {
13105            final boolean matrixIsIdentity = hasIdentityMatrix();
13106            if (matrixIsIdentity) {
13107                if (isHardwareAccelerated()) {
13108                    invalidateViewProperty(false, false);
13109                } else {
13110                    final ViewParent p = mParent;
13111                    if (p != null && mAttachInfo != null) {
13112                        final Rect r = mAttachInfo.mTmpInvalRect;
13113                        int minLeft;
13114                        int maxRight;
13115                        if (offset < 0) {
13116                            minLeft = mLeft + offset;
13117                            maxRight = mRight;
13118                        } else {
13119                            minLeft = mLeft;
13120                            maxRight = mRight + offset;
13121                        }
13122                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13123                        p.invalidateChild(this, r);
13124                    }
13125                }
13126            } else {
13127                invalidateViewProperty(false, false);
13128            }
13129
13130            mLeft += offset;
13131            mRight += offset;
13132            mRenderNode.offsetLeftAndRight(offset);
13133            if (isHardwareAccelerated()) {
13134                invalidateViewProperty(false, false);
13135                invalidateParentIfNeededAndWasQuickRejected();
13136            } else {
13137                if (!matrixIsIdentity) {
13138                    invalidateViewProperty(false, true);
13139                }
13140                invalidateParentIfNeeded();
13141            }
13142            notifySubtreeAccessibilityStateChangedIfNeeded();
13143        }
13144    }
13145
13146    /**
13147     * Get the LayoutParams associated with this view. All views should have
13148     * layout parameters. These supply parameters to the <i>parent</i> of this
13149     * view specifying how it should be arranged. There are many subclasses of
13150     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13151     * of ViewGroup that are responsible for arranging their children.
13152     *
13153     * This method may return null if this View is not attached to a parent
13154     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13155     * was not invoked successfully. When a View is attached to a parent
13156     * ViewGroup, this method must not return null.
13157     *
13158     * @return The LayoutParams associated with this view, or null if no
13159     *         parameters have been set yet
13160     */
13161    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13162    public ViewGroup.LayoutParams getLayoutParams() {
13163        return mLayoutParams;
13164    }
13165
13166    /**
13167     * Set the layout parameters associated with this view. These supply
13168     * parameters to the <i>parent</i> of this view specifying how it should be
13169     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13170     * correspond to the different subclasses of ViewGroup that are responsible
13171     * for arranging their children.
13172     *
13173     * @param params The layout parameters for this view, cannot be null
13174     */
13175    public void setLayoutParams(ViewGroup.LayoutParams params) {
13176        if (params == null) {
13177            throw new NullPointerException("Layout parameters cannot be null");
13178        }
13179        mLayoutParams = params;
13180        resolveLayoutParams();
13181        if (mParent instanceof ViewGroup) {
13182            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13183        }
13184        requestLayout();
13185    }
13186
13187    /**
13188     * Resolve the layout parameters depending on the resolved layout direction
13189     *
13190     * @hide
13191     */
13192    public void resolveLayoutParams() {
13193        if (mLayoutParams != null) {
13194            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13195        }
13196    }
13197
13198    /**
13199     * Set the scrolled position of your view. This will cause a call to
13200     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13201     * invalidated.
13202     * @param x the x position to scroll to
13203     * @param y the y position to scroll to
13204     */
13205    public void scrollTo(int x, int y) {
13206        if (mScrollX != x || mScrollY != y) {
13207            int oldX = mScrollX;
13208            int oldY = mScrollY;
13209            mScrollX = x;
13210            mScrollY = y;
13211            invalidateParentCaches();
13212            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13213            if (!awakenScrollBars()) {
13214                postInvalidateOnAnimation();
13215            }
13216        }
13217    }
13218
13219    /**
13220     * Move the scrolled position of your view. This will cause a call to
13221     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13222     * invalidated.
13223     * @param x the amount of pixels to scroll by horizontally
13224     * @param y the amount of pixels to scroll by vertically
13225     */
13226    public void scrollBy(int x, int y) {
13227        scrollTo(mScrollX + x, mScrollY + y);
13228    }
13229
13230    /**
13231     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13232     * animation to fade the scrollbars out after a default delay. If a subclass
13233     * provides animated scrolling, the start delay should equal the duration
13234     * of the scrolling animation.</p>
13235     *
13236     * <p>The animation starts only if at least one of the scrollbars is
13237     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13238     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13239     * this method returns true, and false otherwise. If the animation is
13240     * started, this method calls {@link #invalidate()}; in that case the
13241     * caller should not call {@link #invalidate()}.</p>
13242     *
13243     * <p>This method should be invoked every time a subclass directly updates
13244     * the scroll parameters.</p>
13245     *
13246     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13247     * and {@link #scrollTo(int, int)}.</p>
13248     *
13249     * @return true if the animation is played, false otherwise
13250     *
13251     * @see #awakenScrollBars(int)
13252     * @see #scrollBy(int, int)
13253     * @see #scrollTo(int, int)
13254     * @see #isHorizontalScrollBarEnabled()
13255     * @see #isVerticalScrollBarEnabled()
13256     * @see #setHorizontalScrollBarEnabled(boolean)
13257     * @see #setVerticalScrollBarEnabled(boolean)
13258     */
13259    protected boolean awakenScrollBars() {
13260        return mScrollCache != null &&
13261                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
13262    }
13263
13264    /**
13265     * Trigger the scrollbars to draw.
13266     * This method differs from awakenScrollBars() only in its default duration.
13267     * initialAwakenScrollBars() will show the scroll bars for longer than
13268     * usual to give the user more of a chance to notice them.
13269     *
13270     * @return true if the animation is played, false otherwise.
13271     */
13272    private boolean initialAwakenScrollBars() {
13273        return mScrollCache != null &&
13274                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
13275    }
13276
13277    /**
13278     * <p>
13279     * Trigger the scrollbars to draw. When invoked this method starts an
13280     * animation to fade the scrollbars out after a fixed delay. If a subclass
13281     * provides animated scrolling, the start delay should equal the duration of
13282     * the scrolling animation.
13283     * </p>
13284     *
13285     * <p>
13286     * The animation starts only if at least one of the scrollbars is enabled,
13287     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13288     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13289     * this method returns true, and false otherwise. If the animation is
13290     * started, this method calls {@link #invalidate()}; in that case the caller
13291     * should not call {@link #invalidate()}.
13292     * </p>
13293     *
13294     * <p>
13295     * This method should be invoked every time a subclass directly updates the
13296     * scroll parameters.
13297     * </p>
13298     *
13299     * @param startDelay the delay, in milliseconds, after which the animation
13300     *        should start; when the delay is 0, the animation starts
13301     *        immediately
13302     * @return true if the animation is played, false otherwise
13303     *
13304     * @see #scrollBy(int, int)
13305     * @see #scrollTo(int, int)
13306     * @see #isHorizontalScrollBarEnabled()
13307     * @see #isVerticalScrollBarEnabled()
13308     * @see #setHorizontalScrollBarEnabled(boolean)
13309     * @see #setVerticalScrollBarEnabled(boolean)
13310     */
13311    protected boolean awakenScrollBars(int startDelay) {
13312        return awakenScrollBars(startDelay, 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()} if the invalidate parameter
13329     * is set to true; in that case the caller
13330     * should not call {@link #invalidate()}.
13331     * </p>
13332     *
13333     * <p>
13334     * This method should be invoked every time a subclass directly updates the
13335     * scroll parameters.
13336     * </p>
13337     *
13338     * @param startDelay the delay, in milliseconds, after which the animation
13339     *        should start; when the delay is 0, the animation starts
13340     *        immediately
13341     *
13342     * @param invalidate Whether this method should call invalidate
13343     *
13344     * @return true if the animation is played, false otherwise
13345     *
13346     * @see #scrollBy(int, int)
13347     * @see #scrollTo(int, int)
13348     * @see #isHorizontalScrollBarEnabled()
13349     * @see #isVerticalScrollBarEnabled()
13350     * @see #setHorizontalScrollBarEnabled(boolean)
13351     * @see #setVerticalScrollBarEnabled(boolean)
13352     */
13353    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
13354        final ScrollabilityCache scrollCache = mScrollCache;
13355
13356        if (scrollCache == null || !scrollCache.fadeScrollBars) {
13357            return false;
13358        }
13359
13360        if (scrollCache.scrollBar == null) {
13361            scrollCache.scrollBar = new ScrollBarDrawable();
13362            scrollCache.scrollBar.setState(getDrawableState());
13363            scrollCache.scrollBar.setCallback(this);
13364        }
13365
13366        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
13367
13368            if (invalidate) {
13369                // Invalidate to show the scrollbars
13370                postInvalidateOnAnimation();
13371            }
13372
13373            if (scrollCache.state == ScrollabilityCache.OFF) {
13374                // FIXME: this is copied from WindowManagerService.
13375                // We should get this value from the system when it
13376                // is possible to do so.
13377                final int KEY_REPEAT_FIRST_DELAY = 750;
13378                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
13379            }
13380
13381            // Tell mScrollCache when we should start fading. This may
13382            // extend the fade start time if one was already scheduled
13383            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
13384            scrollCache.fadeStartTime = fadeStartTime;
13385            scrollCache.state = ScrollabilityCache.ON;
13386
13387            // Schedule our fader to run, unscheduling any old ones first
13388            if (mAttachInfo != null) {
13389                mAttachInfo.mHandler.removeCallbacks(scrollCache);
13390                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
13391            }
13392
13393            return true;
13394        }
13395
13396        return false;
13397    }
13398
13399    /**
13400     * Do not invalidate views which are not visible and which are not running an animation. They
13401     * will not get drawn and they should not set dirty flags as if they will be drawn
13402     */
13403    private boolean skipInvalidate() {
13404        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
13405                (!(mParent instanceof ViewGroup) ||
13406                        !((ViewGroup) mParent).isViewTransitioning(this));
13407    }
13408
13409    /**
13410     * Mark the area defined by dirty as needing to be drawn. If the view is
13411     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13412     * point in the future.
13413     * <p>
13414     * This must be called from a UI thread. To call from a non-UI thread, call
13415     * {@link #postInvalidate()}.
13416     * <p>
13417     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
13418     * {@code dirty}.
13419     *
13420     * @param dirty the rectangle representing the bounds of the dirty region
13421     */
13422    public void invalidate(Rect dirty) {
13423        final int scrollX = mScrollX;
13424        final int scrollY = mScrollY;
13425        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
13426                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
13427    }
13428
13429    /**
13430     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
13431     * coordinates of the dirty rect are relative to the view. If the view is
13432     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13433     * point in the future.
13434     * <p>
13435     * This must be called from a UI thread. To call from a non-UI thread, call
13436     * {@link #postInvalidate()}.
13437     *
13438     * @param l the left position of the dirty region
13439     * @param t the top position of the dirty region
13440     * @param r the right position of the dirty region
13441     * @param b the bottom position of the dirty region
13442     */
13443    public void invalidate(int l, int t, int r, int b) {
13444        final int scrollX = mScrollX;
13445        final int scrollY = mScrollY;
13446        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
13447    }
13448
13449    /**
13450     * Invalidate the whole view. If the view is visible,
13451     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
13452     * the future.
13453     * <p>
13454     * This must be called from a UI thread. To call from a non-UI thread, call
13455     * {@link #postInvalidate()}.
13456     */
13457    public void invalidate() {
13458        invalidate(true);
13459    }
13460
13461    /**
13462     * This is where the invalidate() work actually happens. A full invalidate()
13463     * causes the drawing cache to be invalidated, but this function can be
13464     * called with invalidateCache set to false to skip that invalidation step
13465     * for cases that do not need it (for example, a component that remains at
13466     * the same dimensions with the same content).
13467     *
13468     * @param invalidateCache Whether the drawing cache for this view should be
13469     *            invalidated as well. This is usually true for a full
13470     *            invalidate, but may be set to false if the View's contents or
13471     *            dimensions have not changed.
13472     */
13473    void invalidate(boolean invalidateCache) {
13474        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
13475    }
13476
13477    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
13478            boolean fullInvalidate) {
13479        if (mGhostView != null) {
13480            mGhostView.invalidate(true);
13481            return;
13482        }
13483
13484        if (skipInvalidate()) {
13485            return;
13486        }
13487
13488        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
13489                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
13490                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
13491                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
13492            if (fullInvalidate) {
13493                mLastIsOpaque = isOpaque();
13494                mPrivateFlags &= ~PFLAG_DRAWN;
13495            }
13496
13497            mPrivateFlags |= PFLAG_DIRTY;
13498
13499            if (invalidateCache) {
13500                mPrivateFlags |= PFLAG_INVALIDATED;
13501                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13502            }
13503
13504            // Propagate the damage rectangle to the parent view.
13505            final AttachInfo ai = mAttachInfo;
13506            final ViewParent p = mParent;
13507            if (p != null && ai != null && l < r && t < b) {
13508                final Rect damage = ai.mTmpInvalRect;
13509                damage.set(l, t, r, b);
13510                p.invalidateChild(this, damage);
13511            }
13512
13513            // Damage the entire projection receiver, if necessary.
13514            if (mBackground != null && mBackground.isProjected()) {
13515                final View receiver = getProjectionReceiver();
13516                if (receiver != null) {
13517                    receiver.damageInParent();
13518                }
13519            }
13520
13521            // Damage the entire IsolatedZVolume receiving this view's shadow.
13522            if (isHardwareAccelerated() && getZ() != 0) {
13523                damageShadowReceiver();
13524            }
13525        }
13526    }
13527
13528    /**
13529     * @return this view's projection receiver, or {@code null} if none exists
13530     */
13531    private View getProjectionReceiver() {
13532        ViewParent p = getParent();
13533        while (p != null && p instanceof View) {
13534            final View v = (View) p;
13535            if (v.isProjectionReceiver()) {
13536                return v;
13537            }
13538            p = p.getParent();
13539        }
13540
13541        return null;
13542    }
13543
13544    /**
13545     * @return whether the view is a projection receiver
13546     */
13547    private boolean isProjectionReceiver() {
13548        return mBackground != null;
13549    }
13550
13551    /**
13552     * Damage area of the screen that can be covered by this View's shadow.
13553     *
13554     * This method will guarantee that any changes to shadows cast by a View
13555     * are damaged on the screen for future redraw.
13556     */
13557    private void damageShadowReceiver() {
13558        final AttachInfo ai = mAttachInfo;
13559        if (ai != null) {
13560            ViewParent p = getParent();
13561            if (p != null && p instanceof ViewGroup) {
13562                final ViewGroup vg = (ViewGroup) p;
13563                vg.damageInParent();
13564            }
13565        }
13566    }
13567
13568    /**
13569     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
13570     * set any flags or handle all of the cases handled by the default invalidation methods.
13571     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
13572     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
13573     * walk up the hierarchy, transforming the dirty rect as necessary.
13574     *
13575     * The method also handles normal invalidation logic if display list properties are not
13576     * being used in this view. The invalidateParent and forceRedraw flags are used by that
13577     * backup approach, to handle these cases used in the various property-setting methods.
13578     *
13579     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
13580     * are not being used in this view
13581     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
13582     * list properties are not being used in this view
13583     */
13584    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
13585        if (!isHardwareAccelerated()
13586                || !mRenderNode.isValid()
13587                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
13588            if (invalidateParent) {
13589                invalidateParentCaches();
13590            }
13591            if (forceRedraw) {
13592                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13593            }
13594            invalidate(false);
13595        } else {
13596            damageInParent();
13597        }
13598        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
13599            damageShadowReceiver();
13600        }
13601    }
13602
13603    /**
13604     * Tells the parent view to damage this view's bounds.
13605     *
13606     * @hide
13607     */
13608    protected void damageInParent() {
13609        final AttachInfo ai = mAttachInfo;
13610        final ViewParent p = mParent;
13611        if (p != null && ai != null) {
13612            final Rect r = ai.mTmpInvalRect;
13613            r.set(0, 0, mRight - mLeft, mBottom - mTop);
13614            if (mParent instanceof ViewGroup) {
13615                ((ViewGroup) mParent).damageChild(this, r);
13616            } else {
13617                mParent.invalidateChild(this, r);
13618            }
13619        }
13620    }
13621
13622    /**
13623     * Utility method to transform a given Rect by the current matrix of this view.
13624     */
13625    void transformRect(final Rect rect) {
13626        if (!getMatrix().isIdentity()) {
13627            RectF boundingRect = mAttachInfo.mTmpTransformRect;
13628            boundingRect.set(rect);
13629            getMatrix().mapRect(boundingRect);
13630            rect.set((int) Math.floor(boundingRect.left),
13631                    (int) Math.floor(boundingRect.top),
13632                    (int) Math.ceil(boundingRect.right),
13633                    (int) Math.ceil(boundingRect.bottom));
13634        }
13635    }
13636
13637    /**
13638     * Used to indicate that the parent of this view should clear its caches. This functionality
13639     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13640     * which is necessary when various parent-managed properties of the view change, such as
13641     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
13642     * clears the parent caches and does not causes an invalidate event.
13643     *
13644     * @hide
13645     */
13646    protected void invalidateParentCaches() {
13647        if (mParent instanceof View) {
13648            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
13649        }
13650    }
13651
13652    /**
13653     * Used to indicate that the parent of this view should be invalidated. This functionality
13654     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13655     * which is necessary when various parent-managed properties of the view change, such as
13656     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
13657     * an invalidation event to the parent.
13658     *
13659     * @hide
13660     */
13661    protected void invalidateParentIfNeeded() {
13662        if (isHardwareAccelerated() && mParent instanceof View) {
13663            ((View) mParent).invalidate(true);
13664        }
13665    }
13666
13667    /**
13668     * @hide
13669     */
13670    protected void invalidateParentIfNeededAndWasQuickRejected() {
13671        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
13672            // View was rejected last time it was drawn by its parent; this may have changed
13673            invalidateParentIfNeeded();
13674        }
13675    }
13676
13677    /**
13678     * Indicates whether this View is opaque. An opaque View guarantees that it will
13679     * draw all the pixels overlapping its bounds using a fully opaque color.
13680     *
13681     * Subclasses of View should override this method whenever possible to indicate
13682     * whether an instance is opaque. Opaque Views are treated in a special way by
13683     * the View hierarchy, possibly allowing it to perform optimizations during
13684     * invalidate/draw passes.
13685     *
13686     * @return True if this View is guaranteed to be fully opaque, false otherwise.
13687     */
13688    @ViewDebug.ExportedProperty(category = "drawing")
13689    public boolean isOpaque() {
13690        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
13691                getFinalAlpha() >= 1.0f;
13692    }
13693
13694    /**
13695     * @hide
13696     */
13697    protected void computeOpaqueFlags() {
13698        // Opaque if:
13699        //   - Has a background
13700        //   - Background is opaque
13701        //   - Doesn't have scrollbars or scrollbars overlay
13702
13703        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
13704            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
13705        } else {
13706            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
13707        }
13708
13709        final int flags = mViewFlags;
13710        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
13711                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
13712                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
13713            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
13714        } else {
13715            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
13716        }
13717    }
13718
13719    /**
13720     * @hide
13721     */
13722    protected boolean hasOpaqueScrollbars() {
13723        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
13724    }
13725
13726    /**
13727     * @return A handler associated with the thread running the View. This
13728     * handler can be used to pump events in the UI events queue.
13729     */
13730    public Handler getHandler() {
13731        final AttachInfo attachInfo = mAttachInfo;
13732        if (attachInfo != null) {
13733            return attachInfo.mHandler;
13734        }
13735        return null;
13736    }
13737
13738    /**
13739     * Returns the queue of runnable for this view.
13740     *
13741     * @return the queue of runnables for this view
13742     */
13743    private HandlerActionQueue getRunQueue() {
13744        if (mRunQueue == null) {
13745            mRunQueue = new HandlerActionQueue();
13746        }
13747        return mRunQueue;
13748    }
13749
13750    /**
13751     * Gets the view root associated with the View.
13752     * @return The view root, or null if none.
13753     * @hide
13754     */
13755    public ViewRootImpl getViewRootImpl() {
13756        if (mAttachInfo != null) {
13757            return mAttachInfo.mViewRootImpl;
13758        }
13759        return null;
13760    }
13761
13762    /**
13763     * @hide
13764     */
13765    public ThreadedRenderer getHardwareRenderer() {
13766        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
13767    }
13768
13769    /**
13770     * <p>Causes the Runnable to be added to the message queue.
13771     * The runnable will be run on the user interface thread.</p>
13772     *
13773     * @param action The Runnable that will be executed.
13774     *
13775     * @return Returns true if the Runnable was successfully placed in to the
13776     *         message queue.  Returns false on failure, usually because the
13777     *         looper processing the message queue is exiting.
13778     *
13779     * @see #postDelayed
13780     * @see #removeCallbacks
13781     */
13782    public boolean post(Runnable action) {
13783        final AttachInfo attachInfo = mAttachInfo;
13784        if (attachInfo != null) {
13785            return attachInfo.mHandler.post(action);
13786        }
13787
13788        // Postpone the runnable until we know on which thread it needs to run.
13789        // Assume that the runnable will be successfully placed after attach.
13790        getRunQueue().post(action);
13791        return true;
13792    }
13793
13794    /**
13795     * <p>Causes the Runnable to be added to the message queue, to be run
13796     * after the specified amount of time elapses.
13797     * The runnable will be run on the user interface thread.</p>
13798     *
13799     * @param action The Runnable that will be executed.
13800     * @param delayMillis The delay (in milliseconds) until the Runnable
13801     *        will be executed.
13802     *
13803     * @return true if the Runnable was successfully placed in to the
13804     *         message queue.  Returns false on failure, usually because the
13805     *         looper processing the message queue is exiting.  Note that a
13806     *         result of true does not mean the Runnable will be processed --
13807     *         if the looper is quit before the delivery time of the message
13808     *         occurs then the message will be dropped.
13809     *
13810     * @see #post
13811     * @see #removeCallbacks
13812     */
13813    public boolean postDelayed(Runnable action, long delayMillis) {
13814        final AttachInfo attachInfo = mAttachInfo;
13815        if (attachInfo != null) {
13816            return attachInfo.mHandler.postDelayed(action, delayMillis);
13817        }
13818
13819        // Postpone the runnable until we know on which thread it needs to run.
13820        // Assume that the runnable will be successfully placed after attach.
13821        getRunQueue().postDelayed(action, delayMillis);
13822        return true;
13823    }
13824
13825    /**
13826     * <p>Causes the Runnable to execute on the next animation time step.
13827     * The runnable will be run on the user interface thread.</p>
13828     *
13829     * @param action The Runnable that will be executed.
13830     *
13831     * @see #postOnAnimationDelayed
13832     * @see #removeCallbacks
13833     */
13834    public void postOnAnimation(Runnable action) {
13835        final AttachInfo attachInfo = mAttachInfo;
13836        if (attachInfo != null) {
13837            attachInfo.mViewRootImpl.mChoreographer.postCallback(
13838                    Choreographer.CALLBACK_ANIMATION, action, null);
13839        } else {
13840            // Postpone the runnable until we know
13841            // on which thread it needs to run.
13842            getRunQueue().post(action);
13843        }
13844    }
13845
13846    /**
13847     * <p>Causes the Runnable to execute on the next animation time step,
13848     * after the specified amount of time elapses.
13849     * The runnable will be run on the user interface thread.</p>
13850     *
13851     * @param action The Runnable that will be executed.
13852     * @param delayMillis The delay (in milliseconds) until the Runnable
13853     *        will be executed.
13854     *
13855     * @see #postOnAnimation
13856     * @see #removeCallbacks
13857     */
13858    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
13859        final AttachInfo attachInfo = mAttachInfo;
13860        if (attachInfo != null) {
13861            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13862                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
13863        } else {
13864            // Postpone the runnable until we know
13865            // on which thread it needs to run.
13866            getRunQueue().postDelayed(action, delayMillis);
13867        }
13868    }
13869
13870    /**
13871     * <p>Removes the specified Runnable from the message queue.</p>
13872     *
13873     * @param action The Runnable to remove from the message handling queue
13874     *
13875     * @return true if this view could ask the Handler to remove the Runnable,
13876     *         false otherwise. When the returned value is true, the Runnable
13877     *         may or may not have been actually removed from the message queue
13878     *         (for instance, if the Runnable was not in the queue already.)
13879     *
13880     * @see #post
13881     * @see #postDelayed
13882     * @see #postOnAnimation
13883     * @see #postOnAnimationDelayed
13884     */
13885    public boolean removeCallbacks(Runnable action) {
13886        if (action != null) {
13887            final AttachInfo attachInfo = mAttachInfo;
13888            if (attachInfo != null) {
13889                attachInfo.mHandler.removeCallbacks(action);
13890                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13891                        Choreographer.CALLBACK_ANIMATION, action, null);
13892            }
13893            getRunQueue().removeCallbacks(action);
13894        }
13895        return true;
13896    }
13897
13898    /**
13899     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
13900     * Use this to invalidate the View from a non-UI thread.</p>
13901     *
13902     * <p>This method can be invoked from outside of the UI thread
13903     * only when this View is attached to a window.</p>
13904     *
13905     * @see #invalidate()
13906     * @see #postInvalidateDelayed(long)
13907     */
13908    public void postInvalidate() {
13909        postInvalidateDelayed(0);
13910    }
13911
13912    /**
13913     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13914     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
13915     *
13916     * <p>This method can be invoked from outside of the UI thread
13917     * only when this View is attached to a window.</p>
13918     *
13919     * @param left The left coordinate of the rectangle to invalidate.
13920     * @param top The top coordinate of the rectangle to invalidate.
13921     * @param right The right coordinate of the rectangle to invalidate.
13922     * @param bottom The bottom coordinate of the rectangle to invalidate.
13923     *
13924     * @see #invalidate(int, int, int, int)
13925     * @see #invalidate(Rect)
13926     * @see #postInvalidateDelayed(long, int, int, int, int)
13927     */
13928    public void postInvalidate(int left, int top, int right, int bottom) {
13929        postInvalidateDelayed(0, left, top, right, bottom);
13930    }
13931
13932    /**
13933     * <p>Cause an invalidate to happen on a subsequent cycle through the event
13934     * loop. Waits for the specified amount of time.</p>
13935     *
13936     * <p>This method can be invoked from outside of the UI thread
13937     * only when this View is attached to a window.</p>
13938     *
13939     * @param delayMilliseconds the duration in milliseconds to delay the
13940     *         invalidation by
13941     *
13942     * @see #invalidate()
13943     * @see #postInvalidate()
13944     */
13945    public void postInvalidateDelayed(long delayMilliseconds) {
13946        // We try only with the AttachInfo because there's no point in invalidating
13947        // if we are not attached to our window
13948        final AttachInfo attachInfo = mAttachInfo;
13949        if (attachInfo != null) {
13950            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
13951        }
13952    }
13953
13954    /**
13955     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13956     * through the event loop. Waits for the specified amount of time.</p>
13957     *
13958     * <p>This method can be invoked from outside of the UI thread
13959     * only when this View is attached to a window.</p>
13960     *
13961     * @param delayMilliseconds the duration in milliseconds to delay the
13962     *         invalidation by
13963     * @param left The left coordinate of the rectangle to invalidate.
13964     * @param top The top coordinate of the rectangle to invalidate.
13965     * @param right The right coordinate of the rectangle to invalidate.
13966     * @param bottom The bottom coordinate of the rectangle to invalidate.
13967     *
13968     * @see #invalidate(int, int, int, int)
13969     * @see #invalidate(Rect)
13970     * @see #postInvalidate(int, int, int, int)
13971     */
13972    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
13973            int right, int bottom) {
13974
13975        // We try only with the AttachInfo because there's no point in invalidating
13976        // if we are not attached to our window
13977        final AttachInfo attachInfo = mAttachInfo;
13978        if (attachInfo != null) {
13979            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
13980            info.target = this;
13981            info.left = left;
13982            info.top = top;
13983            info.right = right;
13984            info.bottom = bottom;
13985
13986            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
13987        }
13988    }
13989
13990    /**
13991     * <p>Cause an invalidate to happen on the next animation time step, typically the
13992     * next display frame.</p>
13993     *
13994     * <p>This method can be invoked from outside of the UI thread
13995     * only when this View is attached to a window.</p>
13996     *
13997     * @see #invalidate()
13998     */
13999    public void postInvalidateOnAnimation() {
14000        // We try only with the AttachInfo because there's no point in invalidating
14001        // if we are not attached to our window
14002        final AttachInfo attachInfo = mAttachInfo;
14003        if (attachInfo != null) {
14004            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14005        }
14006    }
14007
14008    /**
14009     * <p>Cause an invalidate of the specified area to happen on the next animation
14010     * time step, typically the next display frame.</p>
14011     *
14012     * <p>This method can be invoked from outside of the UI thread
14013     * only when this View is attached to a window.</p>
14014     *
14015     * @param left The left coordinate of the rectangle to invalidate.
14016     * @param top The top coordinate of the rectangle to invalidate.
14017     * @param right The right coordinate of the rectangle to invalidate.
14018     * @param bottom The bottom coordinate of the rectangle to invalidate.
14019     *
14020     * @see #invalidate(int, int, int, int)
14021     * @see #invalidate(Rect)
14022     */
14023    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14024        // We try only with the AttachInfo because there's no point in invalidating
14025        // if we are not attached to our window
14026        final AttachInfo attachInfo = mAttachInfo;
14027        if (attachInfo != null) {
14028            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14029            info.target = this;
14030            info.left = left;
14031            info.top = top;
14032            info.right = right;
14033            info.bottom = bottom;
14034
14035            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14036        }
14037    }
14038
14039    /**
14040     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14041     * This event is sent at most once every
14042     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14043     */
14044    private void postSendViewScrolledAccessibilityEventCallback() {
14045        if (mSendViewScrolledAccessibilityEvent == null) {
14046            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14047        }
14048        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14049            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14050            postDelayed(mSendViewScrolledAccessibilityEvent,
14051                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14052        }
14053    }
14054
14055    /**
14056     * Called by a parent to request that a child update its values for mScrollX
14057     * and mScrollY if necessary. This will typically be done if the child is
14058     * animating a scroll using a {@link android.widget.Scroller Scroller}
14059     * object.
14060     */
14061    public void computeScroll() {
14062    }
14063
14064    /**
14065     * <p>Indicate whether the horizontal edges are faded when the view is
14066     * scrolled horizontally.</p>
14067     *
14068     * @return true if the horizontal edges should are faded on scroll, false
14069     *         otherwise
14070     *
14071     * @see #setHorizontalFadingEdgeEnabled(boolean)
14072     *
14073     * @attr ref android.R.styleable#View_requiresFadingEdge
14074     */
14075    public boolean isHorizontalFadingEdgeEnabled() {
14076        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14077    }
14078
14079    /**
14080     * <p>Define whether the horizontal edges should be faded when this view
14081     * is scrolled horizontally.</p>
14082     *
14083     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14084     *                                    be faded when the view is scrolled
14085     *                                    horizontally
14086     *
14087     * @see #isHorizontalFadingEdgeEnabled()
14088     *
14089     * @attr ref android.R.styleable#View_requiresFadingEdge
14090     */
14091    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14092        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14093            if (horizontalFadingEdgeEnabled) {
14094                initScrollCache();
14095            }
14096
14097            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14098        }
14099    }
14100
14101    /**
14102     * <p>Indicate whether the vertical edges are faded when the view is
14103     * scrolled horizontally.</p>
14104     *
14105     * @return true if the vertical edges should are faded on scroll, false
14106     *         otherwise
14107     *
14108     * @see #setVerticalFadingEdgeEnabled(boolean)
14109     *
14110     * @attr ref android.R.styleable#View_requiresFadingEdge
14111     */
14112    public boolean isVerticalFadingEdgeEnabled() {
14113        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14114    }
14115
14116    /**
14117     * <p>Define whether the vertical edges should be faded when this view
14118     * is scrolled vertically.</p>
14119     *
14120     * @param verticalFadingEdgeEnabled true if the vertical edges should
14121     *                                  be faded when the view is scrolled
14122     *                                  vertically
14123     *
14124     * @see #isVerticalFadingEdgeEnabled()
14125     *
14126     * @attr ref android.R.styleable#View_requiresFadingEdge
14127     */
14128    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14129        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14130            if (verticalFadingEdgeEnabled) {
14131                initScrollCache();
14132            }
14133
14134            mViewFlags ^= FADING_EDGE_VERTICAL;
14135        }
14136    }
14137
14138    /**
14139     * Returns the strength, or intensity, of the top faded edge. The strength is
14140     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14141     * returns 0.0 or 1.0 but no value in between.
14142     *
14143     * Subclasses should override this method to provide a smoother fade transition
14144     * when scrolling occurs.
14145     *
14146     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14147     */
14148    protected float getTopFadingEdgeStrength() {
14149        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14150    }
14151
14152    /**
14153     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14154     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14155     * returns 0.0 or 1.0 but no value in between.
14156     *
14157     * Subclasses should override this method to provide a smoother fade transition
14158     * when scrolling occurs.
14159     *
14160     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14161     */
14162    protected float getBottomFadingEdgeStrength() {
14163        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14164                computeVerticalScrollRange() ? 1.0f : 0.0f;
14165    }
14166
14167    /**
14168     * Returns the strength, or intensity, of the left faded edge. The strength is
14169     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14170     * returns 0.0 or 1.0 but no value in between.
14171     *
14172     * Subclasses should override this method to provide a smoother fade transition
14173     * when scrolling occurs.
14174     *
14175     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14176     */
14177    protected float getLeftFadingEdgeStrength() {
14178        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14179    }
14180
14181    /**
14182     * Returns the strength, or intensity, of the right faded edge. The strength is
14183     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14184     * returns 0.0 or 1.0 but no value in between.
14185     *
14186     * Subclasses should override this method to provide a smoother fade transition
14187     * when scrolling occurs.
14188     *
14189     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14190     */
14191    protected float getRightFadingEdgeStrength() {
14192        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14193                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14194    }
14195
14196    /**
14197     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14198     * scrollbar is not drawn by default.</p>
14199     *
14200     * @return true if the horizontal scrollbar should be painted, false
14201     *         otherwise
14202     *
14203     * @see #setHorizontalScrollBarEnabled(boolean)
14204     */
14205    public boolean isHorizontalScrollBarEnabled() {
14206        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14207    }
14208
14209    /**
14210     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14211     * scrollbar is not drawn by default.</p>
14212     *
14213     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14214     *                                   be painted
14215     *
14216     * @see #isHorizontalScrollBarEnabled()
14217     */
14218    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14219        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14220            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14221            computeOpaqueFlags();
14222            resolvePadding();
14223        }
14224    }
14225
14226    /**
14227     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14228     * scrollbar is not drawn by default.</p>
14229     *
14230     * @return true if the vertical scrollbar should be painted, false
14231     *         otherwise
14232     *
14233     * @see #setVerticalScrollBarEnabled(boolean)
14234     */
14235    public boolean isVerticalScrollBarEnabled() {
14236        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14237    }
14238
14239    /**
14240     * <p>Define whether the vertical scrollbar should be drawn or not. The
14241     * scrollbar is not drawn by default.</p>
14242     *
14243     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14244     *                                 be painted
14245     *
14246     * @see #isVerticalScrollBarEnabled()
14247     */
14248    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14249        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14250            mViewFlags ^= SCROLLBARS_VERTICAL;
14251            computeOpaqueFlags();
14252            resolvePadding();
14253        }
14254    }
14255
14256    /**
14257     * @hide
14258     */
14259    protected void recomputePadding() {
14260        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14261    }
14262
14263    /**
14264     * Define whether scrollbars will fade when the view is not scrolling.
14265     *
14266     * @param fadeScrollbars whether to enable fading
14267     *
14268     * @attr ref android.R.styleable#View_fadeScrollbars
14269     */
14270    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14271        initScrollCache();
14272        final ScrollabilityCache scrollabilityCache = mScrollCache;
14273        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14274        if (fadeScrollbars) {
14275            scrollabilityCache.state = ScrollabilityCache.OFF;
14276        } else {
14277            scrollabilityCache.state = ScrollabilityCache.ON;
14278        }
14279    }
14280
14281    /**
14282     *
14283     * Returns true if scrollbars will fade when this view is not scrolling
14284     *
14285     * @return true if scrollbar fading is enabled
14286     *
14287     * @attr ref android.R.styleable#View_fadeScrollbars
14288     */
14289    public boolean isScrollbarFadingEnabled() {
14290        return mScrollCache != null && mScrollCache.fadeScrollBars;
14291    }
14292
14293    /**
14294     *
14295     * Returns the delay before scrollbars fade.
14296     *
14297     * @return the delay before scrollbars fade
14298     *
14299     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14300     */
14301    public int getScrollBarDefaultDelayBeforeFade() {
14302        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14303                mScrollCache.scrollBarDefaultDelayBeforeFade;
14304    }
14305
14306    /**
14307     * Define the delay before scrollbars fade.
14308     *
14309     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14310     *
14311     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14312     */
14313    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14314        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14315    }
14316
14317    /**
14318     *
14319     * Returns the scrollbar fade duration.
14320     *
14321     * @return the scrollbar fade duration
14322     *
14323     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14324     */
14325    public int getScrollBarFadeDuration() {
14326        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14327                mScrollCache.scrollBarFadeDuration;
14328    }
14329
14330    /**
14331     * Define the scrollbar fade duration.
14332     *
14333     * @param scrollBarFadeDuration - the scrollbar fade duration
14334     *
14335     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14336     */
14337    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14338        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14339    }
14340
14341    /**
14342     *
14343     * Returns the scrollbar size.
14344     *
14345     * @return the scrollbar size
14346     *
14347     * @attr ref android.R.styleable#View_scrollbarSize
14348     */
14349    public int getScrollBarSize() {
14350        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14351                mScrollCache.scrollBarSize;
14352    }
14353
14354    /**
14355     * Define the scrollbar size.
14356     *
14357     * @param scrollBarSize - the scrollbar size
14358     *
14359     * @attr ref android.R.styleable#View_scrollbarSize
14360     */
14361    public void setScrollBarSize(int scrollBarSize) {
14362        getScrollCache().scrollBarSize = scrollBarSize;
14363    }
14364
14365    /**
14366     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14367     * inset. When inset, they add to the padding of the view. And the scrollbars
14368     * can be drawn inside the padding area or on the edge of the view. For example,
14369     * if a view has a background drawable and you want to draw the scrollbars
14370     * inside the padding specified by the drawable, you can use
14371     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14372     * appear at the edge of the view, ignoring the padding, then you can use
14373     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14374     * @param style the style of the scrollbars. Should be one of
14375     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14376     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14377     * @see #SCROLLBARS_INSIDE_OVERLAY
14378     * @see #SCROLLBARS_INSIDE_INSET
14379     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14380     * @see #SCROLLBARS_OUTSIDE_INSET
14381     *
14382     * @attr ref android.R.styleable#View_scrollbarStyle
14383     */
14384    public void setScrollBarStyle(@ScrollBarStyle int style) {
14385        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14386            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14387            computeOpaqueFlags();
14388            resolvePadding();
14389        }
14390    }
14391
14392    /**
14393     * <p>Returns the current scrollbar style.</p>
14394     * @return the current scrollbar style
14395     * @see #SCROLLBARS_INSIDE_OVERLAY
14396     * @see #SCROLLBARS_INSIDE_INSET
14397     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14398     * @see #SCROLLBARS_OUTSIDE_INSET
14399     *
14400     * @attr ref android.R.styleable#View_scrollbarStyle
14401     */
14402    @ViewDebug.ExportedProperty(mapping = {
14403            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14404            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14405            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14406            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14407    })
14408    @ScrollBarStyle
14409    public int getScrollBarStyle() {
14410        return mViewFlags & SCROLLBARS_STYLE_MASK;
14411    }
14412
14413    /**
14414     * <p>Compute the horizontal range that the horizontal scrollbar
14415     * represents.</p>
14416     *
14417     * <p>The range is expressed in arbitrary units that must be the same as the
14418     * units used by {@link #computeHorizontalScrollExtent()} and
14419     * {@link #computeHorizontalScrollOffset()}.</p>
14420     *
14421     * <p>The default range is the drawing width of this view.</p>
14422     *
14423     * @return the total horizontal range represented by the horizontal
14424     *         scrollbar
14425     *
14426     * @see #computeHorizontalScrollExtent()
14427     * @see #computeHorizontalScrollOffset()
14428     * @see android.widget.ScrollBarDrawable
14429     */
14430    protected int computeHorizontalScrollRange() {
14431        return getWidth();
14432    }
14433
14434    /**
14435     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14436     * within the horizontal range. This value is used to compute the position
14437     * of the thumb within the scrollbar's track.</p>
14438     *
14439     * <p>The range is expressed in arbitrary units that must be the same as the
14440     * units used by {@link #computeHorizontalScrollRange()} and
14441     * {@link #computeHorizontalScrollExtent()}.</p>
14442     *
14443     * <p>The default offset is the scroll offset of this view.</p>
14444     *
14445     * @return the horizontal offset of the scrollbar's thumb
14446     *
14447     * @see #computeHorizontalScrollRange()
14448     * @see #computeHorizontalScrollExtent()
14449     * @see android.widget.ScrollBarDrawable
14450     */
14451    protected int computeHorizontalScrollOffset() {
14452        return mScrollX;
14453    }
14454
14455    /**
14456     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14457     * within the horizontal range. This value is used to compute the length
14458     * of the thumb within the scrollbar's track.</p>
14459     *
14460     * <p>The range is expressed in arbitrary units that must be the same as the
14461     * units used by {@link #computeHorizontalScrollRange()} and
14462     * {@link #computeHorizontalScrollOffset()}.</p>
14463     *
14464     * <p>The default extent is the drawing width of this view.</p>
14465     *
14466     * @return the horizontal extent of the scrollbar's thumb
14467     *
14468     * @see #computeHorizontalScrollRange()
14469     * @see #computeHorizontalScrollOffset()
14470     * @see android.widget.ScrollBarDrawable
14471     */
14472    protected int computeHorizontalScrollExtent() {
14473        return getWidth();
14474    }
14475
14476    /**
14477     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
14478     *
14479     * <p>The range is expressed in arbitrary units that must be the same as the
14480     * units used by {@link #computeVerticalScrollExtent()} and
14481     * {@link #computeVerticalScrollOffset()}.</p>
14482     *
14483     * @return the total vertical range represented by the vertical scrollbar
14484     *
14485     * <p>The default range is the drawing height of this view.</p>
14486     *
14487     * @see #computeVerticalScrollExtent()
14488     * @see #computeVerticalScrollOffset()
14489     * @see android.widget.ScrollBarDrawable
14490     */
14491    protected int computeVerticalScrollRange() {
14492        return getHeight();
14493    }
14494
14495    /**
14496     * <p>Compute the vertical offset of the vertical scrollbar's thumb
14497     * within the horizontal range. This value is used to compute the position
14498     * of the thumb within the scrollbar's track.</p>
14499     *
14500     * <p>The range is expressed in arbitrary units that must be the same as the
14501     * units used by {@link #computeVerticalScrollRange()} and
14502     * {@link #computeVerticalScrollExtent()}.</p>
14503     *
14504     * <p>The default offset is the scroll offset of this view.</p>
14505     *
14506     * @return the vertical offset of the scrollbar's thumb
14507     *
14508     * @see #computeVerticalScrollRange()
14509     * @see #computeVerticalScrollExtent()
14510     * @see android.widget.ScrollBarDrawable
14511     */
14512    protected int computeVerticalScrollOffset() {
14513        return mScrollY;
14514    }
14515
14516    /**
14517     * <p>Compute the vertical extent of the vertical scrollbar's thumb
14518     * within the vertical range. This value is used to compute the length
14519     * of the thumb within the scrollbar's track.</p>
14520     *
14521     * <p>The range is expressed in arbitrary units that must be the same as the
14522     * units used by {@link #computeVerticalScrollRange()} and
14523     * {@link #computeVerticalScrollOffset()}.</p>
14524     *
14525     * <p>The default extent is the drawing height of this view.</p>
14526     *
14527     * @return the vertical extent of the scrollbar's thumb
14528     *
14529     * @see #computeVerticalScrollRange()
14530     * @see #computeVerticalScrollOffset()
14531     * @see android.widget.ScrollBarDrawable
14532     */
14533    protected int computeVerticalScrollExtent() {
14534        return getHeight();
14535    }
14536
14537    /**
14538     * Check if this view can be scrolled horizontally in a certain direction.
14539     *
14540     * @param direction Negative to check scrolling left, positive to check scrolling right.
14541     * @return true if this view can be scrolled in the specified direction, false otherwise.
14542     */
14543    public boolean canScrollHorizontally(int direction) {
14544        final int offset = computeHorizontalScrollOffset();
14545        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
14546        if (range == 0) return false;
14547        if (direction < 0) {
14548            return offset > 0;
14549        } else {
14550            return offset < range - 1;
14551        }
14552    }
14553
14554    /**
14555     * Check if this view can be scrolled vertically in a certain direction.
14556     *
14557     * @param direction Negative to check scrolling up, positive to check scrolling down.
14558     * @return true if this view can be scrolled in the specified direction, false otherwise.
14559     */
14560    public boolean canScrollVertically(int direction) {
14561        final int offset = computeVerticalScrollOffset();
14562        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
14563        if (range == 0) return false;
14564        if (direction < 0) {
14565            return offset > 0;
14566        } else {
14567            return offset < range - 1;
14568        }
14569    }
14570
14571    void getScrollIndicatorBounds(@NonNull Rect out) {
14572        out.left = mScrollX;
14573        out.right = mScrollX + mRight - mLeft;
14574        out.top = mScrollY;
14575        out.bottom = mScrollY + mBottom - mTop;
14576    }
14577
14578    private void onDrawScrollIndicators(Canvas c) {
14579        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
14580            // No scroll indicators enabled.
14581            return;
14582        }
14583
14584        final Drawable dr = mScrollIndicatorDrawable;
14585        if (dr == null) {
14586            // Scroll indicators aren't supported here.
14587            return;
14588        }
14589
14590        final int h = dr.getIntrinsicHeight();
14591        final int w = dr.getIntrinsicWidth();
14592        final Rect rect = mAttachInfo.mTmpInvalRect;
14593        getScrollIndicatorBounds(rect);
14594
14595        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
14596            final boolean canScrollUp = canScrollVertically(-1);
14597            if (canScrollUp) {
14598                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
14599                dr.draw(c);
14600            }
14601        }
14602
14603        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
14604            final boolean canScrollDown = canScrollVertically(1);
14605            if (canScrollDown) {
14606                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
14607                dr.draw(c);
14608            }
14609        }
14610
14611        final int leftRtl;
14612        final int rightRtl;
14613        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14614            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
14615            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
14616        } else {
14617            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
14618            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
14619        }
14620
14621        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
14622        if ((mPrivateFlags3 & leftMask) != 0) {
14623            final boolean canScrollLeft = canScrollHorizontally(-1);
14624            if (canScrollLeft) {
14625                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
14626                dr.draw(c);
14627            }
14628        }
14629
14630        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
14631        if ((mPrivateFlags3 & rightMask) != 0) {
14632            final boolean canScrollRight = canScrollHorizontally(1);
14633            if (canScrollRight) {
14634                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
14635                dr.draw(c);
14636            }
14637        }
14638    }
14639
14640    private void getHorizontalScrollBarBounds(Rect bounds) {
14641        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14642        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14643                && !isVerticalScrollBarHidden();
14644        final int size = getHorizontalScrollbarHeight();
14645        final int verticalScrollBarGap = drawVerticalScrollBar ?
14646                getVerticalScrollbarWidth() : 0;
14647        final int width = mRight - mLeft;
14648        final int height = mBottom - mTop;
14649        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
14650        bounds.left = mScrollX + (mPaddingLeft & inside);
14651        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
14652        bounds.bottom = bounds.top + size;
14653    }
14654
14655    private void getVerticalScrollBarBounds(Rect bounds) {
14656        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14657        final int size = getVerticalScrollbarWidth();
14658        int verticalScrollbarPosition = mVerticalScrollbarPosition;
14659        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
14660            verticalScrollbarPosition = isLayoutRtl() ?
14661                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
14662        }
14663        final int width = mRight - mLeft;
14664        final int height = mBottom - mTop;
14665        switch (verticalScrollbarPosition) {
14666            default:
14667            case SCROLLBAR_POSITION_RIGHT:
14668                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
14669                break;
14670            case SCROLLBAR_POSITION_LEFT:
14671                bounds.left = mScrollX + (mUserPaddingLeft & inside);
14672                break;
14673        }
14674        bounds.top = mScrollY + (mPaddingTop & inside);
14675        bounds.right = bounds.left + size;
14676        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
14677    }
14678
14679    /**
14680     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
14681     * scrollbars are painted only if they have been awakened first.</p>
14682     *
14683     * @param canvas the canvas on which to draw the scrollbars
14684     *
14685     * @see #awakenScrollBars(int)
14686     */
14687    protected final void onDrawScrollBars(Canvas canvas) {
14688        // scrollbars are drawn only when the animation is running
14689        final ScrollabilityCache cache = mScrollCache;
14690        if (cache != null) {
14691
14692            int state = cache.state;
14693
14694            if (state == ScrollabilityCache.OFF) {
14695                return;
14696            }
14697
14698            boolean invalidate = false;
14699
14700            if (state == ScrollabilityCache.FADING) {
14701                // We're fading -- get our fade interpolation
14702                if (cache.interpolatorValues == null) {
14703                    cache.interpolatorValues = new float[1];
14704                }
14705
14706                float[] values = cache.interpolatorValues;
14707
14708                // Stops the animation if we're done
14709                if (cache.scrollBarInterpolator.timeToValues(values) ==
14710                        Interpolator.Result.FREEZE_END) {
14711                    cache.state = ScrollabilityCache.OFF;
14712                } else {
14713                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
14714                }
14715
14716                // This will make the scroll bars inval themselves after
14717                // drawing. We only want this when we're fading so that
14718                // we prevent excessive redraws
14719                invalidate = true;
14720            } else {
14721                // We're just on -- but we may have been fading before so
14722                // reset alpha
14723                cache.scrollBar.mutate().setAlpha(255);
14724            }
14725
14726            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
14727            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14728                    && !isVerticalScrollBarHidden();
14729
14730            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
14731                final ScrollBarDrawable scrollBar = cache.scrollBar;
14732
14733                if (drawHorizontalScrollBar) {
14734                    scrollBar.setParameters(computeHorizontalScrollRange(),
14735                                            computeHorizontalScrollOffset(),
14736                                            computeHorizontalScrollExtent(), false);
14737                    final Rect bounds = cache.mScrollBarBounds;
14738                    getHorizontalScrollBarBounds(bounds);
14739                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14740                            bounds.right, bounds.bottom);
14741                    if (invalidate) {
14742                        invalidate(bounds);
14743                    }
14744                }
14745
14746                if (drawVerticalScrollBar) {
14747                    scrollBar.setParameters(computeVerticalScrollRange(),
14748                                            computeVerticalScrollOffset(),
14749                                            computeVerticalScrollExtent(), true);
14750                    final Rect bounds = cache.mScrollBarBounds;
14751                    getVerticalScrollBarBounds(bounds);
14752                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14753                            bounds.right, bounds.bottom);
14754                    if (invalidate) {
14755                        invalidate(bounds);
14756                    }
14757                }
14758            }
14759        }
14760    }
14761
14762    /**
14763     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
14764     * FastScroller is visible.
14765     * @return whether to temporarily hide the vertical scrollbar
14766     * @hide
14767     */
14768    protected boolean isVerticalScrollBarHidden() {
14769        return false;
14770    }
14771
14772    /**
14773     * <p>Draw the horizontal scrollbar if
14774     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
14775     *
14776     * @param canvas the canvas on which to draw the scrollbar
14777     * @param scrollBar the scrollbar's drawable
14778     *
14779     * @see #isHorizontalScrollBarEnabled()
14780     * @see #computeHorizontalScrollRange()
14781     * @see #computeHorizontalScrollExtent()
14782     * @see #computeHorizontalScrollOffset()
14783     * @see android.widget.ScrollBarDrawable
14784     * @hide
14785     */
14786    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
14787            int l, int t, int r, int b) {
14788        scrollBar.setBounds(l, t, r, b);
14789        scrollBar.draw(canvas);
14790    }
14791
14792    /**
14793     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
14794     * returns true.</p>
14795     *
14796     * @param canvas the canvas on which to draw the scrollbar
14797     * @param scrollBar the scrollbar's drawable
14798     *
14799     * @see #isVerticalScrollBarEnabled()
14800     * @see #computeVerticalScrollRange()
14801     * @see #computeVerticalScrollExtent()
14802     * @see #computeVerticalScrollOffset()
14803     * @see android.widget.ScrollBarDrawable
14804     * @hide
14805     */
14806    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
14807            int l, int t, int r, int b) {
14808        scrollBar.setBounds(l, t, r, b);
14809        scrollBar.draw(canvas);
14810    }
14811
14812    /**
14813     * Implement this to do your drawing.
14814     *
14815     * @param canvas the canvas on which the background will be drawn
14816     */
14817    protected void onDraw(Canvas canvas) {
14818    }
14819
14820    /*
14821     * Caller is responsible for calling requestLayout if necessary.
14822     * (This allows addViewInLayout to not request a new layout.)
14823     */
14824    void assignParent(ViewParent parent) {
14825        if (mParent == null) {
14826            mParent = parent;
14827        } else if (parent == null) {
14828            mParent = null;
14829        } else {
14830            throw new RuntimeException("view " + this + " being added, but"
14831                    + " it already has a parent");
14832        }
14833    }
14834
14835    /**
14836     * This is called when the view is attached to a window.  At this point it
14837     * has a Surface and will start drawing.  Note that this function is
14838     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
14839     * however it may be called any time before the first onDraw -- including
14840     * before or after {@link #onMeasure(int, int)}.
14841     *
14842     * @see #onDetachedFromWindow()
14843     */
14844    @CallSuper
14845    protected void onAttachedToWindow() {
14846        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
14847            mParent.requestTransparentRegion(this);
14848        }
14849
14850        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
14851
14852        jumpDrawablesToCurrentState();
14853
14854        resetSubtreeAccessibilityStateChanged();
14855
14856        // rebuild, since Outline not maintained while View is detached
14857        rebuildOutline();
14858
14859        if (isFocused()) {
14860            InputMethodManager imm = InputMethodManager.peekInstance();
14861            if (imm != null) {
14862                imm.focusIn(this);
14863            }
14864        }
14865    }
14866
14867    /**
14868     * Resolve all RTL related properties.
14869     *
14870     * @return true if resolution of RTL properties has been done
14871     *
14872     * @hide
14873     */
14874    public boolean resolveRtlPropertiesIfNeeded() {
14875        if (!needRtlPropertiesResolution()) return false;
14876
14877        // Order is important here: LayoutDirection MUST be resolved first
14878        if (!isLayoutDirectionResolved()) {
14879            resolveLayoutDirection();
14880            resolveLayoutParams();
14881        }
14882        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
14883        if (!isTextDirectionResolved()) {
14884            resolveTextDirection();
14885        }
14886        if (!isTextAlignmentResolved()) {
14887            resolveTextAlignment();
14888        }
14889        // Should resolve Drawables before Padding because we need the layout direction of the
14890        // Drawable to correctly resolve Padding.
14891        if (!areDrawablesResolved()) {
14892            resolveDrawables();
14893        }
14894        if (!isPaddingResolved()) {
14895            resolvePadding();
14896        }
14897        onRtlPropertiesChanged(getLayoutDirection());
14898        return true;
14899    }
14900
14901    /**
14902     * Reset resolution of all RTL related properties.
14903     *
14904     * @hide
14905     */
14906    public void resetRtlProperties() {
14907        resetResolvedLayoutDirection();
14908        resetResolvedTextDirection();
14909        resetResolvedTextAlignment();
14910        resetResolvedPadding();
14911        resetResolvedDrawables();
14912    }
14913
14914    /**
14915     * @see #onScreenStateChanged(int)
14916     */
14917    void dispatchScreenStateChanged(int screenState) {
14918        onScreenStateChanged(screenState);
14919    }
14920
14921    /**
14922     * This method is called whenever the state of the screen this view is
14923     * attached to changes. A state change will usually occurs when the screen
14924     * turns on or off (whether it happens automatically or the user does it
14925     * manually.)
14926     *
14927     * @param screenState The new state of the screen. Can be either
14928     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
14929     */
14930    public void onScreenStateChanged(int screenState) {
14931    }
14932
14933    /**
14934     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
14935     */
14936    private boolean hasRtlSupport() {
14937        return mContext.getApplicationInfo().hasRtlSupport();
14938    }
14939
14940    /**
14941     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
14942     * RTL not supported)
14943     */
14944    private boolean isRtlCompatibilityMode() {
14945        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
14946        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
14947    }
14948
14949    /**
14950     * @return true if RTL properties need resolution.
14951     *
14952     */
14953    private boolean needRtlPropertiesResolution() {
14954        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
14955    }
14956
14957    /**
14958     * Called when any RTL property (layout direction or text direction or text alignment) has
14959     * been changed.
14960     *
14961     * Subclasses need to override this method to take care of cached information that depends on the
14962     * resolved layout direction, or to inform child views that inherit their layout direction.
14963     *
14964     * The default implementation does nothing.
14965     *
14966     * @param layoutDirection the direction of the layout
14967     *
14968     * @see #LAYOUT_DIRECTION_LTR
14969     * @see #LAYOUT_DIRECTION_RTL
14970     */
14971    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
14972    }
14973
14974    /**
14975     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
14976     * that the parent directionality can and will be resolved before its children.
14977     *
14978     * @return true if resolution has been done, false otherwise.
14979     *
14980     * @hide
14981     */
14982    public boolean resolveLayoutDirection() {
14983        // Clear any previous layout direction resolution
14984        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
14985
14986        if (hasRtlSupport()) {
14987            // Set resolved depending on layout direction
14988            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
14989                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
14990                case LAYOUT_DIRECTION_INHERIT:
14991                    // We cannot resolve yet. LTR is by default and let the resolution happen again
14992                    // later to get the correct resolved value
14993                    if (!canResolveLayoutDirection()) return false;
14994
14995                    // Parent has not yet resolved, LTR is still the default
14996                    try {
14997                        if (!mParent.isLayoutDirectionResolved()) return false;
14998
14999                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15000                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15001                        }
15002                    } catch (AbstractMethodError e) {
15003                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15004                                " does not fully implement ViewParent", e);
15005                    }
15006                    break;
15007                case LAYOUT_DIRECTION_RTL:
15008                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15009                    break;
15010                case LAYOUT_DIRECTION_LOCALE:
15011                    if((LAYOUT_DIRECTION_RTL ==
15012                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15013                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15014                    }
15015                    break;
15016                default:
15017                    // Nothing to do, LTR by default
15018            }
15019        }
15020
15021        // Set to resolved
15022        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15023        return true;
15024    }
15025
15026    /**
15027     * Check if layout direction resolution can be done.
15028     *
15029     * @return true if layout direction resolution can be done otherwise return false.
15030     */
15031    public boolean canResolveLayoutDirection() {
15032        switch (getRawLayoutDirection()) {
15033            case LAYOUT_DIRECTION_INHERIT:
15034                if (mParent != null) {
15035                    try {
15036                        return mParent.canResolveLayoutDirection();
15037                    } catch (AbstractMethodError e) {
15038                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15039                                " does not fully implement ViewParent", e);
15040                    }
15041                }
15042                return false;
15043
15044            default:
15045                return true;
15046        }
15047    }
15048
15049    /**
15050     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15051     * {@link #onMeasure(int, int)}.
15052     *
15053     * @hide
15054     */
15055    public void resetResolvedLayoutDirection() {
15056        // Reset the current resolved bits
15057        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15058    }
15059
15060    /**
15061     * @return true if the layout direction is inherited.
15062     *
15063     * @hide
15064     */
15065    public boolean isLayoutDirectionInherited() {
15066        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15067    }
15068
15069    /**
15070     * @return true if layout direction has been resolved.
15071     */
15072    public boolean isLayoutDirectionResolved() {
15073        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15074    }
15075
15076    /**
15077     * Return if padding has been resolved
15078     *
15079     * @hide
15080     */
15081    boolean isPaddingResolved() {
15082        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15083    }
15084
15085    /**
15086     * Resolves padding depending on layout direction, if applicable, and
15087     * recomputes internal padding values to adjust for scroll bars.
15088     *
15089     * @hide
15090     */
15091    public void resolvePadding() {
15092        final int resolvedLayoutDirection = getLayoutDirection();
15093
15094        if (!isRtlCompatibilityMode()) {
15095            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15096            // If start / end padding are defined, they will be resolved (hence overriding) to
15097            // left / right or right / left depending on the resolved layout direction.
15098            // If start / end padding are not defined, use the left / right ones.
15099            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15100                Rect padding = sThreadLocal.get();
15101                if (padding == null) {
15102                    padding = new Rect();
15103                    sThreadLocal.set(padding);
15104                }
15105                mBackground.getPadding(padding);
15106                if (!mLeftPaddingDefined) {
15107                    mUserPaddingLeftInitial = padding.left;
15108                }
15109                if (!mRightPaddingDefined) {
15110                    mUserPaddingRightInitial = padding.right;
15111                }
15112            }
15113            switch (resolvedLayoutDirection) {
15114                case LAYOUT_DIRECTION_RTL:
15115                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15116                        mUserPaddingRight = mUserPaddingStart;
15117                    } else {
15118                        mUserPaddingRight = mUserPaddingRightInitial;
15119                    }
15120                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15121                        mUserPaddingLeft = mUserPaddingEnd;
15122                    } else {
15123                        mUserPaddingLeft = mUserPaddingLeftInitial;
15124                    }
15125                    break;
15126                case LAYOUT_DIRECTION_LTR:
15127                default:
15128                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15129                        mUserPaddingLeft = mUserPaddingStart;
15130                    } else {
15131                        mUserPaddingLeft = mUserPaddingLeftInitial;
15132                    }
15133                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15134                        mUserPaddingRight = mUserPaddingEnd;
15135                    } else {
15136                        mUserPaddingRight = mUserPaddingRightInitial;
15137                    }
15138            }
15139
15140            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15141        }
15142
15143        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15144        onRtlPropertiesChanged(resolvedLayoutDirection);
15145
15146        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15147    }
15148
15149    /**
15150     * Reset the resolved layout direction.
15151     *
15152     * @hide
15153     */
15154    public void resetResolvedPadding() {
15155        resetResolvedPaddingInternal();
15156    }
15157
15158    /**
15159     * Used when we only want to reset *this* view's padding and not trigger overrides
15160     * in ViewGroup that reset children too.
15161     */
15162    void resetResolvedPaddingInternal() {
15163        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15164    }
15165
15166    /**
15167     * This is called when the view is detached from a window.  At this point it
15168     * no longer has a surface for drawing.
15169     *
15170     * @see #onAttachedToWindow()
15171     */
15172    @CallSuper
15173    protected void onDetachedFromWindow() {
15174    }
15175
15176    /**
15177     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15178     * after onDetachedFromWindow().
15179     *
15180     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15181     * The super method should be called at the end of the overridden method to ensure
15182     * subclasses are destroyed first
15183     *
15184     * @hide
15185     */
15186    @CallSuper
15187    protected void onDetachedFromWindowInternal() {
15188        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15189        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15190
15191        removeUnsetPressCallback();
15192        removeLongPressCallback();
15193        removePerformClickCallback();
15194        removeSendViewScrolledAccessibilityEventCallback();
15195        stopNestedScroll();
15196
15197        // Anything that started animating right before detach should already
15198        // be in its final state when re-attached.
15199        jumpDrawablesToCurrentState();
15200
15201        destroyDrawingCache();
15202
15203        cleanupDraw();
15204        releasePointerCapture();
15205        mCurrentAnimation = null;
15206    }
15207
15208    private void cleanupDraw() {
15209        resetDisplayList();
15210        if (mAttachInfo != null) {
15211            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15212        }
15213    }
15214
15215    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15216    }
15217
15218    /**
15219     * @return The number of times this view has been attached to a window
15220     */
15221    protected int getWindowAttachCount() {
15222        return mWindowAttachCount;
15223    }
15224
15225    /**
15226     * Retrieve a unique token identifying the window this view is attached to.
15227     * @return Return the window's token for use in
15228     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15229     */
15230    public IBinder getWindowToken() {
15231        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15232    }
15233
15234    /**
15235     * Retrieve the {@link WindowId} for the window this view is
15236     * currently attached to.
15237     */
15238    public WindowId getWindowId() {
15239        if (mAttachInfo == null) {
15240            return null;
15241        }
15242        if (mAttachInfo.mWindowId == null) {
15243            try {
15244                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15245                        mAttachInfo.mWindowToken);
15246                mAttachInfo.mWindowId = new WindowId(
15247                        mAttachInfo.mIWindowId);
15248            } catch (RemoteException e) {
15249            }
15250        }
15251        return mAttachInfo.mWindowId;
15252    }
15253
15254    /**
15255     * Retrieve a unique token identifying the top-level "real" window of
15256     * the window that this view is attached to.  That is, this is like
15257     * {@link #getWindowToken}, except if the window this view in is a panel
15258     * window (attached to another containing window), then the token of
15259     * the containing window is returned instead.
15260     *
15261     * @return Returns the associated window token, either
15262     * {@link #getWindowToken()} or the containing window's token.
15263     */
15264    public IBinder getApplicationWindowToken() {
15265        AttachInfo ai = mAttachInfo;
15266        if (ai != null) {
15267            IBinder appWindowToken = ai.mPanelParentWindowToken;
15268            if (appWindowToken == null) {
15269                appWindowToken = ai.mWindowToken;
15270            }
15271            return appWindowToken;
15272        }
15273        return null;
15274    }
15275
15276    /**
15277     * Gets the logical display to which the view's window has been attached.
15278     *
15279     * @return The logical display, or null if the view is not currently attached to a window.
15280     */
15281    public Display getDisplay() {
15282        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15283    }
15284
15285    /**
15286     * Retrieve private session object this view hierarchy is using to
15287     * communicate with the window manager.
15288     * @return the session object to communicate with the window manager
15289     */
15290    /*package*/ IWindowSession getWindowSession() {
15291        return mAttachInfo != null ? mAttachInfo.mSession : null;
15292    }
15293
15294    /**
15295     * Return the visibility value of the least visible component passed.
15296     */
15297    int combineVisibility(int vis1, int vis2) {
15298        // This works because VISIBLE < INVISIBLE < GONE.
15299        return Math.max(vis1, vis2);
15300    }
15301
15302    /**
15303     * @param info the {@link android.view.View.AttachInfo} to associated with
15304     *        this view
15305     */
15306    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15307        mAttachInfo = info;
15308        if (mOverlay != null) {
15309            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15310        }
15311        mWindowAttachCount++;
15312        // We will need to evaluate the drawable state at least once.
15313        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15314        if (mFloatingTreeObserver != null) {
15315            info.mTreeObserver.merge(mFloatingTreeObserver);
15316            mFloatingTreeObserver = null;
15317        }
15318
15319        registerPendingFrameMetricsObservers();
15320
15321        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15322            mAttachInfo.mScrollContainers.add(this);
15323            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15324        }
15325        // Transfer all pending runnables.
15326        if (mRunQueue != null) {
15327            mRunQueue.executeActions(info.mHandler);
15328            mRunQueue = null;
15329        }
15330        performCollectViewAttributes(mAttachInfo, visibility);
15331        onAttachedToWindow();
15332
15333        ListenerInfo li = mListenerInfo;
15334        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15335                li != null ? li.mOnAttachStateChangeListeners : null;
15336        if (listeners != null && listeners.size() > 0) {
15337            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15338            // perform the dispatching. The iterator is a safe guard against listeners that
15339            // could mutate the list by calling the various add/remove methods. This prevents
15340            // the array from being modified while we iterate it.
15341            for (OnAttachStateChangeListener listener : listeners) {
15342                listener.onViewAttachedToWindow(this);
15343            }
15344        }
15345
15346        int vis = info.mWindowVisibility;
15347        if (vis != GONE) {
15348            onWindowVisibilityChanged(vis);
15349            if (isShown()) {
15350                // Calling onVisibilityChanged directly here since the subtree will also
15351                // receive dispatchAttachedToWindow and this same call
15352                onVisibilityAggregated(vis == VISIBLE);
15353            }
15354        }
15355
15356        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15357        // As all views in the subtree will already receive dispatchAttachedToWindow
15358        // traversing the subtree again here is not desired.
15359        onVisibilityChanged(this, visibility);
15360
15361        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15362            // If nobody has evaluated the drawable state yet, then do it now.
15363            refreshDrawableState();
15364        }
15365        needGlobalAttributesUpdate(false);
15366    }
15367
15368    void dispatchDetachedFromWindow() {
15369        AttachInfo info = mAttachInfo;
15370        if (info != null) {
15371            int vis = info.mWindowVisibility;
15372            if (vis != GONE) {
15373                onWindowVisibilityChanged(GONE);
15374                if (isShown()) {
15375                    // Invoking onVisibilityAggregated directly here since the subtree
15376                    // will also receive detached from window
15377                    onVisibilityAggregated(false);
15378                }
15379            }
15380        }
15381
15382        onDetachedFromWindow();
15383        onDetachedFromWindowInternal();
15384
15385        InputMethodManager imm = InputMethodManager.peekInstance();
15386        if (imm != null) {
15387            imm.onViewDetachedFromWindow(this);
15388        }
15389
15390        ListenerInfo li = mListenerInfo;
15391        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15392                li != null ? li.mOnAttachStateChangeListeners : null;
15393        if (listeners != null && listeners.size() > 0) {
15394            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15395            // perform the dispatching. The iterator is a safe guard against listeners that
15396            // could mutate the list by calling the various add/remove methods. This prevents
15397            // the array from being modified while we iterate it.
15398            for (OnAttachStateChangeListener listener : listeners) {
15399                listener.onViewDetachedFromWindow(this);
15400            }
15401        }
15402
15403        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15404            mAttachInfo.mScrollContainers.remove(this);
15405            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15406        }
15407
15408        mAttachInfo = null;
15409        if (mOverlay != null) {
15410            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15411        }
15412    }
15413
15414    /**
15415     * Cancel any deferred high-level input events that were previously posted to the event queue.
15416     *
15417     * <p>Many views post high-level events such as click handlers to the event queue
15418     * to run deferred in order to preserve a desired user experience - clearing visible
15419     * pressed states before executing, etc. This method will abort any events of this nature
15420     * that are currently in flight.</p>
15421     *
15422     * <p>Custom views that generate their own high-level deferred input events should override
15423     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15424     *
15425     * <p>This will also cancel pending input events for any child views.</p>
15426     *
15427     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15428     * This will not impact newer events posted after this call that may occur as a result of
15429     * lower-level input events still waiting in the queue. If you are trying to prevent
15430     * double-submitted  events for the duration of some sort of asynchronous transaction
15431     * you should also take other steps to protect against unexpected double inputs e.g. calling
15432     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15433     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15434     */
15435    public final void cancelPendingInputEvents() {
15436        dispatchCancelPendingInputEvents();
15437    }
15438
15439    /**
15440     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
15441     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
15442     */
15443    void dispatchCancelPendingInputEvents() {
15444        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
15445        onCancelPendingInputEvents();
15446        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
15447            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
15448                    " did not call through to super.onCancelPendingInputEvents()");
15449        }
15450    }
15451
15452    /**
15453     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
15454     * a parent view.
15455     *
15456     * <p>This method is responsible for removing any pending high-level input events that were
15457     * posted to the event queue to run later. Custom view classes that post their own deferred
15458     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
15459     * {@link android.os.Handler} should override this method, call
15460     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
15461     * </p>
15462     */
15463    public void onCancelPendingInputEvents() {
15464        removePerformClickCallback();
15465        cancelLongPress();
15466        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
15467    }
15468
15469    /**
15470     * Store this view hierarchy's frozen state into the given container.
15471     *
15472     * @param container The SparseArray in which to save the view's state.
15473     *
15474     * @see #restoreHierarchyState(android.util.SparseArray)
15475     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15476     * @see #onSaveInstanceState()
15477     */
15478    public void saveHierarchyState(SparseArray<Parcelable> container) {
15479        dispatchSaveInstanceState(container);
15480    }
15481
15482    /**
15483     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
15484     * this view and its children. May be overridden to modify how freezing happens to a
15485     * view's children; for example, some views may want to not store state for their children.
15486     *
15487     * @param container The SparseArray in which to save the view's state.
15488     *
15489     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15490     * @see #saveHierarchyState(android.util.SparseArray)
15491     * @see #onSaveInstanceState()
15492     */
15493    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
15494        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
15495            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15496            Parcelable state = onSaveInstanceState();
15497            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15498                throw new IllegalStateException(
15499                        "Derived class did not call super.onSaveInstanceState()");
15500            }
15501            if (state != null) {
15502                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
15503                // + ": " + state);
15504                container.put(mID, state);
15505            }
15506        }
15507    }
15508
15509    /**
15510     * Hook allowing a view to generate a representation of its internal state
15511     * that can later be used to create a new instance with that same state.
15512     * This state should only contain information that is not persistent or can
15513     * not be reconstructed later. For example, you will never store your
15514     * current position on screen because that will be computed again when a
15515     * new instance of the view is placed in its view hierarchy.
15516     * <p>
15517     * Some examples of things you may store here: the current cursor position
15518     * in a text view (but usually not the text itself since that is stored in a
15519     * content provider or other persistent storage), the currently selected
15520     * item in a list view.
15521     *
15522     * @return Returns a Parcelable object containing the view's current dynamic
15523     *         state, or null if there is nothing interesting to save. The
15524     *         default implementation returns null.
15525     * @see #onRestoreInstanceState(android.os.Parcelable)
15526     * @see #saveHierarchyState(android.util.SparseArray)
15527     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15528     * @see #setSaveEnabled(boolean)
15529     */
15530    @CallSuper
15531    protected Parcelable onSaveInstanceState() {
15532        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15533        if (mStartActivityRequestWho != null) {
15534            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
15535            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
15536            return state;
15537        }
15538        return BaseSavedState.EMPTY_STATE;
15539    }
15540
15541    /**
15542     * Restore this view hierarchy's frozen state from the given container.
15543     *
15544     * @param container The SparseArray which holds previously frozen states.
15545     *
15546     * @see #saveHierarchyState(android.util.SparseArray)
15547     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15548     * @see #onRestoreInstanceState(android.os.Parcelable)
15549     */
15550    public void restoreHierarchyState(SparseArray<Parcelable> container) {
15551        dispatchRestoreInstanceState(container);
15552    }
15553
15554    /**
15555     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
15556     * state for this view and its children. May be overridden to modify how restoring
15557     * happens to a view's children; for example, some views may want to not store state
15558     * for their children.
15559     *
15560     * @param container The SparseArray which holds previously saved state.
15561     *
15562     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15563     * @see #restoreHierarchyState(android.util.SparseArray)
15564     * @see #onRestoreInstanceState(android.os.Parcelable)
15565     */
15566    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
15567        if (mID != NO_ID) {
15568            Parcelable state = container.get(mID);
15569            if (state != null) {
15570                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
15571                // + ": " + state);
15572                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15573                onRestoreInstanceState(state);
15574                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15575                    throw new IllegalStateException(
15576                            "Derived class did not call super.onRestoreInstanceState()");
15577                }
15578            }
15579        }
15580    }
15581
15582    /**
15583     * Hook allowing a view to re-apply a representation of its internal state that had previously
15584     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
15585     * null state.
15586     *
15587     * @param state The frozen state that had previously been returned by
15588     *        {@link #onSaveInstanceState}.
15589     *
15590     * @see #onSaveInstanceState()
15591     * @see #restoreHierarchyState(android.util.SparseArray)
15592     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15593     */
15594    @CallSuper
15595    protected void onRestoreInstanceState(Parcelable state) {
15596        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15597        if (state != null && !(state instanceof AbsSavedState)) {
15598            throw new IllegalArgumentException("Wrong state class, expecting View State but "
15599                    + "received " + state.getClass().toString() + " instead. This usually happens "
15600                    + "when two views of different type have the same id in the same hierarchy. "
15601                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
15602                    + "other views do not use the same id.");
15603        }
15604        if (state != null && state instanceof BaseSavedState) {
15605            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
15606        }
15607    }
15608
15609    /**
15610     * <p>Return the time at which the drawing of the view hierarchy started.</p>
15611     *
15612     * @return the drawing start time in milliseconds
15613     */
15614    public long getDrawingTime() {
15615        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
15616    }
15617
15618    /**
15619     * <p>Enables or disables the duplication of the parent's state into this view. When
15620     * duplication is enabled, this view gets its drawable state from its parent rather
15621     * than from its own internal properties.</p>
15622     *
15623     * <p>Note: in the current implementation, setting this property to true after the
15624     * view was added to a ViewGroup might have no effect at all. This property should
15625     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
15626     *
15627     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
15628     * property is enabled, an exception will be thrown.</p>
15629     *
15630     * <p>Note: if the child view uses and updates additional states which are unknown to the
15631     * parent, these states should not be affected by this method.</p>
15632     *
15633     * @param enabled True to enable duplication of the parent's drawable state, false
15634     *                to disable it.
15635     *
15636     * @see #getDrawableState()
15637     * @see #isDuplicateParentStateEnabled()
15638     */
15639    public void setDuplicateParentStateEnabled(boolean enabled) {
15640        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
15641    }
15642
15643    /**
15644     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
15645     *
15646     * @return True if this view's drawable state is duplicated from the parent,
15647     *         false otherwise
15648     *
15649     * @see #getDrawableState()
15650     * @see #setDuplicateParentStateEnabled(boolean)
15651     */
15652    public boolean isDuplicateParentStateEnabled() {
15653        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
15654    }
15655
15656    /**
15657     * <p>Specifies the type of layer backing this view. The layer can be
15658     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15659     * {@link #LAYER_TYPE_HARDWARE}.</p>
15660     *
15661     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15662     * instance that controls how the layer is composed on screen. The following
15663     * properties of the paint are taken into account when composing the layer:</p>
15664     * <ul>
15665     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15666     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15667     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15668     * </ul>
15669     *
15670     * <p>If this view has an alpha value set to < 1.0 by calling
15671     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
15672     * by this view's alpha value.</p>
15673     *
15674     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
15675     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
15676     * for more information on when and how to use layers.</p>
15677     *
15678     * @param layerType The type of layer to use with this view, must be one of
15679     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15680     *        {@link #LAYER_TYPE_HARDWARE}
15681     * @param paint The paint used to compose the layer. This argument is optional
15682     *        and can be null. It is ignored when the layer type is
15683     *        {@link #LAYER_TYPE_NONE}
15684     *
15685     * @see #getLayerType()
15686     * @see #LAYER_TYPE_NONE
15687     * @see #LAYER_TYPE_SOFTWARE
15688     * @see #LAYER_TYPE_HARDWARE
15689     * @see #setAlpha(float)
15690     *
15691     * @attr ref android.R.styleable#View_layerType
15692     */
15693    public void setLayerType(int layerType, @Nullable Paint paint) {
15694        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
15695            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
15696                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
15697        }
15698
15699        boolean typeChanged = mRenderNode.setLayerType(layerType);
15700
15701        if (!typeChanged) {
15702            setLayerPaint(paint);
15703            return;
15704        }
15705
15706        // Destroy any previous software drawing cache if needed
15707        if (mLayerType == LAYER_TYPE_SOFTWARE) {
15708            destroyDrawingCache();
15709        }
15710
15711        mLayerType = layerType;
15712        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
15713        mRenderNode.setLayerPaint(mLayerPaint);
15714
15715        // draw() behaves differently if we are on a layer, so we need to
15716        // invalidate() here
15717        invalidateParentCaches();
15718        invalidate(true);
15719    }
15720
15721    /**
15722     * Updates the {@link Paint} object used with the current layer (used only if the current
15723     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
15724     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
15725     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
15726     * ensure that the view gets redrawn immediately.
15727     *
15728     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15729     * instance that controls how the layer is composed on screen. The following
15730     * properties of the paint are taken into account when composing the layer:</p>
15731     * <ul>
15732     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15733     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15734     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15735     * </ul>
15736     *
15737     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
15738     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
15739     *
15740     * @param paint The paint used to compose the layer. This argument is optional
15741     *        and can be null. It is ignored when the layer type is
15742     *        {@link #LAYER_TYPE_NONE}
15743     *
15744     * @see #setLayerType(int, android.graphics.Paint)
15745     */
15746    public void setLayerPaint(@Nullable Paint paint) {
15747        int layerType = getLayerType();
15748        if (layerType != LAYER_TYPE_NONE) {
15749            mLayerPaint = paint;
15750            if (layerType == LAYER_TYPE_HARDWARE) {
15751                if (mRenderNode.setLayerPaint(paint)) {
15752                    invalidateViewProperty(false, false);
15753                }
15754            } else {
15755                invalidate();
15756            }
15757        }
15758    }
15759
15760    /**
15761     * Indicates what type of layer is currently associated with this view. By default
15762     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
15763     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
15764     * for more information on the different types of layers.
15765     *
15766     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15767     *         {@link #LAYER_TYPE_HARDWARE}
15768     *
15769     * @see #setLayerType(int, android.graphics.Paint)
15770     * @see #buildLayer()
15771     * @see #LAYER_TYPE_NONE
15772     * @see #LAYER_TYPE_SOFTWARE
15773     * @see #LAYER_TYPE_HARDWARE
15774     */
15775    public int getLayerType() {
15776        return mLayerType;
15777    }
15778
15779    /**
15780     * Forces this view's layer to be created and this view to be rendered
15781     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
15782     * invoking this method will have no effect.
15783     *
15784     * This method can for instance be used to render a view into its layer before
15785     * starting an animation. If this view is complex, rendering into the layer
15786     * before starting the animation will avoid skipping frames.
15787     *
15788     * @throws IllegalStateException If this view is not attached to a window
15789     *
15790     * @see #setLayerType(int, android.graphics.Paint)
15791     */
15792    public void buildLayer() {
15793        if (mLayerType == LAYER_TYPE_NONE) return;
15794
15795        final AttachInfo attachInfo = mAttachInfo;
15796        if (attachInfo == null) {
15797            throw new IllegalStateException("This view must be attached to a window first");
15798        }
15799
15800        if (getWidth() == 0 || getHeight() == 0) {
15801            return;
15802        }
15803
15804        switch (mLayerType) {
15805            case LAYER_TYPE_HARDWARE:
15806                updateDisplayListIfDirty();
15807                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
15808                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
15809                }
15810                break;
15811            case LAYER_TYPE_SOFTWARE:
15812                buildDrawingCache(true);
15813                break;
15814        }
15815    }
15816
15817    /**
15818     * Destroys all hardware rendering resources. This method is invoked
15819     * when the system needs to reclaim resources. Upon execution of this
15820     * method, you should free any OpenGL resources created by the view.
15821     *
15822     * Note: you <strong>must</strong> call
15823     * <code>super.destroyHardwareResources()</code> when overriding
15824     * this method.
15825     *
15826     * @hide
15827     */
15828    @CallSuper
15829    protected void destroyHardwareResources() {
15830        // Although the Layer will be destroyed by RenderNode, we want to release
15831        // the staging display list, which is also a signal to RenderNode that it's
15832        // safe to free its copy of the display list as it knows that we will
15833        // push an updated DisplayList if we try to draw again
15834        resetDisplayList();
15835    }
15836
15837    /**
15838     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
15839     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
15840     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
15841     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
15842     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
15843     * null.</p>
15844     *
15845     * <p>Enabling the drawing cache is similar to
15846     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
15847     * acceleration is turned off. When hardware acceleration is turned on, enabling the
15848     * drawing cache has no effect on rendering because the system uses a different mechanism
15849     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
15850     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
15851     * for information on how to enable software and hardware layers.</p>
15852     *
15853     * <p>This API can be used to manually generate
15854     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
15855     * {@link #getDrawingCache()}.</p>
15856     *
15857     * @param enabled true to enable the drawing cache, false otherwise
15858     *
15859     * @see #isDrawingCacheEnabled()
15860     * @see #getDrawingCache()
15861     * @see #buildDrawingCache()
15862     * @see #setLayerType(int, android.graphics.Paint)
15863     */
15864    public void setDrawingCacheEnabled(boolean enabled) {
15865        mCachingFailed = false;
15866        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
15867    }
15868
15869    /**
15870     * <p>Indicates whether the drawing cache is enabled for this view.</p>
15871     *
15872     * @return true if the drawing cache is enabled
15873     *
15874     * @see #setDrawingCacheEnabled(boolean)
15875     * @see #getDrawingCache()
15876     */
15877    @ViewDebug.ExportedProperty(category = "drawing")
15878    public boolean isDrawingCacheEnabled() {
15879        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
15880    }
15881
15882    /**
15883     * Debugging utility which recursively outputs the dirty state of a view and its
15884     * descendants.
15885     *
15886     * @hide
15887     */
15888    @SuppressWarnings({"UnusedDeclaration"})
15889    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
15890        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
15891                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
15892                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
15893                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
15894        if (clear) {
15895            mPrivateFlags &= clearMask;
15896        }
15897        if (this instanceof ViewGroup) {
15898            ViewGroup parent = (ViewGroup) this;
15899            final int count = parent.getChildCount();
15900            for (int i = 0; i < count; i++) {
15901                final View child = parent.getChildAt(i);
15902                child.outputDirtyFlags(indent + "  ", clear, clearMask);
15903            }
15904        }
15905    }
15906
15907    /**
15908     * This method is used by ViewGroup to cause its children to restore or recreate their
15909     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
15910     * to recreate its own display list, which would happen if it went through the normal
15911     * draw/dispatchDraw mechanisms.
15912     *
15913     * @hide
15914     */
15915    protected void dispatchGetDisplayList() {}
15916
15917    /**
15918     * A view that is not attached or hardware accelerated cannot create a display list.
15919     * This method checks these conditions and returns the appropriate result.
15920     *
15921     * @return true if view has the ability to create a display list, false otherwise.
15922     *
15923     * @hide
15924     */
15925    public boolean canHaveDisplayList() {
15926        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
15927    }
15928
15929    /**
15930     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
15931     * @hide
15932     */
15933    @NonNull
15934    public RenderNode updateDisplayListIfDirty() {
15935        final RenderNode renderNode = mRenderNode;
15936        if (!canHaveDisplayList()) {
15937            // can't populate RenderNode, don't try
15938            return renderNode;
15939        }
15940
15941        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
15942                || !renderNode.isValid()
15943                || (mRecreateDisplayList)) {
15944            // Don't need to recreate the display list, just need to tell our
15945            // children to restore/recreate theirs
15946            if (renderNode.isValid()
15947                    && !mRecreateDisplayList) {
15948                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
15949                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15950                dispatchGetDisplayList();
15951
15952                return renderNode; // no work needed
15953            }
15954
15955            // If we got here, we're recreating it. Mark it as such to ensure that
15956            // we copy in child display lists into ours in drawChild()
15957            mRecreateDisplayList = true;
15958
15959            int width = mRight - mLeft;
15960            int height = mBottom - mTop;
15961            int layerType = getLayerType();
15962
15963            final DisplayListCanvas canvas = renderNode.start(width, height);
15964            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
15965
15966            try {
15967                if (layerType == LAYER_TYPE_SOFTWARE) {
15968                    buildDrawingCache(true);
15969                    Bitmap cache = getDrawingCache(true);
15970                    if (cache != null) {
15971                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
15972                    }
15973                } else {
15974                    computeScroll();
15975
15976                    canvas.translate(-mScrollX, -mScrollY);
15977                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
15978                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15979
15980                    // Fast path for layouts with no backgrounds
15981                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15982                        dispatchDraw(canvas);
15983                        if (mOverlay != null && !mOverlay.isEmpty()) {
15984                            mOverlay.getOverlayView().draw(canvas);
15985                        }
15986                    } else {
15987                        draw(canvas);
15988                    }
15989                }
15990            } finally {
15991                renderNode.end(canvas);
15992                setDisplayListProperties(renderNode);
15993            }
15994        } else {
15995            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
15996            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15997        }
15998        return renderNode;
15999    }
16000
16001    private void resetDisplayList() {
16002        if (mRenderNode.isValid()) {
16003            mRenderNode.discardDisplayList();
16004        }
16005
16006        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16007            mBackgroundRenderNode.discardDisplayList();
16008        }
16009    }
16010
16011    /**
16012     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16013     *
16014     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16015     *
16016     * @see #getDrawingCache(boolean)
16017     */
16018    public Bitmap getDrawingCache() {
16019        return getDrawingCache(false);
16020    }
16021
16022    /**
16023     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16024     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16025     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16026     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16027     * request the drawing cache by calling this method and draw it on screen if the
16028     * returned bitmap is not null.</p>
16029     *
16030     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16031     * this method will create a bitmap of the same size as this view. Because this bitmap
16032     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16033     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16034     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16035     * size than the view. This implies that your application must be able to handle this
16036     * size.</p>
16037     *
16038     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16039     *        the current density of the screen when the application is in compatibility
16040     *        mode.
16041     *
16042     * @return A bitmap representing this view or null if cache is disabled.
16043     *
16044     * @see #setDrawingCacheEnabled(boolean)
16045     * @see #isDrawingCacheEnabled()
16046     * @see #buildDrawingCache(boolean)
16047     * @see #destroyDrawingCache()
16048     */
16049    public Bitmap getDrawingCache(boolean autoScale) {
16050        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16051            return null;
16052        }
16053        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16054            buildDrawingCache(autoScale);
16055        }
16056        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16057    }
16058
16059    /**
16060     * <p>Frees the resources used by the drawing cache. If you call
16061     * {@link #buildDrawingCache()} manually without calling
16062     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16063     * should cleanup the cache with this method afterwards.</p>
16064     *
16065     * @see #setDrawingCacheEnabled(boolean)
16066     * @see #buildDrawingCache()
16067     * @see #getDrawingCache()
16068     */
16069    public void destroyDrawingCache() {
16070        if (mDrawingCache != null) {
16071            mDrawingCache.recycle();
16072            mDrawingCache = null;
16073        }
16074        if (mUnscaledDrawingCache != null) {
16075            mUnscaledDrawingCache.recycle();
16076            mUnscaledDrawingCache = null;
16077        }
16078    }
16079
16080    /**
16081     * Setting a solid background color for the drawing cache's bitmaps will improve
16082     * performance and memory usage. Note, though that this should only be used if this
16083     * view will always be drawn on top of a solid color.
16084     *
16085     * @param color The background color to use for the drawing cache's bitmap
16086     *
16087     * @see #setDrawingCacheEnabled(boolean)
16088     * @see #buildDrawingCache()
16089     * @see #getDrawingCache()
16090     */
16091    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16092        if (color != mDrawingCacheBackgroundColor) {
16093            mDrawingCacheBackgroundColor = color;
16094            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16095        }
16096    }
16097
16098    /**
16099     * @see #setDrawingCacheBackgroundColor(int)
16100     *
16101     * @return The background color to used for the drawing cache's bitmap
16102     */
16103    @ColorInt
16104    public int getDrawingCacheBackgroundColor() {
16105        return mDrawingCacheBackgroundColor;
16106    }
16107
16108    /**
16109     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16110     *
16111     * @see #buildDrawingCache(boolean)
16112     */
16113    public void buildDrawingCache() {
16114        buildDrawingCache(false);
16115    }
16116
16117    /**
16118     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16119     *
16120     * <p>If you call {@link #buildDrawingCache()} manually without calling
16121     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16122     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16123     *
16124     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16125     * this method will create a bitmap of the same size as this view. Because this bitmap
16126     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16127     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16128     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16129     * size than the view. This implies that your application must be able to handle this
16130     * size.</p>
16131     *
16132     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16133     * you do not need the drawing cache bitmap, calling this method will increase memory
16134     * usage and cause the view to be rendered in software once, thus negatively impacting
16135     * performance.</p>
16136     *
16137     * @see #getDrawingCache()
16138     * @see #destroyDrawingCache()
16139     */
16140    public void buildDrawingCache(boolean autoScale) {
16141        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16142                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16143            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16144                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16145                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16146            }
16147            try {
16148                buildDrawingCacheImpl(autoScale);
16149            } finally {
16150                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16151            }
16152        }
16153    }
16154
16155    /**
16156     * private, internal implementation of buildDrawingCache, used to enable tracing
16157     */
16158    private void buildDrawingCacheImpl(boolean autoScale) {
16159        mCachingFailed = false;
16160
16161        int width = mRight - mLeft;
16162        int height = mBottom - mTop;
16163
16164        final AttachInfo attachInfo = mAttachInfo;
16165        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16166
16167        if (autoScale && scalingRequired) {
16168            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16169            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16170        }
16171
16172        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16173        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16174        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16175
16176        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16177        final long drawingCacheSize =
16178                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16179        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16180            if (width > 0 && height > 0) {
16181                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16182                        + " too large to fit into a software layer (or drawing cache), needs "
16183                        + projectedBitmapSize + " bytes, only "
16184                        + drawingCacheSize + " available");
16185            }
16186            destroyDrawingCache();
16187            mCachingFailed = true;
16188            return;
16189        }
16190
16191        boolean clear = true;
16192        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16193
16194        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16195            Bitmap.Config quality;
16196            if (!opaque) {
16197                // Never pick ARGB_4444 because it looks awful
16198                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16199                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16200                    case DRAWING_CACHE_QUALITY_AUTO:
16201                    case DRAWING_CACHE_QUALITY_LOW:
16202                    case DRAWING_CACHE_QUALITY_HIGH:
16203                    default:
16204                        quality = Bitmap.Config.ARGB_8888;
16205                        break;
16206                }
16207            } else {
16208                // Optimization for translucent windows
16209                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16210                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16211            }
16212
16213            // Try to cleanup memory
16214            if (bitmap != null) bitmap.recycle();
16215
16216            try {
16217                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16218                        width, height, quality);
16219                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16220                if (autoScale) {
16221                    mDrawingCache = bitmap;
16222                } else {
16223                    mUnscaledDrawingCache = bitmap;
16224                }
16225                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16226            } catch (OutOfMemoryError e) {
16227                // If there is not enough memory to create the bitmap cache, just
16228                // ignore the issue as bitmap caches are not required to draw the
16229                // view hierarchy
16230                if (autoScale) {
16231                    mDrawingCache = null;
16232                } else {
16233                    mUnscaledDrawingCache = null;
16234                }
16235                mCachingFailed = true;
16236                return;
16237            }
16238
16239            clear = drawingCacheBackgroundColor != 0;
16240        }
16241
16242        Canvas canvas;
16243        if (attachInfo != null) {
16244            canvas = attachInfo.mCanvas;
16245            if (canvas == null) {
16246                canvas = new Canvas();
16247            }
16248            canvas.setBitmap(bitmap);
16249            // Temporarily clobber the cached Canvas in case one of our children
16250            // is also using a drawing cache. Without this, the children would
16251            // steal the canvas by attaching their own bitmap to it and bad, bad
16252            // thing would happen (invisible views, corrupted drawings, etc.)
16253            attachInfo.mCanvas = null;
16254        } else {
16255            // This case should hopefully never or seldom happen
16256            canvas = new Canvas(bitmap);
16257        }
16258
16259        if (clear) {
16260            bitmap.eraseColor(drawingCacheBackgroundColor);
16261        }
16262
16263        computeScroll();
16264        final int restoreCount = canvas.save();
16265
16266        if (autoScale && scalingRequired) {
16267            final float scale = attachInfo.mApplicationScale;
16268            canvas.scale(scale, scale);
16269        }
16270
16271        canvas.translate(-mScrollX, -mScrollY);
16272
16273        mPrivateFlags |= PFLAG_DRAWN;
16274        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16275                mLayerType != LAYER_TYPE_NONE) {
16276            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16277        }
16278
16279        // Fast path for layouts with no backgrounds
16280        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16281            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16282            dispatchDraw(canvas);
16283            if (mOverlay != null && !mOverlay.isEmpty()) {
16284                mOverlay.getOverlayView().draw(canvas);
16285            }
16286        } else {
16287            draw(canvas);
16288        }
16289
16290        canvas.restoreToCount(restoreCount);
16291        canvas.setBitmap(null);
16292
16293        if (attachInfo != null) {
16294            // Restore the cached Canvas for our siblings
16295            attachInfo.mCanvas = canvas;
16296        }
16297    }
16298
16299    /**
16300     * Create a snapshot of the view into a bitmap.  We should probably make
16301     * some form of this public, but should think about the API.
16302     *
16303     * @hide
16304     */
16305    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16306        int width = mRight - mLeft;
16307        int height = mBottom - mTop;
16308
16309        final AttachInfo attachInfo = mAttachInfo;
16310        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16311        width = (int) ((width * scale) + 0.5f);
16312        height = (int) ((height * scale) + 0.5f);
16313
16314        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16315                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16316        if (bitmap == null) {
16317            throw new OutOfMemoryError();
16318        }
16319
16320        Resources resources = getResources();
16321        if (resources != null) {
16322            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16323        }
16324
16325        Canvas canvas;
16326        if (attachInfo != null) {
16327            canvas = attachInfo.mCanvas;
16328            if (canvas == null) {
16329                canvas = new Canvas();
16330            }
16331            canvas.setBitmap(bitmap);
16332            // Temporarily clobber the cached Canvas in case one of our children
16333            // is also using a drawing cache. Without this, the children would
16334            // steal the canvas by attaching their own bitmap to it and bad, bad
16335            // things would happen (invisible views, corrupted drawings, etc.)
16336            attachInfo.mCanvas = null;
16337        } else {
16338            // This case should hopefully never or seldom happen
16339            canvas = new Canvas(bitmap);
16340        }
16341
16342        if ((backgroundColor & 0xff000000) != 0) {
16343            bitmap.eraseColor(backgroundColor);
16344        }
16345
16346        computeScroll();
16347        final int restoreCount = canvas.save();
16348        canvas.scale(scale, scale);
16349        canvas.translate(-mScrollX, -mScrollY);
16350
16351        // Temporarily remove the dirty mask
16352        int flags = mPrivateFlags;
16353        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16354
16355        // Fast path for layouts with no backgrounds
16356        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16357            dispatchDraw(canvas);
16358            if (mOverlay != null && !mOverlay.isEmpty()) {
16359                mOverlay.getOverlayView().draw(canvas);
16360            }
16361        } else {
16362            draw(canvas);
16363        }
16364
16365        mPrivateFlags = flags;
16366
16367        canvas.restoreToCount(restoreCount);
16368        canvas.setBitmap(null);
16369
16370        if (attachInfo != null) {
16371            // Restore the cached Canvas for our siblings
16372            attachInfo.mCanvas = canvas;
16373        }
16374
16375        return bitmap;
16376    }
16377
16378    /**
16379     * Indicates whether this View is currently in edit mode. A View is usually
16380     * in edit mode when displayed within a developer tool. For instance, if
16381     * this View is being drawn by a visual user interface builder, this method
16382     * should return true.
16383     *
16384     * Subclasses should check the return value of this method to provide
16385     * different behaviors if their normal behavior might interfere with the
16386     * host environment. For instance: the class spawns a thread in its
16387     * constructor, the drawing code relies on device-specific features, etc.
16388     *
16389     * This method is usually checked in the drawing code of custom widgets.
16390     *
16391     * @return True if this View is in edit mode, false otherwise.
16392     */
16393    public boolean isInEditMode() {
16394        return false;
16395    }
16396
16397    /**
16398     * If the View draws content inside its padding and enables fading edges,
16399     * it needs to support padding offsets. Padding offsets are added to the
16400     * fading edges to extend the length of the fade so that it covers pixels
16401     * drawn inside the padding.
16402     *
16403     * Subclasses of this class should override this method if they need
16404     * to draw content inside the padding.
16405     *
16406     * @return True if padding offset must be applied, false otherwise.
16407     *
16408     * @see #getLeftPaddingOffset()
16409     * @see #getRightPaddingOffset()
16410     * @see #getTopPaddingOffset()
16411     * @see #getBottomPaddingOffset()
16412     *
16413     * @since CURRENT
16414     */
16415    protected boolean isPaddingOffsetRequired() {
16416        return false;
16417    }
16418
16419    /**
16420     * Amount by which to extend the left fading region. Called only when
16421     * {@link #isPaddingOffsetRequired()} returns true.
16422     *
16423     * @return The left padding offset in pixels.
16424     *
16425     * @see #isPaddingOffsetRequired()
16426     *
16427     * @since CURRENT
16428     */
16429    protected int getLeftPaddingOffset() {
16430        return 0;
16431    }
16432
16433    /**
16434     * Amount by which to extend the right fading region. Called only when
16435     * {@link #isPaddingOffsetRequired()} returns true.
16436     *
16437     * @return The right padding offset in pixels.
16438     *
16439     * @see #isPaddingOffsetRequired()
16440     *
16441     * @since CURRENT
16442     */
16443    protected int getRightPaddingOffset() {
16444        return 0;
16445    }
16446
16447    /**
16448     * Amount by which to extend the top fading region. Called only when
16449     * {@link #isPaddingOffsetRequired()} returns true.
16450     *
16451     * @return The top padding offset in pixels.
16452     *
16453     * @see #isPaddingOffsetRequired()
16454     *
16455     * @since CURRENT
16456     */
16457    protected int getTopPaddingOffset() {
16458        return 0;
16459    }
16460
16461    /**
16462     * Amount by which to extend the bottom fading region. Called only when
16463     * {@link #isPaddingOffsetRequired()} returns true.
16464     *
16465     * @return The bottom padding offset in pixels.
16466     *
16467     * @see #isPaddingOffsetRequired()
16468     *
16469     * @since CURRENT
16470     */
16471    protected int getBottomPaddingOffset() {
16472        return 0;
16473    }
16474
16475    /**
16476     * @hide
16477     * @param offsetRequired
16478     */
16479    protected int getFadeTop(boolean offsetRequired) {
16480        int top = mPaddingTop;
16481        if (offsetRequired) top += getTopPaddingOffset();
16482        return top;
16483    }
16484
16485    /**
16486     * @hide
16487     * @param offsetRequired
16488     */
16489    protected int getFadeHeight(boolean offsetRequired) {
16490        int padding = mPaddingTop;
16491        if (offsetRequired) padding += getTopPaddingOffset();
16492        return mBottom - mTop - mPaddingBottom - padding;
16493    }
16494
16495    /**
16496     * <p>Indicates whether this view is attached to a hardware accelerated
16497     * window or not.</p>
16498     *
16499     * <p>Even if this method returns true, it does not mean that every call
16500     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
16501     * accelerated {@link android.graphics.Canvas}. For instance, if this view
16502     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
16503     * window is hardware accelerated,
16504     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
16505     * return false, and this method will return true.</p>
16506     *
16507     * @return True if the view is attached to a window and the window is
16508     *         hardware accelerated; false in any other case.
16509     */
16510    @ViewDebug.ExportedProperty(category = "drawing")
16511    public boolean isHardwareAccelerated() {
16512        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
16513    }
16514
16515    /**
16516     * Sets a rectangular area on this view to which the view will be clipped
16517     * when it is drawn. Setting the value to null will remove the clip bounds
16518     * and the view will draw normally, using its full bounds.
16519     *
16520     * @param clipBounds The rectangular area, in the local coordinates of
16521     * this view, to which future drawing operations will be clipped.
16522     */
16523    public void setClipBounds(Rect clipBounds) {
16524        if (clipBounds == mClipBounds
16525                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
16526            return;
16527        }
16528        if (clipBounds != null) {
16529            if (mClipBounds == null) {
16530                mClipBounds = new Rect(clipBounds);
16531            } else {
16532                mClipBounds.set(clipBounds);
16533            }
16534        } else {
16535            mClipBounds = null;
16536        }
16537        mRenderNode.setClipBounds(mClipBounds);
16538        invalidateViewProperty(false, false);
16539    }
16540
16541    /**
16542     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
16543     *
16544     * @return A copy of the current clip bounds if clip bounds are set,
16545     * otherwise null.
16546     */
16547    public Rect getClipBounds() {
16548        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
16549    }
16550
16551
16552    /**
16553     * Populates an output rectangle with the clip bounds of the view,
16554     * returning {@code true} if successful or {@code false} if the view's
16555     * clip bounds are {@code null}.
16556     *
16557     * @param outRect rectangle in which to place the clip bounds of the view
16558     * @return {@code true} if successful or {@code false} if the view's
16559     *         clip bounds are {@code null}
16560     */
16561    public boolean getClipBounds(Rect outRect) {
16562        if (mClipBounds != null) {
16563            outRect.set(mClipBounds);
16564            return true;
16565        }
16566        return false;
16567    }
16568
16569    /**
16570     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
16571     * case of an active Animation being run on the view.
16572     */
16573    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
16574            Animation a, boolean scalingRequired) {
16575        Transformation invalidationTransform;
16576        final int flags = parent.mGroupFlags;
16577        final boolean initialized = a.isInitialized();
16578        if (!initialized) {
16579            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
16580            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
16581            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
16582            onAnimationStart();
16583        }
16584
16585        final Transformation t = parent.getChildTransformation();
16586        boolean more = a.getTransformation(drawingTime, t, 1f);
16587        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
16588            if (parent.mInvalidationTransformation == null) {
16589                parent.mInvalidationTransformation = new Transformation();
16590            }
16591            invalidationTransform = parent.mInvalidationTransformation;
16592            a.getTransformation(drawingTime, invalidationTransform, 1f);
16593        } else {
16594            invalidationTransform = t;
16595        }
16596
16597        if (more) {
16598            if (!a.willChangeBounds()) {
16599                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
16600                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
16601                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
16602                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
16603                    // The child need to draw an animation, potentially offscreen, so
16604                    // make sure we do not cancel invalidate requests
16605                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16606                    parent.invalidate(mLeft, mTop, mRight, mBottom);
16607                }
16608            } else {
16609                if (parent.mInvalidateRegion == null) {
16610                    parent.mInvalidateRegion = new RectF();
16611                }
16612                final RectF region = parent.mInvalidateRegion;
16613                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
16614                        invalidationTransform);
16615
16616                // The child need to draw an animation, potentially offscreen, so
16617                // make sure we do not cancel invalidate requests
16618                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16619
16620                final int left = mLeft + (int) region.left;
16621                final int top = mTop + (int) region.top;
16622                parent.invalidate(left, top, left + (int) (region.width() + .5f),
16623                        top + (int) (region.height() + .5f));
16624            }
16625        }
16626        return more;
16627    }
16628
16629    /**
16630     * This method is called by getDisplayList() when a display list is recorded for a View.
16631     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
16632     */
16633    void setDisplayListProperties(RenderNode renderNode) {
16634        if (renderNode != null) {
16635            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
16636            renderNode.setClipToBounds(mParent instanceof ViewGroup
16637                    && ((ViewGroup) mParent).getClipChildren());
16638
16639            float alpha = 1;
16640            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
16641                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16642                ViewGroup parentVG = (ViewGroup) mParent;
16643                final Transformation t = parentVG.getChildTransformation();
16644                if (parentVG.getChildStaticTransformation(this, t)) {
16645                    final int transformType = t.getTransformationType();
16646                    if (transformType != Transformation.TYPE_IDENTITY) {
16647                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
16648                            alpha = t.getAlpha();
16649                        }
16650                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
16651                            renderNode.setStaticMatrix(t.getMatrix());
16652                        }
16653                    }
16654                }
16655            }
16656            if (mTransformationInfo != null) {
16657                alpha *= getFinalAlpha();
16658                if (alpha < 1) {
16659                    final int multipliedAlpha = (int) (255 * alpha);
16660                    if (onSetAlpha(multipliedAlpha)) {
16661                        alpha = 1;
16662                    }
16663                }
16664                renderNode.setAlpha(alpha);
16665            } else if (alpha < 1) {
16666                renderNode.setAlpha(alpha);
16667            }
16668        }
16669    }
16670
16671    /**
16672     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
16673     *
16674     * This is where the View specializes rendering behavior based on layer type,
16675     * and hardware acceleration.
16676     */
16677    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
16678        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
16679        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
16680         *
16681         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
16682         * HW accelerated, it can't handle drawing RenderNodes.
16683         */
16684        boolean drawingWithRenderNode = mAttachInfo != null
16685                && mAttachInfo.mHardwareAccelerated
16686                && hardwareAcceleratedCanvas;
16687
16688        boolean more = false;
16689        final boolean childHasIdentityMatrix = hasIdentityMatrix();
16690        final int parentFlags = parent.mGroupFlags;
16691
16692        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
16693            parent.getChildTransformation().clear();
16694            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16695        }
16696
16697        Transformation transformToApply = null;
16698        boolean concatMatrix = false;
16699        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
16700        final Animation a = getAnimation();
16701        if (a != null) {
16702            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
16703            concatMatrix = a.willChangeTransformationMatrix();
16704            if (concatMatrix) {
16705                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16706            }
16707            transformToApply = parent.getChildTransformation();
16708        } else {
16709            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
16710                // No longer animating: clear out old animation matrix
16711                mRenderNode.setAnimationMatrix(null);
16712                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16713            }
16714            if (!drawingWithRenderNode
16715                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16716                final Transformation t = parent.getChildTransformation();
16717                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
16718                if (hasTransform) {
16719                    final int transformType = t.getTransformationType();
16720                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
16721                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
16722                }
16723            }
16724        }
16725
16726        concatMatrix |= !childHasIdentityMatrix;
16727
16728        // Sets the flag as early as possible to allow draw() implementations
16729        // to call invalidate() successfully when doing animations
16730        mPrivateFlags |= PFLAG_DRAWN;
16731
16732        if (!concatMatrix &&
16733                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
16734                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
16735                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
16736                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
16737            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
16738            return more;
16739        }
16740        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
16741
16742        if (hardwareAcceleratedCanvas) {
16743            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
16744            // retain the flag's value temporarily in the mRecreateDisplayList flag
16745            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
16746            mPrivateFlags &= ~PFLAG_INVALIDATED;
16747        }
16748
16749        RenderNode renderNode = null;
16750        Bitmap cache = null;
16751        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
16752        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
16753             if (layerType != LAYER_TYPE_NONE) {
16754                 // If not drawing with RenderNode, treat HW layers as SW
16755                 layerType = LAYER_TYPE_SOFTWARE;
16756                 buildDrawingCache(true);
16757            }
16758            cache = getDrawingCache(true);
16759        }
16760
16761        if (drawingWithRenderNode) {
16762            // Delay getting the display list until animation-driven alpha values are
16763            // set up and possibly passed on to the view
16764            renderNode = updateDisplayListIfDirty();
16765            if (!renderNode.isValid()) {
16766                // Uncommon, but possible. If a view is removed from the hierarchy during the call
16767                // to getDisplayList(), the display list will be marked invalid and we should not
16768                // try to use it again.
16769                renderNode = null;
16770                drawingWithRenderNode = false;
16771            }
16772        }
16773
16774        int sx = 0;
16775        int sy = 0;
16776        if (!drawingWithRenderNode) {
16777            computeScroll();
16778            sx = mScrollX;
16779            sy = mScrollY;
16780        }
16781
16782        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
16783        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
16784
16785        int restoreTo = -1;
16786        if (!drawingWithRenderNode || transformToApply != null) {
16787            restoreTo = canvas.save();
16788        }
16789        if (offsetForScroll) {
16790            canvas.translate(mLeft - sx, mTop - sy);
16791        } else {
16792            if (!drawingWithRenderNode) {
16793                canvas.translate(mLeft, mTop);
16794            }
16795            if (scalingRequired) {
16796                if (drawingWithRenderNode) {
16797                    // TODO: Might not need this if we put everything inside the DL
16798                    restoreTo = canvas.save();
16799                }
16800                // mAttachInfo cannot be null, otherwise scalingRequired == false
16801                final float scale = 1.0f / mAttachInfo.mApplicationScale;
16802                canvas.scale(scale, scale);
16803            }
16804        }
16805
16806        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
16807        if (transformToApply != null
16808                || alpha < 1
16809                || !hasIdentityMatrix()
16810                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16811            if (transformToApply != null || !childHasIdentityMatrix) {
16812                int transX = 0;
16813                int transY = 0;
16814
16815                if (offsetForScroll) {
16816                    transX = -sx;
16817                    transY = -sy;
16818                }
16819
16820                if (transformToApply != null) {
16821                    if (concatMatrix) {
16822                        if (drawingWithRenderNode) {
16823                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
16824                        } else {
16825                            // Undo the scroll translation, apply the transformation matrix,
16826                            // then redo the scroll translate to get the correct result.
16827                            canvas.translate(-transX, -transY);
16828                            canvas.concat(transformToApply.getMatrix());
16829                            canvas.translate(transX, transY);
16830                        }
16831                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16832                    }
16833
16834                    float transformAlpha = transformToApply.getAlpha();
16835                    if (transformAlpha < 1) {
16836                        alpha *= transformAlpha;
16837                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16838                    }
16839                }
16840
16841                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
16842                    canvas.translate(-transX, -transY);
16843                    canvas.concat(getMatrix());
16844                    canvas.translate(transX, transY);
16845                }
16846            }
16847
16848            // Deal with alpha if it is or used to be <1
16849            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16850                if (alpha < 1) {
16851                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16852                } else {
16853                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16854                }
16855                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16856                if (!drawingWithDrawingCache) {
16857                    final int multipliedAlpha = (int) (255 * alpha);
16858                    if (!onSetAlpha(multipliedAlpha)) {
16859                        if (drawingWithRenderNode) {
16860                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
16861                        } else if (layerType == LAYER_TYPE_NONE) {
16862                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
16863                                    multipliedAlpha);
16864                        }
16865                    } else {
16866                        // Alpha is handled by the child directly, clobber the layer's alpha
16867                        mPrivateFlags |= PFLAG_ALPHA_SET;
16868                    }
16869                }
16870            }
16871        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16872            onSetAlpha(255);
16873            mPrivateFlags &= ~PFLAG_ALPHA_SET;
16874        }
16875
16876        if (!drawingWithRenderNode) {
16877            // apply clips directly, since RenderNode won't do it for this draw
16878            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
16879                if (offsetForScroll) {
16880                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
16881                } else {
16882                    if (!scalingRequired || cache == null) {
16883                        canvas.clipRect(0, 0, getWidth(), getHeight());
16884                    } else {
16885                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
16886                    }
16887                }
16888            }
16889
16890            if (mClipBounds != null) {
16891                // clip bounds ignore scroll
16892                canvas.clipRect(mClipBounds);
16893            }
16894        }
16895
16896        if (!drawingWithDrawingCache) {
16897            if (drawingWithRenderNode) {
16898                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16899                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
16900            } else {
16901                // Fast path for layouts with no backgrounds
16902                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16903                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16904                    dispatchDraw(canvas);
16905                } else {
16906                    draw(canvas);
16907                }
16908            }
16909        } else if (cache != null) {
16910            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16911            if (layerType == LAYER_TYPE_NONE) {
16912                // no layer paint, use temporary paint to draw bitmap
16913                Paint cachePaint = parent.mCachePaint;
16914                if (cachePaint == null) {
16915                    cachePaint = new Paint();
16916                    cachePaint.setDither(false);
16917                    parent.mCachePaint = cachePaint;
16918                }
16919                cachePaint.setAlpha((int) (alpha * 255));
16920                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
16921            } else {
16922                // use layer paint to draw the bitmap, merging the two alphas, but also restore
16923                int layerPaintAlpha = mLayerPaint != null ? mLayerPaint.getAlpha() : 255;
16924                if (mLayerPaint == null && alpha < 1) {
16925                    mLayerPaint = new Paint();
16926                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
16927                }
16928                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
16929                if (mLayerPaint != null) {
16930                    mLayerPaint.setAlpha(layerPaintAlpha);
16931                }
16932            }
16933        }
16934
16935        if (restoreTo >= 0) {
16936            canvas.restoreToCount(restoreTo);
16937        }
16938
16939        if (a != null && !more) {
16940            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
16941                onSetAlpha(255);
16942            }
16943            parent.finishAnimatingView(this, a);
16944        }
16945
16946        if (more && hardwareAcceleratedCanvas) {
16947            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16948                // alpha animations should cause the child to recreate its display list
16949                invalidate(true);
16950            }
16951        }
16952
16953        mRecreateDisplayList = false;
16954
16955        return more;
16956    }
16957
16958    /**
16959     * Manually render this view (and all of its children) to the given Canvas.
16960     * The view must have already done a full layout before this function is
16961     * called.  When implementing a view, implement
16962     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
16963     * If you do need to override this method, call the superclass version.
16964     *
16965     * @param canvas The Canvas to which the View is rendered.
16966     */
16967    @CallSuper
16968    public void draw(Canvas canvas) {
16969        final int privateFlags = mPrivateFlags;
16970        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
16971                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
16972        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
16973
16974        /*
16975         * Draw traversal performs several drawing steps which must be executed
16976         * in the appropriate order:
16977         *
16978         *      1. Draw the background
16979         *      2. If necessary, save the canvas' layers to prepare for fading
16980         *      3. Draw view's content
16981         *      4. Draw children
16982         *      5. If necessary, draw the fading edges and restore layers
16983         *      6. Draw decorations (scrollbars for instance)
16984         */
16985
16986        // Step 1, draw the background, if needed
16987        int saveCount;
16988
16989        if (!dirtyOpaque) {
16990            drawBackground(canvas);
16991        }
16992
16993        // skip step 2 & 5 if possible (common case)
16994        final int viewFlags = mViewFlags;
16995        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
16996        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
16997        if (!verticalEdges && !horizontalEdges) {
16998            // Step 3, draw the content
16999            if (!dirtyOpaque) onDraw(canvas);
17000
17001            // Step 4, draw the children
17002            dispatchDraw(canvas);
17003
17004            // Overlay is part of the content and draws beneath Foreground
17005            if (mOverlay != null && !mOverlay.isEmpty()) {
17006                mOverlay.getOverlayView().dispatchDraw(canvas);
17007            }
17008
17009            // Step 6, draw decorations (foreground, scrollbars)
17010            onDrawForeground(canvas);
17011
17012            // we're done...
17013            return;
17014        }
17015
17016        /*
17017         * Here we do the full fledged routine...
17018         * (this is an uncommon case where speed matters less,
17019         * this is why we repeat some of the tests that have been
17020         * done above)
17021         */
17022
17023        boolean drawTop = false;
17024        boolean drawBottom = false;
17025        boolean drawLeft = false;
17026        boolean drawRight = false;
17027
17028        float topFadeStrength = 0.0f;
17029        float bottomFadeStrength = 0.0f;
17030        float leftFadeStrength = 0.0f;
17031        float rightFadeStrength = 0.0f;
17032
17033        // Step 2, save the canvas' layers
17034        int paddingLeft = mPaddingLeft;
17035
17036        final boolean offsetRequired = isPaddingOffsetRequired();
17037        if (offsetRequired) {
17038            paddingLeft += getLeftPaddingOffset();
17039        }
17040
17041        int left = mScrollX + paddingLeft;
17042        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17043        int top = mScrollY + getFadeTop(offsetRequired);
17044        int bottom = top + getFadeHeight(offsetRequired);
17045
17046        if (offsetRequired) {
17047            right += getRightPaddingOffset();
17048            bottom += getBottomPaddingOffset();
17049        }
17050
17051        final ScrollabilityCache scrollabilityCache = mScrollCache;
17052        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17053        int length = (int) fadeHeight;
17054
17055        // clip the fade length if top and bottom fades overlap
17056        // overlapping fades produce odd-looking artifacts
17057        if (verticalEdges && (top + length > bottom - length)) {
17058            length = (bottom - top) / 2;
17059        }
17060
17061        // also clip horizontal fades if necessary
17062        if (horizontalEdges && (left + length > right - length)) {
17063            length = (right - left) / 2;
17064        }
17065
17066        if (verticalEdges) {
17067            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17068            drawTop = topFadeStrength * fadeHeight > 1.0f;
17069            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17070            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17071        }
17072
17073        if (horizontalEdges) {
17074            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17075            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17076            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17077            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17078        }
17079
17080        saveCount = canvas.getSaveCount();
17081
17082        int solidColor = getSolidColor();
17083        if (solidColor == 0) {
17084            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17085
17086            if (drawTop) {
17087                canvas.saveLayer(left, top, right, top + length, null, flags);
17088            }
17089
17090            if (drawBottom) {
17091                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17092            }
17093
17094            if (drawLeft) {
17095                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17096            }
17097
17098            if (drawRight) {
17099                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17100            }
17101        } else {
17102            scrollabilityCache.setFadeColor(solidColor);
17103        }
17104
17105        // Step 3, draw the content
17106        if (!dirtyOpaque) onDraw(canvas);
17107
17108        // Step 4, draw the children
17109        dispatchDraw(canvas);
17110
17111        // Step 5, draw the fade effect and restore layers
17112        final Paint p = scrollabilityCache.paint;
17113        final Matrix matrix = scrollabilityCache.matrix;
17114        final Shader fade = scrollabilityCache.shader;
17115
17116        if (drawTop) {
17117            matrix.setScale(1, fadeHeight * topFadeStrength);
17118            matrix.postTranslate(left, top);
17119            fade.setLocalMatrix(matrix);
17120            p.setShader(fade);
17121            canvas.drawRect(left, top, right, top + length, p);
17122        }
17123
17124        if (drawBottom) {
17125            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17126            matrix.postRotate(180);
17127            matrix.postTranslate(left, bottom);
17128            fade.setLocalMatrix(matrix);
17129            p.setShader(fade);
17130            canvas.drawRect(left, bottom - length, right, bottom, p);
17131        }
17132
17133        if (drawLeft) {
17134            matrix.setScale(1, fadeHeight * leftFadeStrength);
17135            matrix.postRotate(-90);
17136            matrix.postTranslate(left, top);
17137            fade.setLocalMatrix(matrix);
17138            p.setShader(fade);
17139            canvas.drawRect(left, top, left + length, bottom, p);
17140        }
17141
17142        if (drawRight) {
17143            matrix.setScale(1, fadeHeight * rightFadeStrength);
17144            matrix.postRotate(90);
17145            matrix.postTranslate(right, top);
17146            fade.setLocalMatrix(matrix);
17147            p.setShader(fade);
17148            canvas.drawRect(right - length, top, right, bottom, p);
17149        }
17150
17151        canvas.restoreToCount(saveCount);
17152
17153        // Overlay is part of the content and draws beneath Foreground
17154        if (mOverlay != null && !mOverlay.isEmpty()) {
17155            mOverlay.getOverlayView().dispatchDraw(canvas);
17156        }
17157
17158        // Step 6, draw decorations (foreground, scrollbars)
17159        onDrawForeground(canvas);
17160    }
17161
17162    /**
17163     * Draws the background onto the specified canvas.
17164     *
17165     * @param canvas Canvas on which to draw the background
17166     */
17167    private void drawBackground(Canvas canvas) {
17168        final Drawable background = mBackground;
17169        if (background == null) {
17170            return;
17171        }
17172
17173        setBackgroundBounds();
17174
17175        // Attempt to use a display list if requested.
17176        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17177                && mAttachInfo.mHardwareRenderer != null) {
17178            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17179
17180            final RenderNode renderNode = mBackgroundRenderNode;
17181            if (renderNode != null && renderNode.isValid()) {
17182                setBackgroundRenderNodeProperties(renderNode);
17183                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17184                return;
17185            }
17186        }
17187
17188        final int scrollX = mScrollX;
17189        final int scrollY = mScrollY;
17190        if ((scrollX | scrollY) == 0) {
17191            background.draw(canvas);
17192        } else {
17193            canvas.translate(scrollX, scrollY);
17194            background.draw(canvas);
17195            canvas.translate(-scrollX, -scrollY);
17196        }
17197    }
17198
17199    /**
17200     * Sets the correct background bounds and rebuilds the outline, if needed.
17201     * <p/>
17202     * This is called by LayoutLib.
17203     */
17204    void setBackgroundBounds() {
17205        if (mBackgroundSizeChanged && mBackground != null) {
17206            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17207            mBackgroundSizeChanged = false;
17208            rebuildOutline();
17209        }
17210    }
17211
17212    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17213        renderNode.setTranslationX(mScrollX);
17214        renderNode.setTranslationY(mScrollY);
17215    }
17216
17217    /**
17218     * Creates a new display list or updates the existing display list for the
17219     * specified Drawable.
17220     *
17221     * @param drawable Drawable for which to create a display list
17222     * @param renderNode Existing RenderNode, or {@code null}
17223     * @return A valid display list for the specified drawable
17224     */
17225    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17226        if (renderNode == null) {
17227            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17228        }
17229
17230        final Rect bounds = drawable.getBounds();
17231        final int width = bounds.width();
17232        final int height = bounds.height();
17233        final DisplayListCanvas canvas = renderNode.start(width, height);
17234
17235        // Reverse left/top translation done by drawable canvas, which will
17236        // instead be applied by rendernode's LTRB bounds below. This way, the
17237        // drawable's bounds match with its rendernode bounds and its content
17238        // will lie within those bounds in the rendernode tree.
17239        canvas.translate(-bounds.left, -bounds.top);
17240
17241        try {
17242            drawable.draw(canvas);
17243        } finally {
17244            renderNode.end(canvas);
17245        }
17246
17247        // Set up drawable properties that are view-independent.
17248        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17249        renderNode.setProjectBackwards(drawable.isProjected());
17250        renderNode.setProjectionReceiver(true);
17251        renderNode.setClipToBounds(false);
17252        return renderNode;
17253    }
17254
17255    /**
17256     * Returns the overlay for this view, creating it if it does not yet exist.
17257     * Adding drawables to the overlay will cause them to be displayed whenever
17258     * the view itself is redrawn. Objects in the overlay should be actively
17259     * managed: remove them when they should not be displayed anymore. The
17260     * overlay will always have the same size as its host view.
17261     *
17262     * <p>Note: Overlays do not currently work correctly with {@link
17263     * SurfaceView} or {@link TextureView}; contents in overlays for these
17264     * types of views may not display correctly.</p>
17265     *
17266     * @return The ViewOverlay object for this view.
17267     * @see ViewOverlay
17268     */
17269    public ViewOverlay getOverlay() {
17270        if (mOverlay == null) {
17271            mOverlay = new ViewOverlay(mContext, this);
17272        }
17273        return mOverlay;
17274    }
17275
17276    /**
17277     * Override this if your view is known to always be drawn on top of a solid color background,
17278     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17279     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17280     * should be set to 0xFF.
17281     *
17282     * @see #setVerticalFadingEdgeEnabled(boolean)
17283     * @see #setHorizontalFadingEdgeEnabled(boolean)
17284     *
17285     * @return The known solid color background for this view, or 0 if the color may vary
17286     */
17287    @ViewDebug.ExportedProperty(category = "drawing")
17288    @ColorInt
17289    public int getSolidColor() {
17290        return 0;
17291    }
17292
17293    /**
17294     * Build a human readable string representation of the specified view flags.
17295     *
17296     * @param flags the view flags to convert to a string
17297     * @return a String representing the supplied flags
17298     */
17299    private static String printFlags(int flags) {
17300        String output = "";
17301        int numFlags = 0;
17302        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17303            output += "TAKES_FOCUS";
17304            numFlags++;
17305        }
17306
17307        switch (flags & VISIBILITY_MASK) {
17308        case INVISIBLE:
17309            if (numFlags > 0) {
17310                output += " ";
17311            }
17312            output += "INVISIBLE";
17313            // USELESS HERE numFlags++;
17314            break;
17315        case GONE:
17316            if (numFlags > 0) {
17317                output += " ";
17318            }
17319            output += "GONE";
17320            // USELESS HERE numFlags++;
17321            break;
17322        default:
17323            break;
17324        }
17325        return output;
17326    }
17327
17328    /**
17329     * Build a human readable string representation of the specified private
17330     * view flags.
17331     *
17332     * @param privateFlags the private view flags to convert to a string
17333     * @return a String representing the supplied flags
17334     */
17335    private static String printPrivateFlags(int privateFlags) {
17336        String output = "";
17337        int numFlags = 0;
17338
17339        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17340            output += "WANTS_FOCUS";
17341            numFlags++;
17342        }
17343
17344        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17345            if (numFlags > 0) {
17346                output += " ";
17347            }
17348            output += "FOCUSED";
17349            numFlags++;
17350        }
17351
17352        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17353            if (numFlags > 0) {
17354                output += " ";
17355            }
17356            output += "SELECTED";
17357            numFlags++;
17358        }
17359
17360        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17361            if (numFlags > 0) {
17362                output += " ";
17363            }
17364            output += "IS_ROOT_NAMESPACE";
17365            numFlags++;
17366        }
17367
17368        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17369            if (numFlags > 0) {
17370                output += " ";
17371            }
17372            output += "HAS_BOUNDS";
17373            numFlags++;
17374        }
17375
17376        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17377            if (numFlags > 0) {
17378                output += " ";
17379            }
17380            output += "DRAWN";
17381            // USELESS HERE numFlags++;
17382        }
17383        return output;
17384    }
17385
17386    /**
17387     * <p>Indicates whether or not this view's layout will be requested during
17388     * the next hierarchy layout pass.</p>
17389     *
17390     * @return true if the layout will be forced during next layout pass
17391     */
17392    public boolean isLayoutRequested() {
17393        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17394    }
17395
17396    /**
17397     * Return true if o is a ViewGroup that is laying out using optical bounds.
17398     * @hide
17399     */
17400    public static boolean isLayoutModeOptical(Object o) {
17401        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
17402    }
17403
17404    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
17405        Insets parentInsets = mParent instanceof View ?
17406                ((View) mParent).getOpticalInsets() : Insets.NONE;
17407        Insets childInsets = getOpticalInsets();
17408        return setFrame(
17409                left   + parentInsets.left - childInsets.left,
17410                top    + parentInsets.top  - childInsets.top,
17411                right  + parentInsets.left + childInsets.right,
17412                bottom + parentInsets.top  + childInsets.bottom);
17413    }
17414
17415    /**
17416     * Assign a size and position to a view and all of its
17417     * descendants
17418     *
17419     * <p>This is the second phase of the layout mechanism.
17420     * (The first is measuring). In this phase, each parent calls
17421     * layout on all of its children to position them.
17422     * This is typically done using the child measurements
17423     * that were stored in the measure pass().</p>
17424     *
17425     * <p>Derived classes should not override this method.
17426     * Derived classes with children should override
17427     * onLayout. In that method, they should
17428     * call layout on each of their children.</p>
17429     *
17430     * @param l Left position, relative to parent
17431     * @param t Top position, relative to parent
17432     * @param r Right position, relative to parent
17433     * @param b Bottom position, relative to parent
17434     */
17435    @SuppressWarnings({"unchecked"})
17436    public void layout(int l, int t, int r, int b) {
17437        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
17438            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
17439            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17440        }
17441
17442        int oldL = mLeft;
17443        int oldT = mTop;
17444        int oldB = mBottom;
17445        int oldR = mRight;
17446
17447        boolean changed = isLayoutModeOptical(mParent) ?
17448                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
17449
17450        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
17451            onLayout(changed, l, t, r, b);
17452            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
17453
17454            ListenerInfo li = mListenerInfo;
17455            if (li != null && li.mOnLayoutChangeListeners != null) {
17456                ArrayList<OnLayoutChangeListener> listenersCopy =
17457                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
17458                int numListeners = listenersCopy.size();
17459                for (int i = 0; i < numListeners; ++i) {
17460                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
17461                }
17462            }
17463        }
17464
17465        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
17466        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
17467    }
17468
17469    /**
17470     * Called from layout when this view should
17471     * assign a size and position to each of its children.
17472     *
17473     * Derived classes with children should override
17474     * this method and call layout on each of
17475     * their children.
17476     * @param changed This is a new size or position for this view
17477     * @param left Left position, relative to parent
17478     * @param top Top position, relative to parent
17479     * @param right Right position, relative to parent
17480     * @param bottom Bottom position, relative to parent
17481     */
17482    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
17483    }
17484
17485    /**
17486     * Assign a size and position to this view.
17487     *
17488     * This is called from layout.
17489     *
17490     * @param left Left position, relative to parent
17491     * @param top Top position, relative to parent
17492     * @param right Right position, relative to parent
17493     * @param bottom Bottom position, relative to parent
17494     * @return true if the new size and position are different than the
17495     *         previous ones
17496     * {@hide}
17497     */
17498    protected boolean setFrame(int left, int top, int right, int bottom) {
17499        boolean changed = false;
17500
17501        if (DBG) {
17502            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
17503                    + right + "," + bottom + ")");
17504        }
17505
17506        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
17507            changed = true;
17508
17509            // Remember our drawn bit
17510            int drawn = mPrivateFlags & PFLAG_DRAWN;
17511
17512            int oldWidth = mRight - mLeft;
17513            int oldHeight = mBottom - mTop;
17514            int newWidth = right - left;
17515            int newHeight = bottom - top;
17516            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
17517
17518            // Invalidate our old position
17519            invalidate(sizeChanged);
17520
17521            mLeft = left;
17522            mTop = top;
17523            mRight = right;
17524            mBottom = bottom;
17525            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
17526
17527            mPrivateFlags |= PFLAG_HAS_BOUNDS;
17528
17529
17530            if (sizeChanged) {
17531                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
17532            }
17533
17534            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
17535                // If we are visible, force the DRAWN bit to on so that
17536                // this invalidate will go through (at least to our parent).
17537                // This is because someone may have invalidated this view
17538                // before this call to setFrame came in, thereby clearing
17539                // the DRAWN bit.
17540                mPrivateFlags |= PFLAG_DRAWN;
17541                invalidate(sizeChanged);
17542                // parent display list may need to be recreated based on a change in the bounds
17543                // of any child
17544                invalidateParentCaches();
17545            }
17546
17547            // Reset drawn bit to original value (invalidate turns it off)
17548            mPrivateFlags |= drawn;
17549
17550            mBackgroundSizeChanged = true;
17551            if (mForegroundInfo != null) {
17552                mForegroundInfo.mBoundsChanged = true;
17553            }
17554
17555            notifySubtreeAccessibilityStateChangedIfNeeded();
17556        }
17557        return changed;
17558    }
17559
17560    /**
17561     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
17562     * @hide
17563     */
17564    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
17565        setFrame(left, top, right, bottom);
17566    }
17567
17568    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
17569        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
17570        if (mOverlay != null) {
17571            mOverlay.getOverlayView().setRight(newWidth);
17572            mOverlay.getOverlayView().setBottom(newHeight);
17573        }
17574        rebuildOutline();
17575    }
17576
17577    /**
17578     * Finalize inflating a view from XML.  This is called as the last phase
17579     * of inflation, after all child views have been added.
17580     *
17581     * <p>Even if the subclass overrides onFinishInflate, they should always be
17582     * sure to call the super method, so that we get called.
17583     */
17584    @CallSuper
17585    protected void onFinishInflate() {
17586    }
17587
17588    /**
17589     * Returns the resources associated with this view.
17590     *
17591     * @return Resources object.
17592     */
17593    public Resources getResources() {
17594        return mResources;
17595    }
17596
17597    /**
17598     * Invalidates the specified Drawable.
17599     *
17600     * @param drawable the drawable to invalidate
17601     */
17602    @Override
17603    public void invalidateDrawable(@NonNull Drawable drawable) {
17604        if (verifyDrawable(drawable)) {
17605            final Rect dirty = drawable.getDirtyBounds();
17606            final int scrollX = mScrollX;
17607            final int scrollY = mScrollY;
17608
17609            invalidate(dirty.left + scrollX, dirty.top + scrollY,
17610                    dirty.right + scrollX, dirty.bottom + scrollY);
17611            rebuildOutline();
17612        }
17613    }
17614
17615    /**
17616     * Schedules an action on a drawable to occur at a specified time.
17617     *
17618     * @param who the recipient of the action
17619     * @param what the action to run on the drawable
17620     * @param when the time at which the action must occur. Uses the
17621     *        {@link SystemClock#uptimeMillis} timebase.
17622     */
17623    @Override
17624    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
17625        if (verifyDrawable(who) && what != null) {
17626            final long delay = when - SystemClock.uptimeMillis();
17627            if (mAttachInfo != null) {
17628                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
17629                        Choreographer.CALLBACK_ANIMATION, what, who,
17630                        Choreographer.subtractFrameDelay(delay));
17631            } else {
17632                // Postpone the runnable until we know
17633                // on which thread it needs to run.
17634                getRunQueue().postDelayed(what, delay);
17635            }
17636        }
17637    }
17638
17639    /**
17640     * Cancels a scheduled action on a drawable.
17641     *
17642     * @param who the recipient of the action
17643     * @param what the action to cancel
17644     */
17645    @Override
17646    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
17647        if (verifyDrawable(who) && what != null) {
17648            if (mAttachInfo != null) {
17649                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17650                        Choreographer.CALLBACK_ANIMATION, what, who);
17651            }
17652            getRunQueue().removeCallbacks(what);
17653        }
17654    }
17655
17656    /**
17657     * Unschedule any events associated with the given Drawable.  This can be
17658     * used when selecting a new Drawable into a view, so that the previous
17659     * one is completely unscheduled.
17660     *
17661     * @param who The Drawable to unschedule.
17662     *
17663     * @see #drawableStateChanged
17664     */
17665    public void unscheduleDrawable(Drawable who) {
17666        if (mAttachInfo != null && who != null) {
17667            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17668                    Choreographer.CALLBACK_ANIMATION, null, who);
17669        }
17670    }
17671
17672    /**
17673     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
17674     * that the View directionality can and will be resolved before its Drawables.
17675     *
17676     * Will call {@link View#onResolveDrawables} when resolution is done.
17677     *
17678     * @hide
17679     */
17680    protected void resolveDrawables() {
17681        // Drawables resolution may need to happen before resolving the layout direction (which is
17682        // done only during the measure() call).
17683        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
17684        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
17685        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
17686        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
17687        // direction to be resolved as its resolved value will be the same as its raw value.
17688        if (!isLayoutDirectionResolved() &&
17689                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
17690            return;
17691        }
17692
17693        final int layoutDirection = isLayoutDirectionResolved() ?
17694                getLayoutDirection() : getRawLayoutDirection();
17695
17696        if (mBackground != null) {
17697            mBackground.setLayoutDirection(layoutDirection);
17698        }
17699        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17700            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
17701        }
17702        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
17703        onResolveDrawables(layoutDirection);
17704    }
17705
17706    boolean areDrawablesResolved() {
17707        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
17708    }
17709
17710    /**
17711     * Called when layout direction has been resolved.
17712     *
17713     * The default implementation does nothing.
17714     *
17715     * @param layoutDirection The resolved layout direction.
17716     *
17717     * @see #LAYOUT_DIRECTION_LTR
17718     * @see #LAYOUT_DIRECTION_RTL
17719     *
17720     * @hide
17721     */
17722    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
17723    }
17724
17725    /**
17726     * @hide
17727     */
17728    protected void resetResolvedDrawables() {
17729        resetResolvedDrawablesInternal();
17730    }
17731
17732    void resetResolvedDrawablesInternal() {
17733        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
17734    }
17735
17736    /**
17737     * If your view subclass is displaying its own Drawable objects, it should
17738     * override this function and return true for any Drawable it is
17739     * displaying.  This allows animations for those drawables to be
17740     * scheduled.
17741     *
17742     * <p>Be sure to call through to the super class when overriding this
17743     * function.
17744     *
17745     * @param who The Drawable to verify.  Return true if it is one you are
17746     *            displaying, else return the result of calling through to the
17747     *            super class.
17748     *
17749     * @return boolean If true than the Drawable is being displayed in the
17750     *         view; else false and it is not allowed to animate.
17751     *
17752     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
17753     * @see #drawableStateChanged()
17754     */
17755    @CallSuper
17756    protected boolean verifyDrawable(@NonNull Drawable who) {
17757        // Avoid verifying the scroll bar drawable so that we don't end up in
17758        // an invalidation loop. This effectively prevents the scroll bar
17759        // drawable from triggering invalidations and scheduling runnables.
17760        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
17761    }
17762
17763    /**
17764     * This function is called whenever the state of the view changes in such
17765     * a way that it impacts the state of drawables being shown.
17766     * <p>
17767     * If the View has a StateListAnimator, it will also be called to run necessary state
17768     * change animations.
17769     * <p>
17770     * Be sure to call through to the superclass when overriding this function.
17771     *
17772     * @see Drawable#setState(int[])
17773     */
17774    @CallSuper
17775    protected void drawableStateChanged() {
17776        final int[] state = getDrawableState();
17777        boolean changed = false;
17778
17779        final Drawable bg = mBackground;
17780        if (bg != null && bg.isStateful()) {
17781            changed |= bg.setState(state);
17782        }
17783
17784        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17785        if (fg != null && fg.isStateful()) {
17786            changed |= fg.setState(state);
17787        }
17788
17789        if (mScrollCache != null) {
17790            final Drawable scrollBar = mScrollCache.scrollBar;
17791            if (scrollBar != null && scrollBar.isStateful()) {
17792                changed |= scrollBar.setState(state)
17793                        && mScrollCache.state != ScrollabilityCache.OFF;
17794            }
17795        }
17796
17797        if (mStateListAnimator != null) {
17798            mStateListAnimator.setState(state);
17799        }
17800
17801        if (changed) {
17802            invalidate();
17803        }
17804    }
17805
17806    /**
17807     * This function is called whenever the view hotspot changes and needs to
17808     * be propagated to drawables or child views managed by the view.
17809     * <p>
17810     * Dispatching to child views is handled by
17811     * {@link #dispatchDrawableHotspotChanged(float, float)}.
17812     * <p>
17813     * Be sure to call through to the superclass when overriding this function.
17814     *
17815     * @param x hotspot x coordinate
17816     * @param y hotspot y coordinate
17817     */
17818    @CallSuper
17819    public void drawableHotspotChanged(float x, float y) {
17820        if (mBackground != null) {
17821            mBackground.setHotspot(x, y);
17822        }
17823        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17824            mForegroundInfo.mDrawable.setHotspot(x, y);
17825        }
17826
17827        dispatchDrawableHotspotChanged(x, y);
17828    }
17829
17830    /**
17831     * Dispatches drawableHotspotChanged to all of this View's children.
17832     *
17833     * @param x hotspot x coordinate
17834     * @param y hotspot y coordinate
17835     * @see #drawableHotspotChanged(float, float)
17836     */
17837    public void dispatchDrawableHotspotChanged(float x, float y) {
17838    }
17839
17840    /**
17841     * Call this to force a view to update its drawable state. This will cause
17842     * drawableStateChanged to be called on this view. Views that are interested
17843     * in the new state should call getDrawableState.
17844     *
17845     * @see #drawableStateChanged
17846     * @see #getDrawableState
17847     */
17848    public void refreshDrawableState() {
17849        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
17850        drawableStateChanged();
17851
17852        ViewParent parent = mParent;
17853        if (parent != null) {
17854            parent.childDrawableStateChanged(this);
17855        }
17856    }
17857
17858    /**
17859     * Return an array of resource IDs of the drawable states representing the
17860     * current state of the view.
17861     *
17862     * @return The current drawable state
17863     *
17864     * @see Drawable#setState(int[])
17865     * @see #drawableStateChanged()
17866     * @see #onCreateDrawableState(int)
17867     */
17868    public final int[] getDrawableState() {
17869        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
17870            return mDrawableState;
17871        } else {
17872            mDrawableState = onCreateDrawableState(0);
17873            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
17874            return mDrawableState;
17875        }
17876    }
17877
17878    /**
17879     * Generate the new {@link android.graphics.drawable.Drawable} state for
17880     * this view. This is called by the view
17881     * system when the cached Drawable state is determined to be invalid.  To
17882     * retrieve the current state, you should use {@link #getDrawableState}.
17883     *
17884     * @param extraSpace if non-zero, this is the number of extra entries you
17885     * would like in the returned array in which you can place your own
17886     * states.
17887     *
17888     * @return Returns an array holding the current {@link Drawable} state of
17889     * the view.
17890     *
17891     * @see #mergeDrawableStates(int[], int[])
17892     */
17893    protected int[] onCreateDrawableState(int extraSpace) {
17894        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
17895                mParent instanceof View) {
17896            return ((View) mParent).onCreateDrawableState(extraSpace);
17897        }
17898
17899        int[] drawableState;
17900
17901        int privateFlags = mPrivateFlags;
17902
17903        int viewStateIndex = 0;
17904        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
17905        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
17906        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
17907        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
17908        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
17909        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
17910        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
17911                ThreadedRenderer.isAvailable()) {
17912            // This is set if HW acceleration is requested, even if the current
17913            // process doesn't allow it.  This is just to allow app preview
17914            // windows to better match their app.
17915            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
17916        }
17917        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
17918
17919        final int privateFlags2 = mPrivateFlags2;
17920        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
17921            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
17922        }
17923        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
17924            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
17925        }
17926
17927        drawableState = StateSet.get(viewStateIndex);
17928
17929        //noinspection ConstantIfStatement
17930        if (false) {
17931            Log.i("View", "drawableStateIndex=" + viewStateIndex);
17932            Log.i("View", toString()
17933                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
17934                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
17935                    + " fo=" + hasFocus()
17936                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
17937                    + " wf=" + hasWindowFocus()
17938                    + ": " + Arrays.toString(drawableState));
17939        }
17940
17941        if (extraSpace == 0) {
17942            return drawableState;
17943        }
17944
17945        final int[] fullState;
17946        if (drawableState != null) {
17947            fullState = new int[drawableState.length + extraSpace];
17948            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
17949        } else {
17950            fullState = new int[extraSpace];
17951        }
17952
17953        return fullState;
17954    }
17955
17956    /**
17957     * Merge your own state values in <var>additionalState</var> into the base
17958     * state values <var>baseState</var> that were returned by
17959     * {@link #onCreateDrawableState(int)}.
17960     *
17961     * @param baseState The base state values returned by
17962     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
17963     * own additional state values.
17964     *
17965     * @param additionalState The additional state values you would like
17966     * added to <var>baseState</var>; this array is not modified.
17967     *
17968     * @return As a convenience, the <var>baseState</var> array you originally
17969     * passed into the function is returned.
17970     *
17971     * @see #onCreateDrawableState(int)
17972     */
17973    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
17974        final int N = baseState.length;
17975        int i = N - 1;
17976        while (i >= 0 && baseState[i] == 0) {
17977            i--;
17978        }
17979        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
17980        return baseState;
17981    }
17982
17983    /**
17984     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
17985     * on all Drawable objects associated with this view.
17986     * <p>
17987     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
17988     * attached to this view.
17989     */
17990    @CallSuper
17991    public void jumpDrawablesToCurrentState() {
17992        if (mBackground != null) {
17993            mBackground.jumpToCurrentState();
17994        }
17995        if (mStateListAnimator != null) {
17996            mStateListAnimator.jumpToCurrentState();
17997        }
17998        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17999            mForegroundInfo.mDrawable.jumpToCurrentState();
18000        }
18001    }
18002
18003    /**
18004     * Sets the background color for this view.
18005     * @param color the color of the background
18006     */
18007    @RemotableViewMethod
18008    public void setBackgroundColor(@ColorInt int color) {
18009        if (mBackground instanceof ColorDrawable) {
18010            ((ColorDrawable) mBackground.mutate()).setColor(color);
18011            computeOpaqueFlags();
18012            mBackgroundResource = 0;
18013        } else {
18014            setBackground(new ColorDrawable(color));
18015        }
18016    }
18017
18018    /**
18019     * Set the background to a given resource. The resource should refer to
18020     * a Drawable object or 0 to remove the background.
18021     * @param resid The identifier of the resource.
18022     *
18023     * @attr ref android.R.styleable#View_background
18024     */
18025    @RemotableViewMethod
18026    public void setBackgroundResource(@DrawableRes int resid) {
18027        if (resid != 0 && resid == mBackgroundResource) {
18028            return;
18029        }
18030
18031        Drawable d = null;
18032        if (resid != 0) {
18033            d = mContext.getDrawable(resid);
18034        }
18035        setBackground(d);
18036
18037        mBackgroundResource = resid;
18038    }
18039
18040    /**
18041     * Set the background to a given Drawable, or remove the background. If the
18042     * background has padding, this View's padding is set to the background's
18043     * padding. However, when a background is removed, this View's padding isn't
18044     * touched. If setting the padding is desired, please use
18045     * {@link #setPadding(int, int, int, int)}.
18046     *
18047     * @param background The Drawable to use as the background, or null to remove the
18048     *        background
18049     */
18050    public void setBackground(Drawable background) {
18051        //noinspection deprecation
18052        setBackgroundDrawable(background);
18053    }
18054
18055    /**
18056     * @deprecated use {@link #setBackground(Drawable)} instead
18057     */
18058    @Deprecated
18059    public void setBackgroundDrawable(Drawable background) {
18060        computeOpaqueFlags();
18061
18062        if (background == mBackground) {
18063            return;
18064        }
18065
18066        boolean requestLayout = false;
18067
18068        mBackgroundResource = 0;
18069
18070        /*
18071         * Regardless of whether we're setting a new background or not, we want
18072         * to clear the previous drawable. setVisible first while we still have the callback set.
18073         */
18074        if (mBackground != null) {
18075            // It's possible for this method to be invoked from the View constructor before
18076            // subclass constructors have run. Drawables can and should trigger invalidations
18077            // and other activity with their callback on visibility changes, which shouldn't
18078            // happen before subclass constructors finish. However, we won't have set the
18079            // drawable as visible until the view becomes attached. This guard below keeps
18080            // multiple calls to this method from constructors from causing issues.
18081            if (mBackground.isVisible()) {
18082                mBackground.setVisible(false, false);
18083            }
18084            mBackground.setCallback(null);
18085            unscheduleDrawable(mBackground);
18086        }
18087
18088        if (background != null) {
18089            Rect padding = sThreadLocal.get();
18090            if (padding == null) {
18091                padding = new Rect();
18092                sThreadLocal.set(padding);
18093            }
18094            resetResolvedDrawablesInternal();
18095            background.setLayoutDirection(getLayoutDirection());
18096            if (background.getPadding(padding)) {
18097                resetResolvedPaddingInternal();
18098                switch (background.getLayoutDirection()) {
18099                    case LAYOUT_DIRECTION_RTL:
18100                        mUserPaddingLeftInitial = padding.right;
18101                        mUserPaddingRightInitial = padding.left;
18102                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18103                        break;
18104                    case LAYOUT_DIRECTION_LTR:
18105                    default:
18106                        mUserPaddingLeftInitial = padding.left;
18107                        mUserPaddingRightInitial = padding.right;
18108                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18109                }
18110                mLeftPaddingDefined = false;
18111                mRightPaddingDefined = false;
18112            }
18113
18114            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18115            // if it has a different minimum size, we should layout again
18116            if (mBackground == null
18117                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18118                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18119                requestLayout = true;
18120            }
18121
18122            // Set mBackground before we set this as the callback and start making other
18123            // background drawable state change calls. In particular, the setVisible call below
18124            // can result in drawables attempting to start animations or otherwise invalidate,
18125            // which requires the view set as the callback (us) to recognize the drawable as
18126            // belonging to it as per verifyDrawable.
18127            mBackground = background;
18128            if (background.isStateful()) {
18129                background.setState(getDrawableState());
18130            }
18131            if (isAttachedToWindow()) {
18132                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18133            }
18134
18135            applyBackgroundTint();
18136
18137            // Set callback last, since the view may still be initializing.
18138            background.setCallback(this);
18139
18140            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18141                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18142                requestLayout = true;
18143            }
18144        } else {
18145            /* Remove the background */
18146            mBackground = null;
18147            if ((mViewFlags & WILL_NOT_DRAW) != 0
18148                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18149                mPrivateFlags |= PFLAG_SKIP_DRAW;
18150            }
18151
18152            /*
18153             * When the background is set, we try to apply its padding to this
18154             * View. When the background is removed, we don't touch this View's
18155             * padding. This is noted in the Javadocs. Hence, we don't need to
18156             * requestLayout(), the invalidate() below is sufficient.
18157             */
18158
18159            // The old background's minimum size could have affected this
18160            // View's layout, so let's requestLayout
18161            requestLayout = true;
18162        }
18163
18164        computeOpaqueFlags();
18165
18166        if (requestLayout) {
18167            requestLayout();
18168        }
18169
18170        mBackgroundSizeChanged = true;
18171        invalidate(true);
18172        invalidateOutline();
18173    }
18174
18175    /**
18176     * Gets the background drawable
18177     *
18178     * @return The drawable used as the background for this view, if any.
18179     *
18180     * @see #setBackground(Drawable)
18181     *
18182     * @attr ref android.R.styleable#View_background
18183     */
18184    public Drawable getBackground() {
18185        return mBackground;
18186    }
18187
18188    /**
18189     * Applies a tint to the background drawable. Does not modify the current tint
18190     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18191     * <p>
18192     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18193     * mutate the drawable and apply the specified tint and tint mode using
18194     * {@link Drawable#setTintList(ColorStateList)}.
18195     *
18196     * @param tint the tint to apply, may be {@code null} to clear tint
18197     *
18198     * @attr ref android.R.styleable#View_backgroundTint
18199     * @see #getBackgroundTintList()
18200     * @see Drawable#setTintList(ColorStateList)
18201     */
18202    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18203        if (mBackgroundTint == null) {
18204            mBackgroundTint = new TintInfo();
18205        }
18206        mBackgroundTint.mTintList = tint;
18207        mBackgroundTint.mHasTintList = true;
18208
18209        applyBackgroundTint();
18210    }
18211
18212    /**
18213     * Return the tint applied to the background drawable, if specified.
18214     *
18215     * @return the tint applied to the background drawable
18216     * @attr ref android.R.styleable#View_backgroundTint
18217     * @see #setBackgroundTintList(ColorStateList)
18218     */
18219    @Nullable
18220    public ColorStateList getBackgroundTintList() {
18221        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18222    }
18223
18224    /**
18225     * Specifies the blending mode used to apply the tint specified by
18226     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18227     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18228     *
18229     * @param tintMode the blending mode used to apply the tint, may be
18230     *                 {@code null} to clear tint
18231     * @attr ref android.R.styleable#View_backgroundTintMode
18232     * @see #getBackgroundTintMode()
18233     * @see Drawable#setTintMode(PorterDuff.Mode)
18234     */
18235    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18236        if (mBackgroundTint == null) {
18237            mBackgroundTint = new TintInfo();
18238        }
18239        mBackgroundTint.mTintMode = tintMode;
18240        mBackgroundTint.mHasTintMode = true;
18241
18242        applyBackgroundTint();
18243    }
18244
18245    /**
18246     * Return the blending mode used to apply the tint to the background
18247     * drawable, if specified.
18248     *
18249     * @return the blending mode used to apply the tint to the background
18250     *         drawable
18251     * @attr ref android.R.styleable#View_backgroundTintMode
18252     * @see #setBackgroundTintMode(PorterDuff.Mode)
18253     */
18254    @Nullable
18255    public PorterDuff.Mode getBackgroundTintMode() {
18256        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18257    }
18258
18259    private void applyBackgroundTint() {
18260        if (mBackground != null && mBackgroundTint != null) {
18261            final TintInfo tintInfo = mBackgroundTint;
18262            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18263                mBackground = mBackground.mutate();
18264
18265                if (tintInfo.mHasTintList) {
18266                    mBackground.setTintList(tintInfo.mTintList);
18267                }
18268
18269                if (tintInfo.mHasTintMode) {
18270                    mBackground.setTintMode(tintInfo.mTintMode);
18271                }
18272
18273                // The drawable (or one of its children) may not have been
18274                // stateful before applying the tint, so let's try again.
18275                if (mBackground.isStateful()) {
18276                    mBackground.setState(getDrawableState());
18277                }
18278            }
18279        }
18280    }
18281
18282    /**
18283     * Returns the drawable used as the foreground of this View. The
18284     * foreground drawable, if non-null, is always drawn on top of the view's content.
18285     *
18286     * @return a Drawable or null if no foreground was set
18287     *
18288     * @see #onDrawForeground(Canvas)
18289     */
18290    public Drawable getForeground() {
18291        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18292    }
18293
18294    /**
18295     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18296     *
18297     * @param foreground the Drawable to be drawn on top of the children
18298     *
18299     * @attr ref android.R.styleable#View_foreground
18300     */
18301    public void setForeground(Drawable foreground) {
18302        if (mForegroundInfo == null) {
18303            if (foreground == null) {
18304                // Nothing to do.
18305                return;
18306            }
18307            mForegroundInfo = new ForegroundInfo();
18308        }
18309
18310        if (foreground == mForegroundInfo.mDrawable) {
18311            // Nothing to do
18312            return;
18313        }
18314
18315        if (mForegroundInfo.mDrawable != null) {
18316            // It's possible for this method to be invoked from the View constructor before
18317            // subclass constructors have run. Drawables can and should trigger invalidations
18318            // and other activity with their callback on visibility changes, which shouldn't
18319            // happen before subclass constructors finish. However, we won't have set the
18320            // drawable as visible until the view becomes attached. This guard below keeps
18321            // multiple calls to this method from constructors from causing issues.
18322            if (mForegroundInfo.mDrawable.isVisible()) {
18323                mForegroundInfo.mDrawable.setVisible(false, false);
18324            }
18325            mForegroundInfo.mDrawable.setCallback(null);
18326            unscheduleDrawable(mForegroundInfo.mDrawable);
18327        }
18328
18329        mForegroundInfo.mDrawable = foreground;
18330        mForegroundInfo.mBoundsChanged = true;
18331        if (foreground != null) {
18332            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18333                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18334            }
18335            foreground.setLayoutDirection(getLayoutDirection());
18336            if (foreground.isStateful()) {
18337                foreground.setState(getDrawableState());
18338            }
18339            applyForegroundTint();
18340            if (isAttachedToWindow()) {
18341                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18342            }
18343            // Set callback last, since the view may still be initializing.
18344            foreground.setCallback(this);
18345        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18346            mPrivateFlags |= PFLAG_SKIP_DRAW;
18347        }
18348        requestLayout();
18349        invalidate();
18350    }
18351
18352    /**
18353     * Magic bit used to support features of framework-internal window decor implementation details.
18354     * This used to live exclusively in FrameLayout.
18355     *
18356     * @return true if the foreground should draw inside the padding region or false
18357     *         if it should draw inset by the view's padding
18358     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18359     */
18360    public boolean isForegroundInsidePadding() {
18361        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18362    }
18363
18364    /**
18365     * Describes how the foreground is positioned.
18366     *
18367     * @return foreground gravity.
18368     *
18369     * @see #setForegroundGravity(int)
18370     *
18371     * @attr ref android.R.styleable#View_foregroundGravity
18372     */
18373    public int getForegroundGravity() {
18374        return mForegroundInfo != null ? mForegroundInfo.mGravity
18375                : Gravity.START | Gravity.TOP;
18376    }
18377
18378    /**
18379     * Describes how the foreground is positioned. Defaults to START and TOP.
18380     *
18381     * @param gravity see {@link android.view.Gravity}
18382     *
18383     * @see #getForegroundGravity()
18384     *
18385     * @attr ref android.R.styleable#View_foregroundGravity
18386     */
18387    public void setForegroundGravity(int gravity) {
18388        if (mForegroundInfo == null) {
18389            mForegroundInfo = new ForegroundInfo();
18390        }
18391
18392        if (mForegroundInfo.mGravity != gravity) {
18393            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
18394                gravity |= Gravity.START;
18395            }
18396
18397            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
18398                gravity |= Gravity.TOP;
18399            }
18400
18401            mForegroundInfo.mGravity = gravity;
18402            requestLayout();
18403        }
18404    }
18405
18406    /**
18407     * Applies a tint to the foreground drawable. Does not modify the current tint
18408     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18409     * <p>
18410     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
18411     * mutate the drawable and apply the specified tint and tint mode using
18412     * {@link Drawable#setTintList(ColorStateList)}.
18413     *
18414     * @param tint the tint to apply, may be {@code null} to clear tint
18415     *
18416     * @attr ref android.R.styleable#View_foregroundTint
18417     * @see #getForegroundTintList()
18418     * @see Drawable#setTintList(ColorStateList)
18419     */
18420    public void setForegroundTintList(@Nullable ColorStateList tint) {
18421        if (mForegroundInfo == null) {
18422            mForegroundInfo = new ForegroundInfo();
18423        }
18424        if (mForegroundInfo.mTintInfo == null) {
18425            mForegroundInfo.mTintInfo = new TintInfo();
18426        }
18427        mForegroundInfo.mTintInfo.mTintList = tint;
18428        mForegroundInfo.mTintInfo.mHasTintList = true;
18429
18430        applyForegroundTint();
18431    }
18432
18433    /**
18434     * Return the tint applied to the foreground drawable, if specified.
18435     *
18436     * @return the tint applied to the foreground drawable
18437     * @attr ref android.R.styleable#View_foregroundTint
18438     * @see #setForegroundTintList(ColorStateList)
18439     */
18440    @Nullable
18441    public ColorStateList getForegroundTintList() {
18442        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18443                ? mForegroundInfo.mTintInfo.mTintList : null;
18444    }
18445
18446    /**
18447     * Specifies the blending mode used to apply the tint specified by
18448     * {@link #setForegroundTintList(ColorStateList)}} to the background
18449     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18450     *
18451     * @param tintMode the blending mode used to apply the tint, may be
18452     *                 {@code null} to clear tint
18453     * @attr ref android.R.styleable#View_foregroundTintMode
18454     * @see #getForegroundTintMode()
18455     * @see Drawable#setTintMode(PorterDuff.Mode)
18456     */
18457    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18458        if (mForegroundInfo == null) {
18459            mForegroundInfo = new ForegroundInfo();
18460        }
18461        if (mForegroundInfo.mTintInfo == null) {
18462            mForegroundInfo.mTintInfo = new TintInfo();
18463        }
18464        mForegroundInfo.mTintInfo.mTintMode = tintMode;
18465        mForegroundInfo.mTintInfo.mHasTintMode = true;
18466
18467        applyForegroundTint();
18468    }
18469
18470    /**
18471     * Return the blending mode used to apply the tint to the foreground
18472     * drawable, if specified.
18473     *
18474     * @return the blending mode used to apply the tint to the foreground
18475     *         drawable
18476     * @attr ref android.R.styleable#View_foregroundTintMode
18477     * @see #setForegroundTintMode(PorterDuff.Mode)
18478     */
18479    @Nullable
18480    public PorterDuff.Mode getForegroundTintMode() {
18481        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18482                ? mForegroundInfo.mTintInfo.mTintMode : null;
18483    }
18484
18485    private void applyForegroundTint() {
18486        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
18487                && mForegroundInfo.mTintInfo != null) {
18488            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
18489            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18490                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
18491
18492                if (tintInfo.mHasTintList) {
18493                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
18494                }
18495
18496                if (tintInfo.mHasTintMode) {
18497                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
18498                }
18499
18500                // The drawable (or one of its children) may not have been
18501                // stateful before applying the tint, so let's try again.
18502                if (mForegroundInfo.mDrawable.isStateful()) {
18503                    mForegroundInfo.mDrawable.setState(getDrawableState());
18504                }
18505            }
18506        }
18507    }
18508
18509    /**
18510     * Draw any foreground content for this view.
18511     *
18512     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
18513     * drawable or other view-specific decorations. The foreground is drawn on top of the
18514     * primary view content.</p>
18515     *
18516     * @param canvas canvas to draw into
18517     */
18518    public void onDrawForeground(Canvas canvas) {
18519        onDrawScrollIndicators(canvas);
18520        onDrawScrollBars(canvas);
18521
18522        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18523        if (foreground != null) {
18524            if (mForegroundInfo.mBoundsChanged) {
18525                mForegroundInfo.mBoundsChanged = false;
18526                final Rect selfBounds = mForegroundInfo.mSelfBounds;
18527                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
18528
18529                if (mForegroundInfo.mInsidePadding) {
18530                    selfBounds.set(0, 0, getWidth(), getHeight());
18531                } else {
18532                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
18533                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
18534                }
18535
18536                final int ld = getLayoutDirection();
18537                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
18538                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
18539                foreground.setBounds(overlayBounds);
18540            }
18541
18542            foreground.draw(canvas);
18543        }
18544    }
18545
18546    /**
18547     * Sets the padding. The view may add on the space required to display
18548     * the scrollbars, depending on the style and visibility of the scrollbars.
18549     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
18550     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
18551     * from the values set in this call.
18552     *
18553     * @attr ref android.R.styleable#View_padding
18554     * @attr ref android.R.styleable#View_paddingBottom
18555     * @attr ref android.R.styleable#View_paddingLeft
18556     * @attr ref android.R.styleable#View_paddingRight
18557     * @attr ref android.R.styleable#View_paddingTop
18558     * @param left the left padding in pixels
18559     * @param top the top padding in pixels
18560     * @param right the right padding in pixels
18561     * @param bottom the bottom padding in pixels
18562     */
18563    public void setPadding(int left, int top, int right, int bottom) {
18564        resetResolvedPaddingInternal();
18565
18566        mUserPaddingStart = UNDEFINED_PADDING;
18567        mUserPaddingEnd = UNDEFINED_PADDING;
18568
18569        mUserPaddingLeftInitial = left;
18570        mUserPaddingRightInitial = right;
18571
18572        mLeftPaddingDefined = true;
18573        mRightPaddingDefined = true;
18574
18575        internalSetPadding(left, top, right, bottom);
18576    }
18577
18578    /**
18579     * @hide
18580     */
18581    protected void internalSetPadding(int left, int top, int right, int bottom) {
18582        mUserPaddingLeft = left;
18583        mUserPaddingRight = right;
18584        mUserPaddingBottom = bottom;
18585
18586        final int viewFlags = mViewFlags;
18587        boolean changed = false;
18588
18589        // Common case is there are no scroll bars.
18590        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
18591            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
18592                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
18593                        ? 0 : getVerticalScrollbarWidth();
18594                switch (mVerticalScrollbarPosition) {
18595                    case SCROLLBAR_POSITION_DEFAULT:
18596                        if (isLayoutRtl()) {
18597                            left += offset;
18598                        } else {
18599                            right += offset;
18600                        }
18601                        break;
18602                    case SCROLLBAR_POSITION_RIGHT:
18603                        right += offset;
18604                        break;
18605                    case SCROLLBAR_POSITION_LEFT:
18606                        left += offset;
18607                        break;
18608                }
18609            }
18610            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
18611                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
18612                        ? 0 : getHorizontalScrollbarHeight();
18613            }
18614        }
18615
18616        if (mPaddingLeft != left) {
18617            changed = true;
18618            mPaddingLeft = left;
18619        }
18620        if (mPaddingTop != top) {
18621            changed = true;
18622            mPaddingTop = top;
18623        }
18624        if (mPaddingRight != right) {
18625            changed = true;
18626            mPaddingRight = right;
18627        }
18628        if (mPaddingBottom != bottom) {
18629            changed = true;
18630            mPaddingBottom = bottom;
18631        }
18632
18633        if (changed) {
18634            requestLayout();
18635            invalidateOutline();
18636        }
18637    }
18638
18639    /**
18640     * Sets the relative padding. The view may add on the space required to display
18641     * the scrollbars, depending on the style and visibility of the scrollbars.
18642     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
18643     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
18644     * from the values set in this call.
18645     *
18646     * @attr ref android.R.styleable#View_padding
18647     * @attr ref android.R.styleable#View_paddingBottom
18648     * @attr ref android.R.styleable#View_paddingStart
18649     * @attr ref android.R.styleable#View_paddingEnd
18650     * @attr ref android.R.styleable#View_paddingTop
18651     * @param start the start padding in pixels
18652     * @param top the top padding in pixels
18653     * @param end the end padding in pixels
18654     * @param bottom the bottom padding in pixels
18655     */
18656    public void setPaddingRelative(int start, int top, int end, int bottom) {
18657        resetResolvedPaddingInternal();
18658
18659        mUserPaddingStart = start;
18660        mUserPaddingEnd = end;
18661        mLeftPaddingDefined = true;
18662        mRightPaddingDefined = true;
18663
18664        switch(getLayoutDirection()) {
18665            case LAYOUT_DIRECTION_RTL:
18666                mUserPaddingLeftInitial = end;
18667                mUserPaddingRightInitial = start;
18668                internalSetPadding(end, top, start, bottom);
18669                break;
18670            case LAYOUT_DIRECTION_LTR:
18671            default:
18672                mUserPaddingLeftInitial = start;
18673                mUserPaddingRightInitial = end;
18674                internalSetPadding(start, top, end, bottom);
18675        }
18676    }
18677
18678    /**
18679     * Returns the top padding of this view.
18680     *
18681     * @return the top padding in pixels
18682     */
18683    public int getPaddingTop() {
18684        return mPaddingTop;
18685    }
18686
18687    /**
18688     * Returns the bottom padding of this view. If there are inset and enabled
18689     * scrollbars, this value may include the space required to display the
18690     * scrollbars as well.
18691     *
18692     * @return the bottom padding in pixels
18693     */
18694    public int getPaddingBottom() {
18695        return mPaddingBottom;
18696    }
18697
18698    /**
18699     * Returns the left padding of this view. If there are inset and enabled
18700     * scrollbars, this value may include the space required to display the
18701     * scrollbars as well.
18702     *
18703     * @return the left padding in pixels
18704     */
18705    public int getPaddingLeft() {
18706        if (!isPaddingResolved()) {
18707            resolvePadding();
18708        }
18709        return mPaddingLeft;
18710    }
18711
18712    /**
18713     * Returns the start padding of this view depending on its resolved layout direction.
18714     * If there are inset and enabled scrollbars, this value may include the space
18715     * required to display the scrollbars as well.
18716     *
18717     * @return the start padding in pixels
18718     */
18719    public int getPaddingStart() {
18720        if (!isPaddingResolved()) {
18721            resolvePadding();
18722        }
18723        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18724                mPaddingRight : mPaddingLeft;
18725    }
18726
18727    /**
18728     * Returns the right padding of this view. If there are inset and enabled
18729     * scrollbars, this value may include the space required to display the
18730     * scrollbars as well.
18731     *
18732     * @return the right padding in pixels
18733     */
18734    public int getPaddingRight() {
18735        if (!isPaddingResolved()) {
18736            resolvePadding();
18737        }
18738        return mPaddingRight;
18739    }
18740
18741    /**
18742     * Returns the end padding of this view depending on its resolved layout direction.
18743     * If there are inset and enabled scrollbars, this value may include the space
18744     * required to display the scrollbars as well.
18745     *
18746     * @return the end padding in pixels
18747     */
18748    public int getPaddingEnd() {
18749        if (!isPaddingResolved()) {
18750            resolvePadding();
18751        }
18752        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18753                mPaddingLeft : mPaddingRight;
18754    }
18755
18756    /**
18757     * Return if the padding has been set through relative values
18758     * {@link #setPaddingRelative(int, int, int, int)} or through
18759     * @attr ref android.R.styleable#View_paddingStart or
18760     * @attr ref android.R.styleable#View_paddingEnd
18761     *
18762     * @return true if the padding is relative or false if it is not.
18763     */
18764    public boolean isPaddingRelative() {
18765        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
18766    }
18767
18768    Insets computeOpticalInsets() {
18769        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
18770    }
18771
18772    /**
18773     * @hide
18774     */
18775    public void resetPaddingToInitialValues() {
18776        if (isRtlCompatibilityMode()) {
18777            mPaddingLeft = mUserPaddingLeftInitial;
18778            mPaddingRight = mUserPaddingRightInitial;
18779            return;
18780        }
18781        if (isLayoutRtl()) {
18782            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
18783            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
18784        } else {
18785            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
18786            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
18787        }
18788    }
18789
18790    /**
18791     * @hide
18792     */
18793    public Insets getOpticalInsets() {
18794        if (mLayoutInsets == null) {
18795            mLayoutInsets = computeOpticalInsets();
18796        }
18797        return mLayoutInsets;
18798    }
18799
18800    /**
18801     * Set this view's optical insets.
18802     *
18803     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
18804     * property. Views that compute their own optical insets should call it as part of measurement.
18805     * This method does not request layout. If you are setting optical insets outside of
18806     * measure/layout itself you will want to call requestLayout() yourself.
18807     * </p>
18808     * @hide
18809     */
18810    public void setOpticalInsets(Insets insets) {
18811        mLayoutInsets = insets;
18812    }
18813
18814    /**
18815     * Changes the selection state of this view. A view can be selected or not.
18816     * Note that selection is not the same as focus. Views are typically
18817     * selected in the context of an AdapterView like ListView or GridView;
18818     * the selected view is the view that is highlighted.
18819     *
18820     * @param selected true if the view must be selected, false otherwise
18821     */
18822    public void setSelected(boolean selected) {
18823        //noinspection DoubleNegation
18824        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
18825            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
18826            if (!selected) resetPressedState();
18827            invalidate(true);
18828            refreshDrawableState();
18829            dispatchSetSelected(selected);
18830            if (selected) {
18831                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
18832            } else {
18833                notifyViewAccessibilityStateChangedIfNeeded(
18834                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
18835            }
18836        }
18837    }
18838
18839    /**
18840     * Dispatch setSelected to all of this View's children.
18841     *
18842     * @see #setSelected(boolean)
18843     *
18844     * @param selected The new selected state
18845     */
18846    protected void dispatchSetSelected(boolean selected) {
18847    }
18848
18849    /**
18850     * Indicates the selection state of this view.
18851     *
18852     * @return true if the view is selected, false otherwise
18853     */
18854    @ViewDebug.ExportedProperty
18855    public boolean isSelected() {
18856        return (mPrivateFlags & PFLAG_SELECTED) != 0;
18857    }
18858
18859    /**
18860     * Changes the activated state of this view. A view can be activated or not.
18861     * Note that activation is not the same as selection.  Selection is
18862     * a transient property, representing the view (hierarchy) the user is
18863     * currently interacting with.  Activation is a longer-term state that the
18864     * user can move views in and out of.  For example, in a list view with
18865     * single or multiple selection enabled, the views in the current selection
18866     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
18867     * here.)  The activated state is propagated down to children of the view it
18868     * is set on.
18869     *
18870     * @param activated true if the view must be activated, false otherwise
18871     */
18872    public void setActivated(boolean activated) {
18873        //noinspection DoubleNegation
18874        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
18875            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
18876            invalidate(true);
18877            refreshDrawableState();
18878            dispatchSetActivated(activated);
18879        }
18880    }
18881
18882    /**
18883     * Dispatch setActivated to all of this View's children.
18884     *
18885     * @see #setActivated(boolean)
18886     *
18887     * @param activated The new activated state
18888     */
18889    protected void dispatchSetActivated(boolean activated) {
18890    }
18891
18892    /**
18893     * Indicates the activation state of this view.
18894     *
18895     * @return true if the view is activated, false otherwise
18896     */
18897    @ViewDebug.ExportedProperty
18898    public boolean isActivated() {
18899        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
18900    }
18901
18902    /**
18903     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
18904     * observer can be used to get notifications when global events, like
18905     * layout, happen.
18906     *
18907     * The returned ViewTreeObserver observer is not guaranteed to remain
18908     * valid for the lifetime of this View. If the caller of this method keeps
18909     * a long-lived reference to ViewTreeObserver, it should always check for
18910     * the return value of {@link ViewTreeObserver#isAlive()}.
18911     *
18912     * @return The ViewTreeObserver for this view's hierarchy.
18913     */
18914    public ViewTreeObserver getViewTreeObserver() {
18915        if (mAttachInfo != null) {
18916            return mAttachInfo.mTreeObserver;
18917        }
18918        if (mFloatingTreeObserver == null) {
18919            mFloatingTreeObserver = new ViewTreeObserver();
18920        }
18921        return mFloatingTreeObserver;
18922    }
18923
18924    /**
18925     * <p>Finds the topmost view in the current view hierarchy.</p>
18926     *
18927     * @return the topmost view containing this view
18928     */
18929    public View getRootView() {
18930        if (mAttachInfo != null) {
18931            final View v = mAttachInfo.mRootView;
18932            if (v != null) {
18933                return v;
18934            }
18935        }
18936
18937        View parent = this;
18938
18939        while (parent.mParent != null && parent.mParent instanceof View) {
18940            parent = (View) parent.mParent;
18941        }
18942
18943        return parent;
18944    }
18945
18946    /**
18947     * Transforms a motion event from view-local coordinates to on-screen
18948     * coordinates.
18949     *
18950     * @param ev the view-local motion event
18951     * @return false if the transformation could not be applied
18952     * @hide
18953     */
18954    public boolean toGlobalMotionEvent(MotionEvent ev) {
18955        final AttachInfo info = mAttachInfo;
18956        if (info == null) {
18957            return false;
18958        }
18959
18960        final Matrix m = info.mTmpMatrix;
18961        m.set(Matrix.IDENTITY_MATRIX);
18962        transformMatrixToGlobal(m);
18963        ev.transform(m);
18964        return true;
18965    }
18966
18967    /**
18968     * Transforms a motion event from on-screen coordinates to view-local
18969     * coordinates.
18970     *
18971     * @param ev the on-screen motion event
18972     * @return false if the transformation could not be applied
18973     * @hide
18974     */
18975    public boolean toLocalMotionEvent(MotionEvent ev) {
18976        final AttachInfo info = mAttachInfo;
18977        if (info == null) {
18978            return false;
18979        }
18980
18981        final Matrix m = info.mTmpMatrix;
18982        m.set(Matrix.IDENTITY_MATRIX);
18983        transformMatrixToLocal(m);
18984        ev.transform(m);
18985        return true;
18986    }
18987
18988    /**
18989     * Modifies the input matrix such that it maps view-local coordinates to
18990     * on-screen coordinates.
18991     *
18992     * @param m input matrix to modify
18993     * @hide
18994     */
18995    public void transformMatrixToGlobal(Matrix m) {
18996        final ViewParent parent = mParent;
18997        if (parent instanceof View) {
18998            final View vp = (View) parent;
18999            vp.transformMatrixToGlobal(m);
19000            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19001        } else if (parent instanceof ViewRootImpl) {
19002            final ViewRootImpl vr = (ViewRootImpl) parent;
19003            vr.transformMatrixToGlobal(m);
19004            m.preTranslate(0, -vr.mCurScrollY);
19005        }
19006
19007        m.preTranslate(mLeft, mTop);
19008
19009        if (!hasIdentityMatrix()) {
19010            m.preConcat(getMatrix());
19011        }
19012    }
19013
19014    /**
19015     * Modifies the input matrix such that it maps on-screen coordinates to
19016     * view-local coordinates.
19017     *
19018     * @param m input matrix to modify
19019     * @hide
19020     */
19021    public void transformMatrixToLocal(Matrix m) {
19022        final ViewParent parent = mParent;
19023        if (parent instanceof View) {
19024            final View vp = (View) parent;
19025            vp.transformMatrixToLocal(m);
19026            m.postTranslate(vp.mScrollX, vp.mScrollY);
19027        } else if (parent instanceof ViewRootImpl) {
19028            final ViewRootImpl vr = (ViewRootImpl) parent;
19029            vr.transformMatrixToLocal(m);
19030            m.postTranslate(0, vr.mCurScrollY);
19031        }
19032
19033        m.postTranslate(-mLeft, -mTop);
19034
19035        if (!hasIdentityMatrix()) {
19036            m.postConcat(getInverseMatrix());
19037        }
19038    }
19039
19040    /**
19041     * @hide
19042     */
19043    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19044            @ViewDebug.IntToString(from = 0, to = "x"),
19045            @ViewDebug.IntToString(from = 1, to = "y")
19046    })
19047    public int[] getLocationOnScreen() {
19048        int[] location = new int[2];
19049        getLocationOnScreen(location);
19050        return location;
19051    }
19052
19053    /**
19054     * <p>Computes the coordinates of this view on the screen. The argument
19055     * must be an array of two integers. After the method returns, the array
19056     * contains the x and y location in that order.</p>
19057     *
19058     * @param outLocation an array of two integers in which to hold the coordinates
19059     */
19060    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19061        getLocationInWindow(outLocation);
19062
19063        final AttachInfo info = mAttachInfo;
19064        if (info != null) {
19065            outLocation[0] += info.mWindowLeft;
19066            outLocation[1] += info.mWindowTop;
19067        }
19068    }
19069
19070    /**
19071     * <p>Computes the coordinates of this view in its window. The argument
19072     * must be an array of two integers. After the method returns, the array
19073     * contains the x and y location in that order.</p>
19074     *
19075     * @param outLocation an array of two integers in which to hold the coordinates
19076     */
19077    public void getLocationInWindow(@Size(2) int[] outLocation) {
19078        if (outLocation == null || outLocation.length < 2) {
19079            throw new IllegalArgumentException("outLocation must be an array of two integers");
19080        }
19081
19082        outLocation[0] = 0;
19083        outLocation[1] = 0;
19084
19085        transformFromViewToWindowSpace(outLocation);
19086    }
19087
19088    /** @hide */
19089    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19090        if (inOutLocation == null || inOutLocation.length < 2) {
19091            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19092        }
19093
19094        if (mAttachInfo == null) {
19095            // When the view is not attached to a window, this method does not make sense
19096            inOutLocation[0] = inOutLocation[1] = 0;
19097            return;
19098        }
19099
19100        float position[] = mAttachInfo.mTmpTransformLocation;
19101        position[0] = inOutLocation[0];
19102        position[1] = inOutLocation[1];
19103
19104        if (!hasIdentityMatrix()) {
19105            getMatrix().mapPoints(position);
19106        }
19107
19108        position[0] += mLeft;
19109        position[1] += mTop;
19110
19111        ViewParent viewParent = mParent;
19112        while (viewParent instanceof View) {
19113            final View view = (View) viewParent;
19114
19115            position[0] -= view.mScrollX;
19116            position[1] -= view.mScrollY;
19117
19118            if (!view.hasIdentityMatrix()) {
19119                view.getMatrix().mapPoints(position);
19120            }
19121
19122            position[0] += view.mLeft;
19123            position[1] += view.mTop;
19124
19125            viewParent = view.mParent;
19126         }
19127
19128        if (viewParent instanceof ViewRootImpl) {
19129            // *cough*
19130            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19131            position[1] -= vr.mCurScrollY;
19132        }
19133
19134        inOutLocation[0] = Math.round(position[0]);
19135        inOutLocation[1] = Math.round(position[1]);
19136    }
19137
19138    /**
19139     * {@hide}
19140     * @param id the id of the view to be found
19141     * @return the view of the specified id, null if cannot be found
19142     */
19143    protected View findViewTraversal(@IdRes int id) {
19144        if (id == mID) {
19145            return this;
19146        }
19147        return null;
19148    }
19149
19150    /**
19151     * {@hide}
19152     * @param tag the tag of the view to be found
19153     * @return the view of specified tag, null if cannot be found
19154     */
19155    protected View findViewWithTagTraversal(Object tag) {
19156        if (tag != null && tag.equals(mTag)) {
19157            return this;
19158        }
19159        return null;
19160    }
19161
19162    /**
19163     * {@hide}
19164     * @param predicate The predicate to evaluate.
19165     * @param childToSkip If not null, ignores this child during the recursive traversal.
19166     * @return The first view that matches the predicate or null.
19167     */
19168    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19169        if (predicate.apply(this)) {
19170            return this;
19171        }
19172        return null;
19173    }
19174
19175    /**
19176     * Look for a child view with the given id.  If this view has the given
19177     * id, return this view.
19178     *
19179     * @param id The id to search for.
19180     * @return The view that has the given id in the hierarchy or null
19181     */
19182    @Nullable
19183    public final View findViewById(@IdRes int id) {
19184        if (id < 0) {
19185            return null;
19186        }
19187        return findViewTraversal(id);
19188    }
19189
19190    /**
19191     * Finds a view by its unuque and stable accessibility id.
19192     *
19193     * @param accessibilityId The searched accessibility id.
19194     * @return The found view.
19195     */
19196    final View findViewByAccessibilityId(int accessibilityId) {
19197        if (accessibilityId < 0) {
19198            return null;
19199        }
19200        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19201        if (view != null) {
19202            return view.includeForAccessibility() ? view : null;
19203        }
19204        return null;
19205    }
19206
19207    /**
19208     * Performs the traversal to find a view by its unuque and stable accessibility id.
19209     *
19210     * <strong>Note:</strong>This method does not stop at the root namespace
19211     * boundary since the user can touch the screen at an arbitrary location
19212     * potentially crossing the root namespace bounday which will send an
19213     * accessibility event to accessibility services and they should be able
19214     * to obtain the event source. Also accessibility ids are guaranteed to be
19215     * unique in the window.
19216     *
19217     * @param accessibilityId The accessibility id.
19218     * @return The found view.
19219     *
19220     * @hide
19221     */
19222    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19223        if (getAccessibilityViewId() == accessibilityId) {
19224            return this;
19225        }
19226        return null;
19227    }
19228
19229    /**
19230     * Look for a child view with the given tag.  If this view has the given
19231     * tag, return this view.
19232     *
19233     * @param tag The tag to search for, using "tag.equals(getTag())".
19234     * @return The View that has the given tag in the hierarchy or null
19235     */
19236    public final View findViewWithTag(Object tag) {
19237        if (tag == null) {
19238            return null;
19239        }
19240        return findViewWithTagTraversal(tag);
19241    }
19242
19243    /**
19244     * {@hide}
19245     * Look for a child view that matches the specified predicate.
19246     * If this view matches the predicate, return this view.
19247     *
19248     * @param predicate The predicate to evaluate.
19249     * @return The first view that matches the predicate or null.
19250     */
19251    public final View findViewByPredicate(Predicate<View> predicate) {
19252        return findViewByPredicateTraversal(predicate, null);
19253    }
19254
19255    /**
19256     * {@hide}
19257     * Look for a child view that matches the specified predicate,
19258     * starting with the specified view and its descendents and then
19259     * recusively searching the ancestors and siblings of that view
19260     * until this view is reached.
19261     *
19262     * This method is useful in cases where the predicate does not match
19263     * a single unique view (perhaps multiple views use the same id)
19264     * and we are trying to find the view that is "closest" in scope to the
19265     * starting view.
19266     *
19267     * @param start The view to start from.
19268     * @param predicate The predicate to evaluate.
19269     * @return The first view that matches the predicate or null.
19270     */
19271    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19272        View childToSkip = null;
19273        for (;;) {
19274            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19275            if (view != null || start == this) {
19276                return view;
19277            }
19278
19279            ViewParent parent = start.getParent();
19280            if (parent == null || !(parent instanceof View)) {
19281                return null;
19282            }
19283
19284            childToSkip = start;
19285            start = (View) parent;
19286        }
19287    }
19288
19289    /**
19290     * Sets the identifier for this view. The identifier does not have to be
19291     * unique in this view's hierarchy. The identifier should be a positive
19292     * number.
19293     *
19294     * @see #NO_ID
19295     * @see #getId()
19296     * @see #findViewById(int)
19297     *
19298     * @param id a number used to identify the view
19299     *
19300     * @attr ref android.R.styleable#View_id
19301     */
19302    public void setId(@IdRes int id) {
19303        mID = id;
19304        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19305            mID = generateViewId();
19306        }
19307    }
19308
19309    /**
19310     * {@hide}
19311     *
19312     * @param isRoot true if the view belongs to the root namespace, false
19313     *        otherwise
19314     */
19315    public void setIsRootNamespace(boolean isRoot) {
19316        if (isRoot) {
19317            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19318        } else {
19319            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19320        }
19321    }
19322
19323    /**
19324     * {@hide}
19325     *
19326     * @return true if the view belongs to the root namespace, false otherwise
19327     */
19328    public boolean isRootNamespace() {
19329        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19330    }
19331
19332    /**
19333     * Returns this view's identifier.
19334     *
19335     * @return a positive integer used to identify the view or {@link #NO_ID}
19336     *         if the view has no ID
19337     *
19338     * @see #setId(int)
19339     * @see #findViewById(int)
19340     * @attr ref android.R.styleable#View_id
19341     */
19342    @IdRes
19343    @ViewDebug.CapturedViewProperty
19344    public int getId() {
19345        return mID;
19346    }
19347
19348    /**
19349     * Returns this view's tag.
19350     *
19351     * @return the Object stored in this view as a tag, or {@code null} if not
19352     *         set
19353     *
19354     * @see #setTag(Object)
19355     * @see #getTag(int)
19356     */
19357    @ViewDebug.ExportedProperty
19358    public Object getTag() {
19359        return mTag;
19360    }
19361
19362    /**
19363     * Sets the tag associated with this view. A tag can be used to mark
19364     * a view in its hierarchy and does not have to be unique within the
19365     * hierarchy. Tags can also be used to store data within a view without
19366     * resorting to another data structure.
19367     *
19368     * @param tag an Object to tag the view with
19369     *
19370     * @see #getTag()
19371     * @see #setTag(int, Object)
19372     */
19373    public void setTag(final Object tag) {
19374        mTag = tag;
19375    }
19376
19377    /**
19378     * Returns the tag associated with this view and the specified key.
19379     *
19380     * @param key The key identifying the tag
19381     *
19382     * @return the Object stored in this view as a tag, or {@code null} if not
19383     *         set
19384     *
19385     * @see #setTag(int, Object)
19386     * @see #getTag()
19387     */
19388    public Object getTag(int key) {
19389        if (mKeyedTags != null) return mKeyedTags.get(key);
19390        return null;
19391    }
19392
19393    /**
19394     * Sets a tag associated with this view and a key. A tag can be used
19395     * to mark a view in its hierarchy and does not have to be unique within
19396     * the hierarchy. Tags can also be used to store data within a view
19397     * without resorting to another data structure.
19398     *
19399     * The specified key should be an id declared in the resources of the
19400     * application to ensure it is unique (see the <a
19401     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
19402     * Keys identified as belonging to
19403     * the Android framework or not associated with any package will cause
19404     * an {@link IllegalArgumentException} to be thrown.
19405     *
19406     * @param key The key identifying the tag
19407     * @param tag An Object to tag the view with
19408     *
19409     * @throws IllegalArgumentException If they specified key is not valid
19410     *
19411     * @see #setTag(Object)
19412     * @see #getTag(int)
19413     */
19414    public void setTag(int key, final Object tag) {
19415        // If the package id is 0x00 or 0x01, it's either an undefined package
19416        // or a framework id
19417        if ((key >>> 24) < 2) {
19418            throw new IllegalArgumentException("The key must be an application-specific "
19419                    + "resource id.");
19420        }
19421
19422        setKeyedTag(key, tag);
19423    }
19424
19425    /**
19426     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
19427     * framework id.
19428     *
19429     * @hide
19430     */
19431    public void setTagInternal(int key, Object tag) {
19432        if ((key >>> 24) != 0x1) {
19433            throw new IllegalArgumentException("The key must be a framework-specific "
19434                    + "resource id.");
19435        }
19436
19437        setKeyedTag(key, tag);
19438    }
19439
19440    private void setKeyedTag(int key, Object tag) {
19441        if (mKeyedTags == null) {
19442            mKeyedTags = new SparseArray<Object>(2);
19443        }
19444
19445        mKeyedTags.put(key, tag);
19446    }
19447
19448    /**
19449     * Prints information about this view in the log output, with the tag
19450     * {@link #VIEW_LOG_TAG}.
19451     *
19452     * @hide
19453     */
19454    public void debug() {
19455        debug(0);
19456    }
19457
19458    /**
19459     * Prints information about this view in the log output, with the tag
19460     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
19461     * indentation defined by the <code>depth</code>.
19462     *
19463     * @param depth the indentation level
19464     *
19465     * @hide
19466     */
19467    protected void debug(int depth) {
19468        String output = debugIndent(depth - 1);
19469
19470        output += "+ " + this;
19471        int id = getId();
19472        if (id != -1) {
19473            output += " (id=" + id + ")";
19474        }
19475        Object tag = getTag();
19476        if (tag != null) {
19477            output += " (tag=" + tag + ")";
19478        }
19479        Log.d(VIEW_LOG_TAG, output);
19480
19481        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
19482            output = debugIndent(depth) + " FOCUSED";
19483            Log.d(VIEW_LOG_TAG, output);
19484        }
19485
19486        output = debugIndent(depth);
19487        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
19488                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
19489                + "} ";
19490        Log.d(VIEW_LOG_TAG, output);
19491
19492        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
19493                || mPaddingBottom != 0) {
19494            output = debugIndent(depth);
19495            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
19496                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
19497            Log.d(VIEW_LOG_TAG, output);
19498        }
19499
19500        output = debugIndent(depth);
19501        output += "mMeasureWidth=" + mMeasuredWidth +
19502                " mMeasureHeight=" + mMeasuredHeight;
19503        Log.d(VIEW_LOG_TAG, output);
19504
19505        output = debugIndent(depth);
19506        if (mLayoutParams == null) {
19507            output += "BAD! no layout params";
19508        } else {
19509            output = mLayoutParams.debug(output);
19510        }
19511        Log.d(VIEW_LOG_TAG, output);
19512
19513        output = debugIndent(depth);
19514        output += "flags={";
19515        output += View.printFlags(mViewFlags);
19516        output += "}";
19517        Log.d(VIEW_LOG_TAG, output);
19518
19519        output = debugIndent(depth);
19520        output += "privateFlags={";
19521        output += View.printPrivateFlags(mPrivateFlags);
19522        output += "}";
19523        Log.d(VIEW_LOG_TAG, output);
19524    }
19525
19526    /**
19527     * Creates a string of whitespaces used for indentation.
19528     *
19529     * @param depth the indentation level
19530     * @return a String containing (depth * 2 + 3) * 2 white spaces
19531     *
19532     * @hide
19533     */
19534    protected static String debugIndent(int depth) {
19535        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
19536        for (int i = 0; i < (depth * 2) + 3; i++) {
19537            spaces.append(' ').append(' ');
19538        }
19539        return spaces.toString();
19540    }
19541
19542    /**
19543     * <p>Return the offset of the widget's text baseline from the widget's top
19544     * boundary. If this widget does not support baseline alignment, this
19545     * method returns -1. </p>
19546     *
19547     * @return the offset of the baseline within the widget's bounds or -1
19548     *         if baseline alignment is not supported
19549     */
19550    @ViewDebug.ExportedProperty(category = "layout")
19551    public int getBaseline() {
19552        return -1;
19553    }
19554
19555    /**
19556     * Returns whether the view hierarchy is currently undergoing a layout pass. This
19557     * information is useful to avoid situations such as calling {@link #requestLayout()} during
19558     * a layout pass.
19559     *
19560     * @return whether the view hierarchy is currently undergoing a layout pass
19561     */
19562    public boolean isInLayout() {
19563        ViewRootImpl viewRoot = getViewRootImpl();
19564        return (viewRoot != null && viewRoot.isInLayout());
19565    }
19566
19567    /**
19568     * Call this when something has changed which has invalidated the
19569     * layout of this view. This will schedule a layout pass of the view
19570     * tree. This should not be called while the view hierarchy is currently in a layout
19571     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
19572     * end of the current layout pass (and then layout will run again) or after the current
19573     * frame is drawn and the next layout occurs.
19574     *
19575     * <p>Subclasses which override this method should call the superclass method to
19576     * handle possible request-during-layout errors correctly.</p>
19577     */
19578    @CallSuper
19579    public void requestLayout() {
19580        if (mMeasureCache != null) mMeasureCache.clear();
19581
19582        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
19583            // Only trigger request-during-layout logic if this is the view requesting it,
19584            // not the views in its parent hierarchy
19585            ViewRootImpl viewRoot = getViewRootImpl();
19586            if (viewRoot != null && viewRoot.isInLayout()) {
19587                if (!viewRoot.requestLayoutDuringLayout(this)) {
19588                    return;
19589                }
19590            }
19591            mAttachInfo.mViewRequestingLayout = this;
19592        }
19593
19594        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19595        mPrivateFlags |= PFLAG_INVALIDATED;
19596
19597        if (mParent != null && !mParent.isLayoutRequested()) {
19598            mParent.requestLayout();
19599        }
19600        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
19601            mAttachInfo.mViewRequestingLayout = null;
19602        }
19603    }
19604
19605    /**
19606     * Forces this view to be laid out during the next layout pass.
19607     * This method does not call requestLayout() or forceLayout()
19608     * on the parent.
19609     */
19610    public void forceLayout() {
19611        if (mMeasureCache != null) mMeasureCache.clear();
19612
19613        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19614        mPrivateFlags |= PFLAG_INVALIDATED;
19615    }
19616
19617    /**
19618     * <p>
19619     * This is called to find out how big a view should be. The parent
19620     * supplies constraint information in the width and height parameters.
19621     * </p>
19622     *
19623     * <p>
19624     * The actual measurement work of a view is performed in
19625     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
19626     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
19627     * </p>
19628     *
19629     *
19630     * @param widthMeasureSpec Horizontal space requirements as imposed by the
19631     *        parent
19632     * @param heightMeasureSpec Vertical space requirements as imposed by the
19633     *        parent
19634     *
19635     * @see #onMeasure(int, int)
19636     */
19637    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
19638        boolean optical = isLayoutModeOptical(this);
19639        if (optical != isLayoutModeOptical(mParent)) {
19640            Insets insets = getOpticalInsets();
19641            int oWidth  = insets.left + insets.right;
19642            int oHeight = insets.top  + insets.bottom;
19643            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
19644            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
19645        }
19646
19647        // Suppress sign extension for the low bytes
19648        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
19649        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
19650
19651        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19652
19653        // Optimize layout by avoiding an extra EXACTLY pass when the view is
19654        // already measured as the correct size. In API 23 and below, this
19655        // extra pass is required to make LinearLayout re-distribute weight.
19656        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
19657                || heightMeasureSpec != mOldHeightMeasureSpec;
19658        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
19659                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
19660        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
19661                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
19662        final boolean needsLayout = specChanged
19663                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
19664
19665        if (forceLayout || needsLayout) {
19666            // first clears the measured dimension flag
19667            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
19668
19669            resolveRtlPropertiesIfNeeded();
19670
19671            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
19672            if (cacheIndex < 0 || sIgnoreMeasureCache) {
19673                // measure ourselves, this should set the measured dimension flag back
19674                onMeasure(widthMeasureSpec, heightMeasureSpec);
19675                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19676            } else {
19677                long value = mMeasureCache.valueAt(cacheIndex);
19678                // Casting a long to int drops the high 32 bits, no mask needed
19679                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
19680                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19681            }
19682
19683            // flag not set, setMeasuredDimension() was not invoked, we raise
19684            // an exception to warn the developer
19685            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
19686                throw new IllegalStateException("View with id " + getId() + ": "
19687                        + getClass().getName() + "#onMeasure() did not set the"
19688                        + " measured dimension by calling"
19689                        + " setMeasuredDimension()");
19690            }
19691
19692            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
19693        }
19694
19695        mOldWidthMeasureSpec = widthMeasureSpec;
19696        mOldHeightMeasureSpec = heightMeasureSpec;
19697
19698        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
19699                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
19700    }
19701
19702    /**
19703     * <p>
19704     * Measure the view and its content to determine the measured width and the
19705     * measured height. This method is invoked by {@link #measure(int, int)} and
19706     * should be overridden by subclasses to provide accurate and efficient
19707     * measurement of their contents.
19708     * </p>
19709     *
19710     * <p>
19711     * <strong>CONTRACT:</strong> When overriding this method, you
19712     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
19713     * measured width and height of this view. Failure to do so will trigger an
19714     * <code>IllegalStateException</code>, thrown by
19715     * {@link #measure(int, int)}. Calling the superclass'
19716     * {@link #onMeasure(int, int)} is a valid use.
19717     * </p>
19718     *
19719     * <p>
19720     * The base class implementation of measure defaults to the background size,
19721     * unless a larger size is allowed by the MeasureSpec. Subclasses should
19722     * override {@link #onMeasure(int, int)} to provide better measurements of
19723     * their content.
19724     * </p>
19725     *
19726     * <p>
19727     * If this method is overridden, it is the subclass's responsibility to make
19728     * sure the measured height and width are at least the view's minimum height
19729     * and width ({@link #getSuggestedMinimumHeight()} and
19730     * {@link #getSuggestedMinimumWidth()}).
19731     * </p>
19732     *
19733     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
19734     *                         The requirements are encoded with
19735     *                         {@link android.view.View.MeasureSpec}.
19736     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
19737     *                         The requirements are encoded with
19738     *                         {@link android.view.View.MeasureSpec}.
19739     *
19740     * @see #getMeasuredWidth()
19741     * @see #getMeasuredHeight()
19742     * @see #setMeasuredDimension(int, int)
19743     * @see #getSuggestedMinimumHeight()
19744     * @see #getSuggestedMinimumWidth()
19745     * @see android.view.View.MeasureSpec#getMode(int)
19746     * @see android.view.View.MeasureSpec#getSize(int)
19747     */
19748    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
19749        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
19750                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
19751    }
19752
19753    /**
19754     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
19755     * measured width and measured height. Failing to do so will trigger an
19756     * exception at measurement time.</p>
19757     *
19758     * @param measuredWidth The measured width of this view.  May be a complex
19759     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19760     * {@link #MEASURED_STATE_TOO_SMALL}.
19761     * @param measuredHeight The measured height of this view.  May be a complex
19762     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19763     * {@link #MEASURED_STATE_TOO_SMALL}.
19764     */
19765    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
19766        boolean optical = isLayoutModeOptical(this);
19767        if (optical != isLayoutModeOptical(mParent)) {
19768            Insets insets = getOpticalInsets();
19769            int opticalWidth  = insets.left + insets.right;
19770            int opticalHeight = insets.top  + insets.bottom;
19771
19772            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
19773            measuredHeight += optical ? opticalHeight : -opticalHeight;
19774        }
19775        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
19776    }
19777
19778    /**
19779     * Sets the measured dimension without extra processing for things like optical bounds.
19780     * Useful for reapplying consistent values that have already been cooked with adjustments
19781     * for optical bounds, etc. such as those from the measurement cache.
19782     *
19783     * @param measuredWidth The measured width of this view.  May be a complex
19784     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19785     * {@link #MEASURED_STATE_TOO_SMALL}.
19786     * @param measuredHeight The measured height of this view.  May be a complex
19787     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19788     * {@link #MEASURED_STATE_TOO_SMALL}.
19789     */
19790    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
19791        mMeasuredWidth = measuredWidth;
19792        mMeasuredHeight = measuredHeight;
19793
19794        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
19795    }
19796
19797    /**
19798     * Merge two states as returned by {@link #getMeasuredState()}.
19799     * @param curState The current state as returned from a view or the result
19800     * of combining multiple views.
19801     * @param newState The new view state to combine.
19802     * @return Returns a new integer reflecting the combination of the two
19803     * states.
19804     */
19805    public static int combineMeasuredStates(int curState, int newState) {
19806        return curState | newState;
19807    }
19808
19809    /**
19810     * Version of {@link #resolveSizeAndState(int, int, int)}
19811     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
19812     */
19813    public static int resolveSize(int size, int measureSpec) {
19814        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
19815    }
19816
19817    /**
19818     * Utility to reconcile a desired size and state, with constraints imposed
19819     * by a MeasureSpec. Will take the desired size, unless a different size
19820     * is imposed by the constraints. The returned value is a compound integer,
19821     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
19822     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
19823     * resulting size is smaller than the size the view wants to be.
19824     *
19825     * @param size How big the view wants to be.
19826     * @param measureSpec Constraints imposed by the parent.
19827     * @param childMeasuredState Size information bit mask for the view's
19828     *                           children.
19829     * @return Size information bit mask as defined by
19830     *         {@link #MEASURED_SIZE_MASK} and
19831     *         {@link #MEASURED_STATE_TOO_SMALL}.
19832     */
19833    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
19834        final int specMode = MeasureSpec.getMode(measureSpec);
19835        final int specSize = MeasureSpec.getSize(measureSpec);
19836        final int result;
19837        switch (specMode) {
19838            case MeasureSpec.AT_MOST:
19839                if (specSize < size) {
19840                    result = specSize | MEASURED_STATE_TOO_SMALL;
19841                } else {
19842                    result = size;
19843                }
19844                break;
19845            case MeasureSpec.EXACTLY:
19846                result = specSize;
19847                break;
19848            case MeasureSpec.UNSPECIFIED:
19849            default:
19850                result = size;
19851        }
19852        return result | (childMeasuredState & MEASURED_STATE_MASK);
19853    }
19854
19855    /**
19856     * Utility to return a default size. Uses the supplied size if the
19857     * MeasureSpec imposed no constraints. Will get larger if allowed
19858     * by the MeasureSpec.
19859     *
19860     * @param size Default size for this view
19861     * @param measureSpec Constraints imposed by the parent
19862     * @return The size this view should be.
19863     */
19864    public static int getDefaultSize(int size, int measureSpec) {
19865        int result = size;
19866        int specMode = MeasureSpec.getMode(measureSpec);
19867        int specSize = MeasureSpec.getSize(measureSpec);
19868
19869        switch (specMode) {
19870        case MeasureSpec.UNSPECIFIED:
19871            result = size;
19872            break;
19873        case MeasureSpec.AT_MOST:
19874        case MeasureSpec.EXACTLY:
19875            result = specSize;
19876            break;
19877        }
19878        return result;
19879    }
19880
19881    /**
19882     * Returns the suggested minimum height that the view should use. This
19883     * returns the maximum of the view's minimum height
19884     * and the background's minimum height
19885     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
19886     * <p>
19887     * When being used in {@link #onMeasure(int, int)}, the caller should still
19888     * ensure the returned height is within the requirements of the parent.
19889     *
19890     * @return The suggested minimum height of the view.
19891     */
19892    protected int getSuggestedMinimumHeight() {
19893        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
19894
19895    }
19896
19897    /**
19898     * Returns the suggested minimum width that the view should use. This
19899     * returns the maximum of the view's minimum width
19900     * and the background's minimum width
19901     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
19902     * <p>
19903     * When being used in {@link #onMeasure(int, int)}, the caller should still
19904     * ensure the returned width is within the requirements of the parent.
19905     *
19906     * @return The suggested minimum width of the view.
19907     */
19908    protected int getSuggestedMinimumWidth() {
19909        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
19910    }
19911
19912    /**
19913     * Returns the minimum height of the view.
19914     *
19915     * @return the minimum height the view will try to be.
19916     *
19917     * @see #setMinimumHeight(int)
19918     *
19919     * @attr ref android.R.styleable#View_minHeight
19920     */
19921    public int getMinimumHeight() {
19922        return mMinHeight;
19923    }
19924
19925    /**
19926     * Sets the minimum height of the view. It is not guaranteed the view will
19927     * be able to achieve this minimum height (for example, if its parent layout
19928     * constrains it with less available height).
19929     *
19930     * @param minHeight The minimum height the view will try to be.
19931     *
19932     * @see #getMinimumHeight()
19933     *
19934     * @attr ref android.R.styleable#View_minHeight
19935     */
19936    @RemotableViewMethod
19937    public void setMinimumHeight(int minHeight) {
19938        mMinHeight = minHeight;
19939        requestLayout();
19940    }
19941
19942    /**
19943     * Returns the minimum width of the view.
19944     *
19945     * @return the minimum width the view will try to be.
19946     *
19947     * @see #setMinimumWidth(int)
19948     *
19949     * @attr ref android.R.styleable#View_minWidth
19950     */
19951    public int getMinimumWidth() {
19952        return mMinWidth;
19953    }
19954
19955    /**
19956     * Sets the minimum width of the view. It is not guaranteed the view will
19957     * be able to achieve this minimum width (for example, if its parent layout
19958     * constrains it with less available width).
19959     *
19960     * @param minWidth The minimum width the view will try to be.
19961     *
19962     * @see #getMinimumWidth()
19963     *
19964     * @attr ref android.R.styleable#View_minWidth
19965     */
19966    public void setMinimumWidth(int minWidth) {
19967        mMinWidth = minWidth;
19968        requestLayout();
19969
19970    }
19971
19972    /**
19973     * Get the animation currently associated with this view.
19974     *
19975     * @return The animation that is currently playing or
19976     *         scheduled to play for this view.
19977     */
19978    public Animation getAnimation() {
19979        return mCurrentAnimation;
19980    }
19981
19982    /**
19983     * Start the specified animation now.
19984     *
19985     * @param animation the animation to start now
19986     */
19987    public void startAnimation(Animation animation) {
19988        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
19989        setAnimation(animation);
19990        invalidateParentCaches();
19991        invalidate(true);
19992    }
19993
19994    /**
19995     * Cancels any animations for this view.
19996     */
19997    public void clearAnimation() {
19998        if (mCurrentAnimation != null) {
19999            mCurrentAnimation.detach();
20000        }
20001        mCurrentAnimation = null;
20002        invalidateParentIfNeeded();
20003    }
20004
20005    /**
20006     * Sets the next animation to play for this view.
20007     * If you want the animation to play immediately, use
20008     * {@link #startAnimation(android.view.animation.Animation)} instead.
20009     * This method provides allows fine-grained
20010     * control over the start time and invalidation, but you
20011     * must make sure that 1) the animation has a start time set, and
20012     * 2) the view's parent (which controls animations on its children)
20013     * will be invalidated when the animation is supposed to
20014     * start.
20015     *
20016     * @param animation The next animation, or null.
20017     */
20018    public void setAnimation(Animation animation) {
20019        mCurrentAnimation = animation;
20020
20021        if (animation != null) {
20022            // If the screen is off assume the animation start time is now instead of
20023            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20024            // would cause the animation to start when the screen turns back on
20025            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20026                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20027                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20028            }
20029            animation.reset();
20030        }
20031    }
20032
20033    /**
20034     * Invoked by a parent ViewGroup to notify the start of the animation
20035     * currently associated with this view. If you override this method,
20036     * always call super.onAnimationStart();
20037     *
20038     * @see #setAnimation(android.view.animation.Animation)
20039     * @see #getAnimation()
20040     */
20041    @CallSuper
20042    protected void onAnimationStart() {
20043        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20044    }
20045
20046    /**
20047     * Invoked by a parent ViewGroup to notify the end of the animation
20048     * currently associated with this view. If you override this method,
20049     * always call super.onAnimationEnd();
20050     *
20051     * @see #setAnimation(android.view.animation.Animation)
20052     * @see #getAnimation()
20053     */
20054    @CallSuper
20055    protected void onAnimationEnd() {
20056        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20057    }
20058
20059    /**
20060     * Invoked if there is a Transform that involves alpha. Subclass that can
20061     * draw themselves with the specified alpha should return true, and then
20062     * respect that alpha when their onDraw() is called. If this returns false
20063     * then the view may be redirected to draw into an offscreen buffer to
20064     * fulfill the request, which will look fine, but may be slower than if the
20065     * subclass handles it internally. The default implementation returns false.
20066     *
20067     * @param alpha The alpha (0..255) to apply to the view's drawing
20068     * @return true if the view can draw with the specified alpha.
20069     */
20070    protected boolean onSetAlpha(int alpha) {
20071        return false;
20072    }
20073
20074    /**
20075     * This is used by the RootView to perform an optimization when
20076     * the view hierarchy contains one or several SurfaceView.
20077     * SurfaceView is always considered transparent, but its children are not,
20078     * therefore all View objects remove themselves from the global transparent
20079     * region (passed as a parameter to this function).
20080     *
20081     * @param region The transparent region for this ViewAncestor (window).
20082     *
20083     * @return Returns true if the effective visibility of the view at this
20084     * point is opaque, regardless of the transparent region; returns false
20085     * if it is possible for underlying windows to be seen behind the view.
20086     *
20087     * {@hide}
20088     */
20089    public boolean gatherTransparentRegion(Region region) {
20090        final AttachInfo attachInfo = mAttachInfo;
20091        if (region != null && attachInfo != null) {
20092            final int pflags = mPrivateFlags;
20093            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20094                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20095                // remove it from the transparent region.
20096                final int[] location = attachInfo.mTransparentLocation;
20097                getLocationInWindow(location);
20098                region.op(location[0], location[1], location[0] + mRight - mLeft,
20099                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
20100            } else {
20101                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20102                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20103                    // the background drawable's non-transparent parts from this transparent region.
20104                    applyDrawableToTransparentRegion(mBackground, region);
20105                }
20106                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20107                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20108                    // Similarly, we remove the foreground drawable's non-transparent parts.
20109                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20110                }
20111            }
20112        }
20113        return true;
20114    }
20115
20116    /**
20117     * Play a sound effect for this view.
20118     *
20119     * <p>The framework will play sound effects for some built in actions, such as
20120     * clicking, but you may wish to play these effects in your widget,
20121     * for instance, for internal navigation.
20122     *
20123     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20124     * {@link #isSoundEffectsEnabled()} is true.
20125     *
20126     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20127     */
20128    public void playSoundEffect(int soundConstant) {
20129        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20130            return;
20131        }
20132        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20133    }
20134
20135    /**
20136     * BZZZTT!!1!
20137     *
20138     * <p>Provide haptic feedback to the user for this view.
20139     *
20140     * <p>The framework will provide haptic feedback for some built in actions,
20141     * such as long presses, but you may wish to provide feedback for your
20142     * own widget.
20143     *
20144     * <p>The feedback will only be performed if
20145     * {@link #isHapticFeedbackEnabled()} is true.
20146     *
20147     * @param feedbackConstant One of the constants defined in
20148     * {@link HapticFeedbackConstants}
20149     */
20150    public boolean performHapticFeedback(int feedbackConstant) {
20151        return performHapticFeedback(feedbackConstant, 0);
20152    }
20153
20154    /**
20155     * BZZZTT!!1!
20156     *
20157     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20158     *
20159     * @param feedbackConstant One of the constants defined in
20160     * {@link HapticFeedbackConstants}
20161     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20162     */
20163    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20164        if (mAttachInfo == null) {
20165            return false;
20166        }
20167        //noinspection SimplifiableIfStatement
20168        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20169                && !isHapticFeedbackEnabled()) {
20170            return false;
20171        }
20172        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20173                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20174    }
20175
20176    /**
20177     * Request that the visibility of the status bar or other screen/window
20178     * decorations be changed.
20179     *
20180     * <p>This method is used to put the over device UI into temporary modes
20181     * where the user's attention is focused more on the application content,
20182     * by dimming or hiding surrounding system affordances.  This is typically
20183     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20184     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20185     * to be placed behind the action bar (and with these flags other system
20186     * affordances) so that smooth transitions between hiding and showing them
20187     * can be done.
20188     *
20189     * <p>Two representative examples of the use of system UI visibility is
20190     * implementing a content browsing application (like a magazine reader)
20191     * and a video playing application.
20192     *
20193     * <p>The first code shows a typical implementation of a View in a content
20194     * browsing application.  In this implementation, the application goes
20195     * into a content-oriented mode by hiding the status bar and action bar,
20196     * and putting the navigation elements into lights out mode.  The user can
20197     * then interact with content while in this mode.  Such an application should
20198     * provide an easy way for the user to toggle out of the mode (such as to
20199     * check information in the status bar or access notifications).  In the
20200     * implementation here, this is done simply by tapping on the content.
20201     *
20202     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20203     *      content}
20204     *
20205     * <p>This second code sample shows a typical implementation of a View
20206     * in a video playing application.  In this situation, while the video is
20207     * playing the application would like to go into a complete full-screen mode,
20208     * to use as much of the display as possible for the video.  When in this state
20209     * the user can not interact with the application; the system intercepts
20210     * touching on the screen to pop the UI out of full screen mode.  See
20211     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20212     *
20213     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20214     *      content}
20215     *
20216     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20217     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20218     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20219     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20220     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20221     */
20222    public void setSystemUiVisibility(int visibility) {
20223        if (visibility != mSystemUiVisibility) {
20224            mSystemUiVisibility = visibility;
20225            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20226                mParent.recomputeViewAttributes(this);
20227            }
20228        }
20229    }
20230
20231    /**
20232     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20233     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20234     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20235     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20236     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20237     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20238     */
20239    public int getSystemUiVisibility() {
20240        return mSystemUiVisibility;
20241    }
20242
20243    /**
20244     * Returns the current system UI visibility that is currently set for
20245     * the entire window.  This is the combination of the
20246     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20247     * views in the window.
20248     */
20249    public int getWindowSystemUiVisibility() {
20250        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20251    }
20252
20253    /**
20254     * Override to find out when the window's requested system UI visibility
20255     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20256     * This is different from the callbacks received through
20257     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20258     * in that this is only telling you about the local request of the window,
20259     * not the actual values applied by the system.
20260     */
20261    public void onWindowSystemUiVisibilityChanged(int visible) {
20262    }
20263
20264    /**
20265     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20266     * the view hierarchy.
20267     */
20268    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20269        onWindowSystemUiVisibilityChanged(visible);
20270    }
20271
20272    /**
20273     * Set a listener to receive callbacks when the visibility of the system bar changes.
20274     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20275     */
20276    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20277        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20278        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20279            mParent.recomputeViewAttributes(this);
20280        }
20281    }
20282
20283    /**
20284     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20285     * the view hierarchy.
20286     */
20287    public void dispatchSystemUiVisibilityChanged(int visibility) {
20288        ListenerInfo li = mListenerInfo;
20289        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20290            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20291                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20292        }
20293    }
20294
20295    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20296        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20297        if (val != mSystemUiVisibility) {
20298            setSystemUiVisibility(val);
20299            return true;
20300        }
20301        return false;
20302    }
20303
20304    /** @hide */
20305    public void setDisabledSystemUiVisibility(int flags) {
20306        if (mAttachInfo != null) {
20307            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20308                mAttachInfo.mDisabledSystemUiVisibility = flags;
20309                if (mParent != null) {
20310                    mParent.recomputeViewAttributes(this);
20311                }
20312            }
20313        }
20314    }
20315
20316    /**
20317     * Creates an image that the system displays during the drag and drop
20318     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20319     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20320     * appearance as the given View. The default also positions the center of the drag shadow
20321     * directly under the touch point. If no View is provided (the constructor with no parameters
20322     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20323     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20324     * default is an invisible drag shadow.
20325     * <p>
20326     * You are not required to use the View you provide to the constructor as the basis of the
20327     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20328     * anything you want as the drag shadow.
20329     * </p>
20330     * <p>
20331     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20332     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20333     *  size and position of the drag shadow. It uses this data to construct a
20334     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20335     *  so that your application can draw the shadow image in the Canvas.
20336     * </p>
20337     *
20338     * <div class="special reference">
20339     * <h3>Developer Guides</h3>
20340     * <p>For a guide to implementing drag and drop features, read the
20341     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20342     * </div>
20343     */
20344    public static class DragShadowBuilder {
20345        private final WeakReference<View> mView;
20346
20347        /**
20348         * Constructs a shadow image builder based on a View. By default, the resulting drag
20349         * shadow will have the same appearance and dimensions as the View, with the touch point
20350         * over the center of the View.
20351         * @param view A View. Any View in scope can be used.
20352         */
20353        public DragShadowBuilder(View view) {
20354            mView = new WeakReference<View>(view);
20355        }
20356
20357        /**
20358         * Construct a shadow builder object with no associated View.  This
20359         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20360         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20361         * to supply the drag shadow's dimensions and appearance without
20362         * reference to any View object. If they are not overridden, then the result is an
20363         * invisible drag shadow.
20364         */
20365        public DragShadowBuilder() {
20366            mView = new WeakReference<View>(null);
20367        }
20368
20369        /**
20370         * Returns the View object that had been passed to the
20371         * {@link #View.DragShadowBuilder(View)}
20372         * constructor.  If that View parameter was {@code null} or if the
20373         * {@link #View.DragShadowBuilder()}
20374         * constructor was used to instantiate the builder object, this method will return
20375         * null.
20376         *
20377         * @return The View object associate with this builder object.
20378         */
20379        @SuppressWarnings({"JavadocReference"})
20380        final public View getView() {
20381            return mView.get();
20382        }
20383
20384        /**
20385         * Provides the metrics for the shadow image. These include the dimensions of
20386         * the shadow image, and the point within that shadow that should
20387         * be centered under the touch location while dragging.
20388         * <p>
20389         * The default implementation sets the dimensions of the shadow to be the
20390         * same as the dimensions of the View itself and centers the shadow under
20391         * the touch point.
20392         * </p>
20393         *
20394         * @param shadowSize A {@link android.graphics.Point} containing the width and height
20395         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
20396         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
20397         * image.
20398         *
20399         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
20400         * shadow image that should be underneath the touch point during the drag and drop
20401         * operation. Your application must set {@link android.graphics.Point#x} to the
20402         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
20403         */
20404        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
20405            final View view = mView.get();
20406            if (view != null) {
20407                shadowSize.set(view.getWidth(), view.getHeight());
20408                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
20409            } else {
20410                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
20411            }
20412        }
20413
20414        /**
20415         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
20416         * based on the dimensions it received from the
20417         * {@link #onProvideShadowMetrics(Point, Point)} callback.
20418         *
20419         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
20420         */
20421        public void onDrawShadow(Canvas canvas) {
20422            final View view = mView.get();
20423            if (view != null) {
20424                view.draw(canvas);
20425            } else {
20426                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
20427            }
20428        }
20429    }
20430
20431    /**
20432     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
20433     * startDragAndDrop()} for newer platform versions.
20434     */
20435    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
20436                                   Object myLocalState, int flags) {
20437        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
20438    }
20439
20440    /**
20441     * Starts a drag and drop operation. When your application calls this method, it passes a
20442     * {@link android.view.View.DragShadowBuilder} object to the system. The
20443     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
20444     * to get metrics for the drag shadow, and then calls the object's
20445     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
20446     * <p>
20447     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
20448     *  drag events to all the View objects in your application that are currently visible. It does
20449     *  this either by calling the View object's drag listener (an implementation of
20450     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
20451     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
20452     *  Both are passed a {@link android.view.DragEvent} object that has a
20453     *  {@link android.view.DragEvent#getAction()} value of
20454     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
20455     * </p>
20456     * <p>
20457     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
20458     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
20459     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
20460     * to the View the user selected for dragging.
20461     * </p>
20462     * @param data A {@link android.content.ClipData} object pointing to the data to be
20463     * transferred by the drag and drop operation.
20464     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20465     * drag shadow.
20466     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
20467     * drop operation. This Object is put into every DragEvent object sent by the system during the
20468     * current drag.
20469     * <p>
20470     * myLocalState is a lightweight mechanism for the sending information from the dragged View
20471     * to the target Views. For example, it can contain flags that differentiate between a
20472     * a copy operation and a move operation.
20473     * </p>
20474     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
20475     * so the parameter should be set to 0.
20476     * @return {@code true} if the method completes successfully, or
20477     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
20478     * do a drag, and so no drag operation is in progress.
20479     */
20480    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
20481            Object myLocalState, int flags) {
20482        if (ViewDebug.DEBUG_DRAG) {
20483            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
20484        }
20485        boolean okay = false;
20486
20487        Point shadowSize = new Point();
20488        Point shadowTouchPoint = new Point();
20489        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
20490
20491        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
20492                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
20493            throw new IllegalStateException("Drag shadow dimensions must not be negative");
20494        }
20495
20496        if (ViewDebug.DEBUG_DRAG) {
20497            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
20498                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
20499        }
20500        if (mAttachInfo.mDragSurface != null) {
20501            mAttachInfo.mDragSurface.release();
20502        }
20503        mAttachInfo.mDragSurface = new Surface();
20504        try {
20505            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
20506                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
20507            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
20508                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
20509            if (mAttachInfo.mDragToken != null) {
20510                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20511                try {
20512                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20513                    shadowBuilder.onDrawShadow(canvas);
20514                } finally {
20515                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20516                }
20517
20518                final ViewRootImpl root = getViewRootImpl();
20519
20520                // Cache the local state object for delivery with DragEvents
20521                root.setLocalDragState(myLocalState);
20522
20523                // repurpose 'shadowSize' for the last touch point
20524                root.getLastTouchPoint(shadowSize);
20525
20526                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
20527                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
20528                        shadowTouchPoint.x, shadowTouchPoint.y, data);
20529                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
20530            }
20531        } catch (Exception e) {
20532            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
20533            mAttachInfo.mDragSurface.destroy();
20534            mAttachInfo.mDragSurface = null;
20535        }
20536
20537        return okay;
20538    }
20539
20540    /**
20541     * Cancels an ongoing drag and drop operation.
20542     * <p>
20543     * A {@link android.view.DragEvent} object with
20544     * {@link android.view.DragEvent#getAction()} value of
20545     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
20546     * {@link android.view.DragEvent#getResult()} value of {@code false}
20547     * will be sent to every
20548     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
20549     * even if they are not currently visible.
20550     * </p>
20551     * <p>
20552     * This method can be called on any View in the same window as the View on which
20553     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
20554     * was called.
20555     * </p>
20556     */
20557    public final void cancelDragAndDrop() {
20558        if (ViewDebug.DEBUG_DRAG) {
20559            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
20560        }
20561        if (mAttachInfo.mDragToken != null) {
20562            try {
20563                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
20564            } catch (Exception e) {
20565                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
20566            }
20567            mAttachInfo.mDragToken = null;
20568        } else {
20569            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
20570        }
20571    }
20572
20573    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
20574        if (ViewDebug.DEBUG_DRAG) {
20575            Log.d(VIEW_LOG_TAG, "updateDragShadow");
20576        }
20577        if (mAttachInfo.mDragToken != null) {
20578            try {
20579                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20580                try {
20581                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20582                    shadowBuilder.onDrawShadow(canvas);
20583                } finally {
20584                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20585                }
20586            } catch (Exception e) {
20587                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
20588            }
20589        } else {
20590            Log.e(VIEW_LOG_TAG, "No active drag");
20591        }
20592    }
20593
20594    /**
20595     * Starts a move from {startX, startY}, the amount of the movement will be the offset
20596     * between {startX, startY} and the new cursor positon.
20597     * @param startX horizontal coordinate where the move started.
20598     * @param startY vertical coordinate where the move started.
20599     * @return whether moving was started successfully.
20600     * @hide
20601     */
20602    public final boolean startMovingTask(float startX, float startY) {
20603        if (ViewDebug.DEBUG_POSITIONING) {
20604            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
20605        }
20606        try {
20607            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
20608        } catch (RemoteException e) {
20609            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
20610        }
20611        return false;
20612    }
20613
20614    /**
20615     * Handles drag events sent by the system following a call to
20616     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
20617     * startDragAndDrop()}.
20618     *<p>
20619     * When the system calls this method, it passes a
20620     * {@link android.view.DragEvent} object. A call to
20621     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
20622     * in DragEvent. The method uses these to determine what is happening in the drag and drop
20623     * operation.
20624     * @param event The {@link android.view.DragEvent} sent by the system.
20625     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
20626     * in DragEvent, indicating the type of drag event represented by this object.
20627     * @return {@code true} if the method was successful, otherwise {@code false}.
20628     * <p>
20629     *  The method should return {@code true} in response to an action type of
20630     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
20631     *  operation.
20632     * </p>
20633     * <p>
20634     *  The method should also return {@code true} in response to an action type of
20635     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
20636     *  {@code false} if it didn't.
20637     * </p>
20638     */
20639    public boolean onDragEvent(DragEvent event) {
20640        return false;
20641    }
20642
20643    /**
20644     * Detects if this View is enabled and has a drag event listener.
20645     * If both are true, then it calls the drag event listener with the
20646     * {@link android.view.DragEvent} it received. If the drag event listener returns
20647     * {@code true}, then dispatchDragEvent() returns {@code true}.
20648     * <p>
20649     * For all other cases, the method calls the
20650     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
20651     * method and returns its result.
20652     * </p>
20653     * <p>
20654     * This ensures that a drag event is always consumed, even if the View does not have a drag
20655     * event listener. However, if the View has a listener and the listener returns true, then
20656     * onDragEvent() is not called.
20657     * </p>
20658     */
20659    public boolean dispatchDragEvent(DragEvent event) {
20660        ListenerInfo li = mListenerInfo;
20661        //noinspection SimplifiableIfStatement
20662        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
20663                && li.mOnDragListener.onDrag(this, event)) {
20664            return true;
20665        }
20666        return onDragEvent(event);
20667    }
20668
20669    boolean canAcceptDrag() {
20670        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
20671    }
20672
20673    /**
20674     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
20675     * it is ever exposed at all.
20676     * @hide
20677     */
20678    public void onCloseSystemDialogs(String reason) {
20679    }
20680
20681    /**
20682     * Given a Drawable whose bounds have been set to draw into this view,
20683     * update a Region being computed for
20684     * {@link #gatherTransparentRegion(android.graphics.Region)} so
20685     * that any non-transparent parts of the Drawable are removed from the
20686     * given transparent region.
20687     *
20688     * @param dr The Drawable whose transparency is to be applied to the region.
20689     * @param region A Region holding the current transparency information,
20690     * where any parts of the region that are set are considered to be
20691     * transparent.  On return, this region will be modified to have the
20692     * transparency information reduced by the corresponding parts of the
20693     * Drawable that are not transparent.
20694     * {@hide}
20695     */
20696    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
20697        if (DBG) {
20698            Log.i("View", "Getting transparent region for: " + this);
20699        }
20700        final Region r = dr.getTransparentRegion();
20701        final Rect db = dr.getBounds();
20702        final AttachInfo attachInfo = mAttachInfo;
20703        if (r != null && attachInfo != null) {
20704            final int w = getRight()-getLeft();
20705            final int h = getBottom()-getTop();
20706            if (db.left > 0) {
20707                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
20708                r.op(0, 0, db.left, h, Region.Op.UNION);
20709            }
20710            if (db.right < w) {
20711                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
20712                r.op(db.right, 0, w, h, Region.Op.UNION);
20713            }
20714            if (db.top > 0) {
20715                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
20716                r.op(0, 0, w, db.top, Region.Op.UNION);
20717            }
20718            if (db.bottom < h) {
20719                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
20720                r.op(0, db.bottom, w, h, Region.Op.UNION);
20721            }
20722            final int[] location = attachInfo.mTransparentLocation;
20723            getLocationInWindow(location);
20724            r.translate(location[0], location[1]);
20725            region.op(r, Region.Op.INTERSECT);
20726        } else {
20727            region.op(db, Region.Op.DIFFERENCE);
20728        }
20729    }
20730
20731    private void checkForLongClick(int delayOffset, float x, float y) {
20732        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
20733            mHasPerformedLongPress = false;
20734
20735            if (mPendingCheckForLongPress == null) {
20736                mPendingCheckForLongPress = new CheckForLongPress();
20737            }
20738            mPendingCheckForLongPress.setAnchor(x, y);
20739            mPendingCheckForLongPress.rememberWindowAttachCount();
20740            postDelayed(mPendingCheckForLongPress,
20741                    ViewConfiguration.getLongPressTimeout() - delayOffset);
20742        }
20743    }
20744
20745    /**
20746     * Inflate a view from an XML resource.  This convenience method wraps the {@link
20747     * LayoutInflater} class, which provides a full range of options for view inflation.
20748     *
20749     * @param context The Context object for your activity or application.
20750     * @param resource The resource ID to inflate
20751     * @param root A view group that will be the parent.  Used to properly inflate the
20752     * layout_* parameters.
20753     * @see LayoutInflater
20754     */
20755    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
20756        LayoutInflater factory = LayoutInflater.from(context);
20757        return factory.inflate(resource, root);
20758    }
20759
20760    /**
20761     * Scroll the view with standard behavior for scrolling beyond the normal
20762     * content boundaries. Views that call this method should override
20763     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
20764     * results of an over-scroll operation.
20765     *
20766     * Views can use this method to handle any touch or fling-based scrolling.
20767     *
20768     * @param deltaX Change in X in pixels
20769     * @param deltaY Change in Y in pixels
20770     * @param scrollX Current X scroll value in pixels before applying deltaX
20771     * @param scrollY Current Y scroll value in pixels before applying deltaY
20772     * @param scrollRangeX Maximum content scroll range along the X axis
20773     * @param scrollRangeY Maximum content scroll range along the Y axis
20774     * @param maxOverScrollX Number of pixels to overscroll by in either direction
20775     *          along the X axis.
20776     * @param maxOverScrollY Number of pixels to overscroll by in either direction
20777     *          along the Y axis.
20778     * @param isTouchEvent true if this scroll operation is the result of a touch event.
20779     * @return true if scrolling was clamped to an over-scroll boundary along either
20780     *          axis, false otherwise.
20781     */
20782    @SuppressWarnings({"UnusedParameters"})
20783    protected boolean overScrollBy(int deltaX, int deltaY,
20784            int scrollX, int scrollY,
20785            int scrollRangeX, int scrollRangeY,
20786            int maxOverScrollX, int maxOverScrollY,
20787            boolean isTouchEvent) {
20788        final int overScrollMode = mOverScrollMode;
20789        final boolean canScrollHorizontal =
20790                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
20791        final boolean canScrollVertical =
20792                computeVerticalScrollRange() > computeVerticalScrollExtent();
20793        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
20794                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
20795        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
20796                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
20797
20798        int newScrollX = scrollX + deltaX;
20799        if (!overScrollHorizontal) {
20800            maxOverScrollX = 0;
20801        }
20802
20803        int newScrollY = scrollY + deltaY;
20804        if (!overScrollVertical) {
20805            maxOverScrollY = 0;
20806        }
20807
20808        // Clamp values if at the limits and record
20809        final int left = -maxOverScrollX;
20810        final int right = maxOverScrollX + scrollRangeX;
20811        final int top = -maxOverScrollY;
20812        final int bottom = maxOverScrollY + scrollRangeY;
20813
20814        boolean clampedX = false;
20815        if (newScrollX > right) {
20816            newScrollX = right;
20817            clampedX = true;
20818        } else if (newScrollX < left) {
20819            newScrollX = left;
20820            clampedX = true;
20821        }
20822
20823        boolean clampedY = false;
20824        if (newScrollY > bottom) {
20825            newScrollY = bottom;
20826            clampedY = true;
20827        } else if (newScrollY < top) {
20828            newScrollY = top;
20829            clampedY = true;
20830        }
20831
20832        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
20833
20834        return clampedX || clampedY;
20835    }
20836
20837    /**
20838     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
20839     * respond to the results of an over-scroll operation.
20840     *
20841     * @param scrollX New X scroll value in pixels
20842     * @param scrollY New Y scroll value in pixels
20843     * @param clampedX True if scrollX was clamped to an over-scroll boundary
20844     * @param clampedY True if scrollY was clamped to an over-scroll boundary
20845     */
20846    protected void onOverScrolled(int scrollX, int scrollY,
20847            boolean clampedX, boolean clampedY) {
20848        // Intentionally empty.
20849    }
20850
20851    /**
20852     * Returns the over-scroll mode for this view. The result will be
20853     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20854     * (allow over-scrolling only if the view content is larger than the container),
20855     * or {@link #OVER_SCROLL_NEVER}.
20856     *
20857     * @return This view's over-scroll mode.
20858     */
20859    public int getOverScrollMode() {
20860        return mOverScrollMode;
20861    }
20862
20863    /**
20864     * Set the over-scroll mode for this view. Valid over-scroll modes are
20865     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20866     * (allow over-scrolling only if the view content is larger than the container),
20867     * or {@link #OVER_SCROLL_NEVER}.
20868     *
20869     * Setting the over-scroll mode of a view will have an effect only if the
20870     * view is capable of scrolling.
20871     *
20872     * @param overScrollMode The new over-scroll mode for this view.
20873     */
20874    public void setOverScrollMode(int overScrollMode) {
20875        if (overScrollMode != OVER_SCROLL_ALWAYS &&
20876                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
20877                overScrollMode != OVER_SCROLL_NEVER) {
20878            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
20879        }
20880        mOverScrollMode = overScrollMode;
20881    }
20882
20883    /**
20884     * Enable or disable nested scrolling for this view.
20885     *
20886     * <p>If this property is set to true the view will be permitted to initiate nested
20887     * scrolling operations with a compatible parent view in the current hierarchy. If this
20888     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
20889     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
20890     * the nested scroll.</p>
20891     *
20892     * @param enabled true to enable nested scrolling, false to disable
20893     *
20894     * @see #isNestedScrollingEnabled()
20895     */
20896    public void setNestedScrollingEnabled(boolean enabled) {
20897        if (enabled) {
20898            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
20899        } else {
20900            stopNestedScroll();
20901            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
20902        }
20903    }
20904
20905    /**
20906     * Returns true if nested scrolling is enabled for this view.
20907     *
20908     * <p>If nested scrolling is enabled and this View class implementation supports it,
20909     * this view will act as a nested scrolling child view when applicable, forwarding data
20910     * about the scroll operation in progress to a compatible and cooperating nested scrolling
20911     * parent.</p>
20912     *
20913     * @return true if nested scrolling is enabled
20914     *
20915     * @see #setNestedScrollingEnabled(boolean)
20916     */
20917    public boolean isNestedScrollingEnabled() {
20918        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
20919                PFLAG3_NESTED_SCROLLING_ENABLED;
20920    }
20921
20922    /**
20923     * Begin a nestable scroll operation along the given axes.
20924     *
20925     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
20926     *
20927     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
20928     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
20929     * In the case of touch scrolling the nested scroll will be terminated automatically in
20930     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
20931     * In the event of programmatic scrolling the caller must explicitly call
20932     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
20933     *
20934     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
20935     * If it returns false the caller may ignore the rest of this contract until the next scroll.
20936     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
20937     *
20938     * <p>At each incremental step of the scroll the caller should invoke
20939     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
20940     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
20941     * parent at least partially consumed the scroll and the caller should adjust the amount it
20942     * scrolls by.</p>
20943     *
20944     * <p>After applying the remainder of the scroll delta the caller should invoke
20945     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
20946     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
20947     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
20948     * </p>
20949     *
20950     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
20951     *             {@link #SCROLL_AXIS_VERTICAL}.
20952     * @return true if a cooperative parent was found and nested scrolling has been enabled for
20953     *         the current gesture.
20954     *
20955     * @see #stopNestedScroll()
20956     * @see #dispatchNestedPreScroll(int, int, int[], int[])
20957     * @see #dispatchNestedScroll(int, int, int, int, int[])
20958     */
20959    public boolean startNestedScroll(int axes) {
20960        if (hasNestedScrollingParent()) {
20961            // Already in progress
20962            return true;
20963        }
20964        if (isNestedScrollingEnabled()) {
20965            ViewParent p = getParent();
20966            View child = this;
20967            while (p != null) {
20968                try {
20969                    if (p.onStartNestedScroll(child, this, axes)) {
20970                        mNestedScrollingParent = p;
20971                        p.onNestedScrollAccepted(child, this, axes);
20972                        return true;
20973                    }
20974                } catch (AbstractMethodError e) {
20975                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
20976                            "method onStartNestedScroll", e);
20977                    // Allow the search upward to continue
20978                }
20979                if (p instanceof View) {
20980                    child = (View) p;
20981                }
20982                p = p.getParent();
20983            }
20984        }
20985        return false;
20986    }
20987
20988    /**
20989     * Stop a nested scroll in progress.
20990     *
20991     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
20992     *
20993     * @see #startNestedScroll(int)
20994     */
20995    public void stopNestedScroll() {
20996        if (mNestedScrollingParent != null) {
20997            mNestedScrollingParent.onStopNestedScroll(this);
20998            mNestedScrollingParent = null;
20999        }
21000    }
21001
21002    /**
21003     * Returns true if this view has a nested scrolling parent.
21004     *
21005     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21006     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21007     *
21008     * @return whether this view has a nested scrolling parent
21009     */
21010    public boolean hasNestedScrollingParent() {
21011        return mNestedScrollingParent != null;
21012    }
21013
21014    /**
21015     * Dispatch one step of a nested scroll in progress.
21016     *
21017     * <p>Implementations of views that support nested scrolling should call this to report
21018     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21019     * is not currently in progress or nested scrolling is not
21020     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21021     *
21022     * <p>Compatible View implementations should also call
21023     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21024     * consuming a component of the scroll event themselves.</p>
21025     *
21026     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21027     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21028     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21029     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21030     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21031     *                       in local view coordinates of this view from before this operation
21032     *                       to after it completes. View implementations may use this to adjust
21033     *                       expected input coordinate tracking.
21034     * @return true if the event was dispatched, false if it could not be dispatched.
21035     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21036     */
21037    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21038            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21039        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21040            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21041                int startX = 0;
21042                int startY = 0;
21043                if (offsetInWindow != null) {
21044                    getLocationInWindow(offsetInWindow);
21045                    startX = offsetInWindow[0];
21046                    startY = offsetInWindow[1];
21047                }
21048
21049                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21050                        dxUnconsumed, dyUnconsumed);
21051
21052                if (offsetInWindow != null) {
21053                    getLocationInWindow(offsetInWindow);
21054                    offsetInWindow[0] -= startX;
21055                    offsetInWindow[1] -= startY;
21056                }
21057                return true;
21058            } else if (offsetInWindow != null) {
21059                // No motion, no dispatch. Keep offsetInWindow up to date.
21060                offsetInWindow[0] = 0;
21061                offsetInWindow[1] = 0;
21062            }
21063        }
21064        return false;
21065    }
21066
21067    /**
21068     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21069     *
21070     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21071     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21072     * scrolling operation to consume some or all of the scroll operation before the child view
21073     * consumes it.</p>
21074     *
21075     * @param dx Horizontal scroll distance in pixels
21076     * @param dy Vertical scroll distance in pixels
21077     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21078     *                 and consumed[1] the consumed dy.
21079     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21080     *                       in local view coordinates of this view from before this operation
21081     *                       to after it completes. View implementations may use this to adjust
21082     *                       expected input coordinate tracking.
21083     * @return true if the parent consumed some or all of the scroll delta
21084     * @see #dispatchNestedScroll(int, int, int, int, int[])
21085     */
21086    public boolean dispatchNestedPreScroll(int dx, int dy,
21087            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21088        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21089            if (dx != 0 || dy != 0) {
21090                int startX = 0;
21091                int startY = 0;
21092                if (offsetInWindow != null) {
21093                    getLocationInWindow(offsetInWindow);
21094                    startX = offsetInWindow[0];
21095                    startY = offsetInWindow[1];
21096                }
21097
21098                if (consumed == null) {
21099                    if (mTempNestedScrollConsumed == null) {
21100                        mTempNestedScrollConsumed = new int[2];
21101                    }
21102                    consumed = mTempNestedScrollConsumed;
21103                }
21104                consumed[0] = 0;
21105                consumed[1] = 0;
21106                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21107
21108                if (offsetInWindow != null) {
21109                    getLocationInWindow(offsetInWindow);
21110                    offsetInWindow[0] -= startX;
21111                    offsetInWindow[1] -= startY;
21112                }
21113                return consumed[0] != 0 || consumed[1] != 0;
21114            } else if (offsetInWindow != null) {
21115                offsetInWindow[0] = 0;
21116                offsetInWindow[1] = 0;
21117            }
21118        }
21119        return false;
21120    }
21121
21122    /**
21123     * Dispatch a fling to a nested scrolling parent.
21124     *
21125     * <p>This method should be used to indicate that a nested scrolling child has detected
21126     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21127     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21128     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21129     * along a scrollable axis.</p>
21130     *
21131     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21132     * its own content, it can use this method to delegate the fling to its nested scrolling
21133     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21134     *
21135     * @param velocityX Horizontal fling velocity in pixels per second
21136     * @param velocityY Vertical fling velocity in pixels per second
21137     * @param consumed true if the child consumed the fling, false otherwise
21138     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21139     */
21140    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21141        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21142            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21143        }
21144        return false;
21145    }
21146
21147    /**
21148     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21149     *
21150     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21151     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21152     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21153     * before the child view consumes it. If this method returns <code>true</code>, a nested
21154     * parent view consumed the fling and this view should not scroll as a result.</p>
21155     *
21156     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21157     * the fling at a time. If a parent view consumed the fling this method will return false.
21158     * Custom view implementations should account for this in two ways:</p>
21159     *
21160     * <ul>
21161     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21162     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21163     *     position regardless.</li>
21164     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21165     *     even to settle back to a valid idle position.</li>
21166     * </ul>
21167     *
21168     * <p>Views should also not offer fling velocities to nested parent views along an axis
21169     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21170     * should not offer a horizontal fling velocity to its parents since scrolling along that
21171     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21172     *
21173     * @param velocityX Horizontal fling velocity in pixels per second
21174     * @param velocityY Vertical fling velocity in pixels per second
21175     * @return true if a nested scrolling parent consumed the fling
21176     */
21177    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21178        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21179            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21180        }
21181        return false;
21182    }
21183
21184    /**
21185     * Gets a scale factor that determines the distance the view should scroll
21186     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21187     * @return The vertical scroll scale factor.
21188     * @hide
21189     */
21190    protected float getVerticalScrollFactor() {
21191        if (mVerticalScrollFactor == 0) {
21192            TypedValue outValue = new TypedValue();
21193            if (!mContext.getTheme().resolveAttribute(
21194                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21195                throw new IllegalStateException(
21196                        "Expected theme to define listPreferredItemHeight.");
21197            }
21198            mVerticalScrollFactor = outValue.getDimension(
21199                    mContext.getResources().getDisplayMetrics());
21200        }
21201        return mVerticalScrollFactor;
21202    }
21203
21204    /**
21205     * Gets a scale factor that determines the distance the view should scroll
21206     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21207     * @return The horizontal scroll scale factor.
21208     * @hide
21209     */
21210    protected float getHorizontalScrollFactor() {
21211        // TODO: Should use something else.
21212        return getVerticalScrollFactor();
21213    }
21214
21215    /**
21216     * Return the value specifying the text direction or policy that was set with
21217     * {@link #setTextDirection(int)}.
21218     *
21219     * @return the defined text direction. It can be one of:
21220     *
21221     * {@link #TEXT_DIRECTION_INHERIT},
21222     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21223     * {@link #TEXT_DIRECTION_ANY_RTL},
21224     * {@link #TEXT_DIRECTION_LTR},
21225     * {@link #TEXT_DIRECTION_RTL},
21226     * {@link #TEXT_DIRECTION_LOCALE},
21227     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21228     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21229     *
21230     * @attr ref android.R.styleable#View_textDirection
21231     *
21232     * @hide
21233     */
21234    @ViewDebug.ExportedProperty(category = "text", mapping = {
21235            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21236            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21237            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21238            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21239            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21240            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21241            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21242            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21243    })
21244    public int getRawTextDirection() {
21245        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21246    }
21247
21248    /**
21249     * Set the text direction.
21250     *
21251     * @param textDirection the direction to set. Should be one of:
21252     *
21253     * {@link #TEXT_DIRECTION_INHERIT},
21254     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21255     * {@link #TEXT_DIRECTION_ANY_RTL},
21256     * {@link #TEXT_DIRECTION_LTR},
21257     * {@link #TEXT_DIRECTION_RTL},
21258     * {@link #TEXT_DIRECTION_LOCALE}
21259     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21260     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21261     *
21262     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21263     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21264     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21265     *
21266     * @attr ref android.R.styleable#View_textDirection
21267     */
21268    public void setTextDirection(int textDirection) {
21269        if (getRawTextDirection() != textDirection) {
21270            // Reset the current text direction and the resolved one
21271            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21272            resetResolvedTextDirection();
21273            // Set the new text direction
21274            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21275            // Do resolution
21276            resolveTextDirection();
21277            // Notify change
21278            onRtlPropertiesChanged(getLayoutDirection());
21279            // Refresh
21280            requestLayout();
21281            invalidate(true);
21282        }
21283    }
21284
21285    /**
21286     * Return the resolved text direction.
21287     *
21288     * @return the resolved text direction. Returns one of:
21289     *
21290     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21291     * {@link #TEXT_DIRECTION_ANY_RTL},
21292     * {@link #TEXT_DIRECTION_LTR},
21293     * {@link #TEXT_DIRECTION_RTL},
21294     * {@link #TEXT_DIRECTION_LOCALE},
21295     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21296     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21297     *
21298     * @attr ref android.R.styleable#View_textDirection
21299     */
21300    @ViewDebug.ExportedProperty(category = "text", mapping = {
21301            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21302            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21303            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21304            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21305            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21306            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21307            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21308            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21309    })
21310    public int getTextDirection() {
21311        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21312    }
21313
21314    /**
21315     * Resolve the text direction.
21316     *
21317     * @return true if resolution has been done, false otherwise.
21318     *
21319     * @hide
21320     */
21321    public boolean resolveTextDirection() {
21322        // Reset any previous text direction resolution
21323        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21324
21325        if (hasRtlSupport()) {
21326            // Set resolved text direction flag depending on text direction flag
21327            final int textDirection = getRawTextDirection();
21328            switch(textDirection) {
21329                case TEXT_DIRECTION_INHERIT:
21330                    if (!canResolveTextDirection()) {
21331                        // We cannot do the resolution if there is no parent, so use the default one
21332                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21333                        // Resolution will need to happen again later
21334                        return false;
21335                    }
21336
21337                    // Parent has not yet resolved, so we still return the default
21338                    try {
21339                        if (!mParent.isTextDirectionResolved()) {
21340                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21341                            // Resolution will need to happen again later
21342                            return false;
21343                        }
21344                    } catch (AbstractMethodError e) {
21345                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21346                                " does not fully implement ViewParent", e);
21347                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
21348                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21349                        return true;
21350                    }
21351
21352                    // Set current resolved direction to the same value as the parent's one
21353                    int parentResolvedDirection;
21354                    try {
21355                        parentResolvedDirection = mParent.getTextDirection();
21356                    } catch (AbstractMethodError e) {
21357                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21358                                " does not fully implement ViewParent", e);
21359                        parentResolvedDirection = TEXT_DIRECTION_LTR;
21360                    }
21361                    switch (parentResolvedDirection) {
21362                        case TEXT_DIRECTION_FIRST_STRONG:
21363                        case TEXT_DIRECTION_ANY_RTL:
21364                        case TEXT_DIRECTION_LTR:
21365                        case TEXT_DIRECTION_RTL:
21366                        case TEXT_DIRECTION_LOCALE:
21367                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
21368                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
21369                            mPrivateFlags2 |=
21370                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21371                            break;
21372                        default:
21373                            // Default resolved direction is "first strong" heuristic
21374                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21375                    }
21376                    break;
21377                case TEXT_DIRECTION_FIRST_STRONG:
21378                case TEXT_DIRECTION_ANY_RTL:
21379                case TEXT_DIRECTION_LTR:
21380                case TEXT_DIRECTION_RTL:
21381                case TEXT_DIRECTION_LOCALE:
21382                case TEXT_DIRECTION_FIRST_STRONG_LTR:
21383                case TEXT_DIRECTION_FIRST_STRONG_RTL:
21384                    // Resolved direction is the same as text direction
21385                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21386                    break;
21387                default:
21388                    // Default resolved direction is "first strong" heuristic
21389                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21390            }
21391        } else {
21392            // Default resolved direction is "first strong" heuristic
21393            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21394        }
21395
21396        // Set to resolved
21397        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
21398        return true;
21399    }
21400
21401    /**
21402     * Check if text direction resolution can be done.
21403     *
21404     * @return true if text direction resolution can be done otherwise return false.
21405     */
21406    public boolean canResolveTextDirection() {
21407        switch (getRawTextDirection()) {
21408            case TEXT_DIRECTION_INHERIT:
21409                if (mParent != null) {
21410                    try {
21411                        return mParent.canResolveTextDirection();
21412                    } catch (AbstractMethodError e) {
21413                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21414                                " does not fully implement ViewParent", e);
21415                    }
21416                }
21417                return false;
21418
21419            default:
21420                return true;
21421        }
21422    }
21423
21424    /**
21425     * Reset resolved text direction. Text direction will be resolved during a call to
21426     * {@link #onMeasure(int, int)}.
21427     *
21428     * @hide
21429     */
21430    public void resetResolvedTextDirection() {
21431        // Reset any previous text direction resolution
21432        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21433        // Set to default value
21434        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21435    }
21436
21437    /**
21438     * @return true if text direction is inherited.
21439     *
21440     * @hide
21441     */
21442    public boolean isTextDirectionInherited() {
21443        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
21444    }
21445
21446    /**
21447     * @return true if text direction is resolved.
21448     */
21449    public boolean isTextDirectionResolved() {
21450        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
21451    }
21452
21453    /**
21454     * Return the value specifying the text alignment or policy that was set with
21455     * {@link #setTextAlignment(int)}.
21456     *
21457     * @return the defined text alignment. It can be one of:
21458     *
21459     * {@link #TEXT_ALIGNMENT_INHERIT},
21460     * {@link #TEXT_ALIGNMENT_GRAVITY},
21461     * {@link #TEXT_ALIGNMENT_CENTER},
21462     * {@link #TEXT_ALIGNMENT_TEXT_START},
21463     * {@link #TEXT_ALIGNMENT_TEXT_END},
21464     * {@link #TEXT_ALIGNMENT_VIEW_START},
21465     * {@link #TEXT_ALIGNMENT_VIEW_END}
21466     *
21467     * @attr ref android.R.styleable#View_textAlignment
21468     *
21469     * @hide
21470     */
21471    @ViewDebug.ExportedProperty(category = "text", mapping = {
21472            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21473            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21474            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21475            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21476            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21477            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21478            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21479    })
21480    @TextAlignment
21481    public int getRawTextAlignment() {
21482        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
21483    }
21484
21485    /**
21486     * Set the text alignment.
21487     *
21488     * @param textAlignment The text alignment to set. Should be one of
21489     *
21490     * {@link #TEXT_ALIGNMENT_INHERIT},
21491     * {@link #TEXT_ALIGNMENT_GRAVITY},
21492     * {@link #TEXT_ALIGNMENT_CENTER},
21493     * {@link #TEXT_ALIGNMENT_TEXT_START},
21494     * {@link #TEXT_ALIGNMENT_TEXT_END},
21495     * {@link #TEXT_ALIGNMENT_VIEW_START},
21496     * {@link #TEXT_ALIGNMENT_VIEW_END}
21497     *
21498     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
21499     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
21500     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
21501     *
21502     * @attr ref android.R.styleable#View_textAlignment
21503     */
21504    public void setTextAlignment(@TextAlignment int textAlignment) {
21505        if (textAlignment != getRawTextAlignment()) {
21506            // Reset the current and resolved text alignment
21507            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
21508            resetResolvedTextAlignment();
21509            // Set the new text alignment
21510            mPrivateFlags2 |=
21511                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
21512            // Do resolution
21513            resolveTextAlignment();
21514            // Notify change
21515            onRtlPropertiesChanged(getLayoutDirection());
21516            // Refresh
21517            requestLayout();
21518            invalidate(true);
21519        }
21520    }
21521
21522    /**
21523     * Return the resolved text alignment.
21524     *
21525     * @return the resolved text alignment. Returns one of:
21526     *
21527     * {@link #TEXT_ALIGNMENT_GRAVITY},
21528     * {@link #TEXT_ALIGNMENT_CENTER},
21529     * {@link #TEXT_ALIGNMENT_TEXT_START},
21530     * {@link #TEXT_ALIGNMENT_TEXT_END},
21531     * {@link #TEXT_ALIGNMENT_VIEW_START},
21532     * {@link #TEXT_ALIGNMENT_VIEW_END}
21533     *
21534     * @attr ref android.R.styleable#View_textAlignment
21535     */
21536    @ViewDebug.ExportedProperty(category = "text", mapping = {
21537            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21538            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21539            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21540            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21541            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21542            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21543            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21544    })
21545    @TextAlignment
21546    public int getTextAlignment() {
21547        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
21548                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
21549    }
21550
21551    /**
21552     * Resolve the text alignment.
21553     *
21554     * @return true if resolution has been done, false otherwise.
21555     *
21556     * @hide
21557     */
21558    public boolean resolveTextAlignment() {
21559        // Reset any previous text alignment resolution
21560        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21561
21562        if (hasRtlSupport()) {
21563            // Set resolved text alignment flag depending on text alignment flag
21564            final int textAlignment = getRawTextAlignment();
21565            switch (textAlignment) {
21566                case TEXT_ALIGNMENT_INHERIT:
21567                    // Check if we can resolve the text alignment
21568                    if (!canResolveTextAlignment()) {
21569                        // We cannot do the resolution if there is no parent so use the default
21570                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21571                        // Resolution will need to happen again later
21572                        return false;
21573                    }
21574
21575                    // Parent has not yet resolved, so we still return the default
21576                    try {
21577                        if (!mParent.isTextAlignmentResolved()) {
21578                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21579                            // Resolution will need to happen again later
21580                            return false;
21581                        }
21582                    } catch (AbstractMethodError e) {
21583                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21584                                " does not fully implement ViewParent", e);
21585                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
21586                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21587                        return true;
21588                    }
21589
21590                    int parentResolvedTextAlignment;
21591                    try {
21592                        parentResolvedTextAlignment = mParent.getTextAlignment();
21593                    } catch (AbstractMethodError e) {
21594                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21595                                " does not fully implement ViewParent", e);
21596                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
21597                    }
21598                    switch (parentResolvedTextAlignment) {
21599                        case TEXT_ALIGNMENT_GRAVITY:
21600                        case TEXT_ALIGNMENT_TEXT_START:
21601                        case TEXT_ALIGNMENT_TEXT_END:
21602                        case TEXT_ALIGNMENT_CENTER:
21603                        case TEXT_ALIGNMENT_VIEW_START:
21604                        case TEXT_ALIGNMENT_VIEW_END:
21605                            // Resolved text alignment is the same as the parent resolved
21606                            // text alignment
21607                            mPrivateFlags2 |=
21608                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21609                            break;
21610                        default:
21611                            // Use default resolved text alignment
21612                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21613                    }
21614                    break;
21615                case TEXT_ALIGNMENT_GRAVITY:
21616                case TEXT_ALIGNMENT_TEXT_START:
21617                case TEXT_ALIGNMENT_TEXT_END:
21618                case TEXT_ALIGNMENT_CENTER:
21619                case TEXT_ALIGNMENT_VIEW_START:
21620                case TEXT_ALIGNMENT_VIEW_END:
21621                    // Resolved text alignment is the same as text alignment
21622                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21623                    break;
21624                default:
21625                    // Use default resolved text alignment
21626                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21627            }
21628        } else {
21629            // Use default resolved text alignment
21630            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21631        }
21632
21633        // Set the resolved
21634        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21635        return true;
21636    }
21637
21638    /**
21639     * Check if text alignment resolution can be done.
21640     *
21641     * @return true if text alignment resolution can be done otherwise return false.
21642     */
21643    public boolean canResolveTextAlignment() {
21644        switch (getRawTextAlignment()) {
21645            case TEXT_DIRECTION_INHERIT:
21646                if (mParent != null) {
21647                    try {
21648                        return mParent.canResolveTextAlignment();
21649                    } catch (AbstractMethodError e) {
21650                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21651                                " does not fully implement ViewParent", e);
21652                    }
21653                }
21654                return false;
21655
21656            default:
21657                return true;
21658        }
21659    }
21660
21661    /**
21662     * Reset resolved text alignment. Text alignment will be resolved during a call to
21663     * {@link #onMeasure(int, int)}.
21664     *
21665     * @hide
21666     */
21667    public void resetResolvedTextAlignment() {
21668        // Reset any previous text alignment resolution
21669        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21670        // Set to default
21671        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21672    }
21673
21674    /**
21675     * @return true if text alignment is inherited.
21676     *
21677     * @hide
21678     */
21679    public boolean isTextAlignmentInherited() {
21680        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
21681    }
21682
21683    /**
21684     * @return true if text alignment is resolved.
21685     */
21686    public boolean isTextAlignmentResolved() {
21687        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21688    }
21689
21690    /**
21691     * Generate a value suitable for use in {@link #setId(int)}.
21692     * This value will not collide with ID values generated at build time by aapt for R.id.
21693     *
21694     * @return a generated ID value
21695     */
21696    public static int generateViewId() {
21697        for (;;) {
21698            final int result = sNextGeneratedId.get();
21699            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
21700            int newValue = result + 1;
21701            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
21702            if (sNextGeneratedId.compareAndSet(result, newValue)) {
21703                return result;
21704            }
21705        }
21706    }
21707
21708    /**
21709     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
21710     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
21711     *                           a normal View or a ViewGroup with
21712     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
21713     * @hide
21714     */
21715    public void captureTransitioningViews(List<View> transitioningViews) {
21716        if (getVisibility() == View.VISIBLE) {
21717            transitioningViews.add(this);
21718        }
21719    }
21720
21721    /**
21722     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
21723     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
21724     * @hide
21725     */
21726    public void findNamedViews(Map<String, View> namedElements) {
21727        if (getVisibility() == VISIBLE || mGhostView != null) {
21728            String transitionName = getTransitionName();
21729            if (transitionName != null) {
21730                namedElements.put(transitionName, this);
21731            }
21732        }
21733    }
21734
21735    /**
21736     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
21737     * The default implementation does not care the location or event types, but some subclasses
21738     * may use it (such as WebViews).
21739     * @param event The MotionEvent from a mouse
21740     * @param x The x position of the event, local to the view
21741     * @param y The y position of the event, local to the view
21742     * @see PointerIcon
21743     */
21744    public PointerIcon getPointerIcon(MotionEvent event, float x, float y) {
21745        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
21746            return PointerIcon.getSystemIcon(mContext, PointerIcon.STYLE_ARROW);
21747        }
21748        return mPointerIcon;
21749    }
21750
21751    /**
21752     * Set the pointer icon for the current view.
21753     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
21754     */
21755    public void setPointerIcon(PointerIcon pointerIcon) {
21756        mPointerIcon = pointerIcon;
21757        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
21758            return;
21759        }
21760        try {
21761            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
21762        } catch (RemoteException e) {
21763        }
21764    }
21765
21766    /**
21767     * Request capturing further mouse events.
21768     *
21769     * When the view captures, the mouse pointer icon will disappear and will not change its
21770     * position. Further mouse events will come to the capturing view, and the mouse movements
21771     * will can be detected through {@link MotionEvent#AXIS_RELATIVE_X} and
21772     * {@link MotionEvent#AXIS_RELATIVE_Y}. Non-mouse events (touchscreens, or stylus) will not
21773     * be affected.
21774     *
21775     * The capture will be released through {@link #releasePointerCapture()}, or will be lost
21776     * automatically when the view or containing window disappear.
21777     *
21778     * @return true when succeeds.
21779     * @see #releasePointerCapture()
21780     * @see #hasPointerCapture()
21781     */
21782    public void setPointerCapture() {
21783        final ViewRootImpl viewRootImpl = getViewRootImpl();
21784        if (viewRootImpl != null) {
21785            viewRootImpl.setPointerCapture(this);
21786        }
21787    }
21788
21789
21790    /**
21791     * Release the current capture of mouse events.
21792     *
21793     * If the view does not have the capture, it will do nothing.
21794     * @see #setPointerCapture()
21795     * @see #hasPointerCapture()
21796     */
21797    public void releasePointerCapture() {
21798        final ViewRootImpl viewRootImpl = getViewRootImpl();
21799        if (viewRootImpl != null) {
21800            viewRootImpl.releasePointerCapture(this);
21801        }
21802    }
21803
21804    /**
21805     * Checks the capture status of mouse events.
21806     *
21807     * @return true if the view has the capture.
21808     * @see #setPointerCapture()
21809     * @see #hasPointerCapture()
21810     */
21811    public boolean hasPointerCapture() {
21812        final ViewRootImpl viewRootImpl = getViewRootImpl();
21813        return (viewRootImpl != null) && viewRootImpl.hasPointerCapture(this);
21814    }
21815
21816    //
21817    // Properties
21818    //
21819    /**
21820     * A Property wrapper around the <code>alpha</code> functionality handled by the
21821     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
21822     */
21823    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
21824        @Override
21825        public void setValue(View object, float value) {
21826            object.setAlpha(value);
21827        }
21828
21829        @Override
21830        public Float get(View object) {
21831            return object.getAlpha();
21832        }
21833    };
21834
21835    /**
21836     * A Property wrapper around the <code>translationX</code> functionality handled by the
21837     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
21838     */
21839    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
21840        @Override
21841        public void setValue(View object, float value) {
21842            object.setTranslationX(value);
21843        }
21844
21845                @Override
21846        public Float get(View object) {
21847            return object.getTranslationX();
21848        }
21849    };
21850
21851    /**
21852     * A Property wrapper around the <code>translationY</code> functionality handled by the
21853     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
21854     */
21855    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
21856        @Override
21857        public void setValue(View object, float value) {
21858            object.setTranslationY(value);
21859        }
21860
21861        @Override
21862        public Float get(View object) {
21863            return object.getTranslationY();
21864        }
21865    };
21866
21867    /**
21868     * A Property wrapper around the <code>translationZ</code> functionality handled by the
21869     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
21870     */
21871    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
21872        @Override
21873        public void setValue(View object, float value) {
21874            object.setTranslationZ(value);
21875        }
21876
21877        @Override
21878        public Float get(View object) {
21879            return object.getTranslationZ();
21880        }
21881    };
21882
21883    /**
21884     * A Property wrapper around the <code>x</code> functionality handled by the
21885     * {@link View#setX(float)} and {@link View#getX()} methods.
21886     */
21887    public static final Property<View, Float> X = new FloatProperty<View>("x") {
21888        @Override
21889        public void setValue(View object, float value) {
21890            object.setX(value);
21891        }
21892
21893        @Override
21894        public Float get(View object) {
21895            return object.getX();
21896        }
21897    };
21898
21899    /**
21900     * A Property wrapper around the <code>y</code> functionality handled by the
21901     * {@link View#setY(float)} and {@link View#getY()} methods.
21902     */
21903    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
21904        @Override
21905        public void setValue(View object, float value) {
21906            object.setY(value);
21907        }
21908
21909        @Override
21910        public Float get(View object) {
21911            return object.getY();
21912        }
21913    };
21914
21915    /**
21916     * A Property wrapper around the <code>z</code> functionality handled by the
21917     * {@link View#setZ(float)} and {@link View#getZ()} methods.
21918     */
21919    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
21920        @Override
21921        public void setValue(View object, float value) {
21922            object.setZ(value);
21923        }
21924
21925        @Override
21926        public Float get(View object) {
21927            return object.getZ();
21928        }
21929    };
21930
21931    /**
21932     * A Property wrapper around the <code>rotation</code> functionality handled by the
21933     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
21934     */
21935    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
21936        @Override
21937        public void setValue(View object, float value) {
21938            object.setRotation(value);
21939        }
21940
21941        @Override
21942        public Float get(View object) {
21943            return object.getRotation();
21944        }
21945    };
21946
21947    /**
21948     * A Property wrapper around the <code>rotationX</code> functionality handled by the
21949     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
21950     */
21951    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
21952        @Override
21953        public void setValue(View object, float value) {
21954            object.setRotationX(value);
21955        }
21956
21957        @Override
21958        public Float get(View object) {
21959            return object.getRotationX();
21960        }
21961    };
21962
21963    /**
21964     * A Property wrapper around the <code>rotationY</code> functionality handled by the
21965     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
21966     */
21967    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
21968        @Override
21969        public void setValue(View object, float value) {
21970            object.setRotationY(value);
21971        }
21972
21973        @Override
21974        public Float get(View object) {
21975            return object.getRotationY();
21976        }
21977    };
21978
21979    /**
21980     * A Property wrapper around the <code>scaleX</code> functionality handled by the
21981     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
21982     */
21983    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
21984        @Override
21985        public void setValue(View object, float value) {
21986            object.setScaleX(value);
21987        }
21988
21989        @Override
21990        public Float get(View object) {
21991            return object.getScaleX();
21992        }
21993    };
21994
21995    /**
21996     * A Property wrapper around the <code>scaleY</code> functionality handled by the
21997     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
21998     */
21999    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22000        @Override
22001        public void setValue(View object, float value) {
22002            object.setScaleY(value);
22003        }
22004
22005        @Override
22006        public Float get(View object) {
22007            return object.getScaleY();
22008        }
22009    };
22010
22011    /**
22012     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22013     * Each MeasureSpec represents a requirement for either the width or the height.
22014     * A MeasureSpec is comprised of a size and a mode. There are three possible
22015     * modes:
22016     * <dl>
22017     * <dt>UNSPECIFIED</dt>
22018     * <dd>
22019     * The parent has not imposed any constraint on the child. It can be whatever size
22020     * it wants.
22021     * </dd>
22022     *
22023     * <dt>EXACTLY</dt>
22024     * <dd>
22025     * The parent has determined an exact size for the child. The child is going to be
22026     * given those bounds regardless of how big it wants to be.
22027     * </dd>
22028     *
22029     * <dt>AT_MOST</dt>
22030     * <dd>
22031     * The child can be as large as it wants up to the specified size.
22032     * </dd>
22033     * </dl>
22034     *
22035     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22036     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22037     */
22038    public static class MeasureSpec {
22039        private static final int MODE_SHIFT = 30;
22040        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22041
22042        /** @hide */
22043        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22044        @Retention(RetentionPolicy.SOURCE)
22045        public @interface MeasureSpecMode {}
22046
22047        /**
22048         * Measure specification mode: The parent has not imposed any constraint
22049         * on the child. It can be whatever size it wants.
22050         */
22051        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22052
22053        /**
22054         * Measure specification mode: The parent has determined an exact size
22055         * for the child. The child is going to be given those bounds regardless
22056         * of how big it wants to be.
22057         */
22058        public static final int EXACTLY     = 1 << MODE_SHIFT;
22059
22060        /**
22061         * Measure specification mode: The child can be as large as it wants up
22062         * to the specified size.
22063         */
22064        public static final int AT_MOST     = 2 << MODE_SHIFT;
22065
22066        /**
22067         * Creates a measure specification based on the supplied size and mode.
22068         *
22069         * The mode must always be one of the following:
22070         * <ul>
22071         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22072         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22073         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22074         * </ul>
22075         *
22076         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22077         * implementation was such that the order of arguments did not matter
22078         * and overflow in either value could impact the resulting MeasureSpec.
22079         * {@link android.widget.RelativeLayout} was affected by this bug.
22080         * Apps targeting API levels greater than 17 will get the fixed, more strict
22081         * behavior.</p>
22082         *
22083         * @param size the size of the measure specification
22084         * @param mode the mode of the measure specification
22085         * @return the measure specification based on size and mode
22086         */
22087        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22088                                          @MeasureSpecMode int mode) {
22089            if (sUseBrokenMakeMeasureSpec) {
22090                return size + mode;
22091            } else {
22092                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22093            }
22094        }
22095
22096        /**
22097         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22098         * will automatically get a size of 0. Older apps expect this.
22099         *
22100         * @hide internal use only for compatibility with system widgets and older apps
22101         */
22102        public static int makeSafeMeasureSpec(int size, int mode) {
22103            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22104                return 0;
22105            }
22106            return makeMeasureSpec(size, mode);
22107        }
22108
22109        /**
22110         * Extracts the mode from the supplied measure specification.
22111         *
22112         * @param measureSpec the measure specification to extract the mode from
22113         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22114         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22115         *         {@link android.view.View.MeasureSpec#EXACTLY}
22116         */
22117        @MeasureSpecMode
22118        public static int getMode(int measureSpec) {
22119            //noinspection ResourceType
22120            return (measureSpec & MODE_MASK);
22121        }
22122
22123        /**
22124         * Extracts the size from the supplied measure specification.
22125         *
22126         * @param measureSpec the measure specification to extract the size from
22127         * @return the size in pixels defined in the supplied measure specification
22128         */
22129        public static int getSize(int measureSpec) {
22130            return (measureSpec & ~MODE_MASK);
22131        }
22132
22133        static int adjust(int measureSpec, int delta) {
22134            final int mode = getMode(measureSpec);
22135            int size = getSize(measureSpec);
22136            if (mode == UNSPECIFIED) {
22137                // No need to adjust size for UNSPECIFIED mode.
22138                return makeMeasureSpec(size, UNSPECIFIED);
22139            }
22140            size += delta;
22141            if (size < 0) {
22142                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22143                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22144                size = 0;
22145            }
22146            return makeMeasureSpec(size, mode);
22147        }
22148
22149        /**
22150         * Returns a String representation of the specified measure
22151         * specification.
22152         *
22153         * @param measureSpec the measure specification to convert to a String
22154         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22155         */
22156        public static String toString(int measureSpec) {
22157            int mode = getMode(measureSpec);
22158            int size = getSize(measureSpec);
22159
22160            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22161
22162            if (mode == UNSPECIFIED)
22163                sb.append("UNSPECIFIED ");
22164            else if (mode == EXACTLY)
22165                sb.append("EXACTLY ");
22166            else if (mode == AT_MOST)
22167                sb.append("AT_MOST ");
22168            else
22169                sb.append(mode).append(" ");
22170
22171            sb.append(size);
22172            return sb.toString();
22173        }
22174    }
22175
22176    private final class CheckForLongPress implements Runnable {
22177        private int mOriginalWindowAttachCount;
22178        private float mX;
22179        private float mY;
22180
22181        @Override
22182        public void run() {
22183            if (isPressed() && (mParent != null)
22184                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22185                if (performLongClick(mX, mY)) {
22186                    mHasPerformedLongPress = true;
22187                }
22188            }
22189        }
22190
22191        public void setAnchor(float x, float y) {
22192            mX = x;
22193            mY = y;
22194        }
22195
22196        public void rememberWindowAttachCount() {
22197            mOriginalWindowAttachCount = mWindowAttachCount;
22198        }
22199    }
22200
22201    private final class CheckForTap implements Runnable {
22202        public float x;
22203        public float y;
22204
22205        @Override
22206        public void run() {
22207            mPrivateFlags &= ~PFLAG_PREPRESSED;
22208            setPressed(true, x, y);
22209            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22210        }
22211    }
22212
22213    private final class PerformClick implements Runnable {
22214        @Override
22215        public void run() {
22216            performClick();
22217        }
22218    }
22219
22220    /**
22221     * This method returns a ViewPropertyAnimator object, which can be used to animate
22222     * specific properties on this View.
22223     *
22224     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22225     */
22226    public ViewPropertyAnimator animate() {
22227        if (mAnimator == null) {
22228            mAnimator = new ViewPropertyAnimator(this);
22229        }
22230        return mAnimator;
22231    }
22232
22233    /**
22234     * Sets the name of the View to be used to identify Views in Transitions.
22235     * Names should be unique in the View hierarchy.
22236     *
22237     * @param transitionName The name of the View to uniquely identify it for Transitions.
22238     */
22239    public final void setTransitionName(String transitionName) {
22240        mTransitionName = transitionName;
22241    }
22242
22243    /**
22244     * Returns the name of the View to be used to identify Views in Transitions.
22245     * Names should be unique in the View hierarchy.
22246     *
22247     * <p>This returns null if the View has not been given a name.</p>
22248     *
22249     * @return The name used of the View to be used to identify Views in Transitions or null
22250     * if no name has been given.
22251     */
22252    @ViewDebug.ExportedProperty
22253    public String getTransitionName() {
22254        return mTransitionName;
22255    }
22256
22257    /**
22258     * @hide
22259     */
22260    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22261        // Do nothing.
22262    }
22263
22264    /**
22265     * Interface definition for a callback to be invoked when a hardware key event is
22266     * dispatched to this view. The callback will be invoked before the key event is
22267     * given to the view. This is only useful for hardware keyboards; a software input
22268     * method has no obligation to trigger this listener.
22269     */
22270    public interface OnKeyListener {
22271        /**
22272         * Called when a hardware key is dispatched to a view. This allows listeners to
22273         * get a chance to respond before the target view.
22274         * <p>Key presses in software keyboards will generally NOT trigger this method,
22275         * although some may elect to do so in some situations. Do not assume a
22276         * software input method has to be key-based; even if it is, it may use key presses
22277         * in a different way than you expect, so there is no way to reliably catch soft
22278         * input key presses.
22279         *
22280         * @param v The view the key has been dispatched to.
22281         * @param keyCode The code for the physical key that was pressed
22282         * @param event The KeyEvent object containing full information about
22283         *        the event.
22284         * @return True if the listener has consumed the event, false otherwise.
22285         */
22286        boolean onKey(View v, int keyCode, KeyEvent event);
22287    }
22288
22289    /**
22290     * Interface definition for a callback to be invoked when a touch event is
22291     * dispatched to this view. The callback will be invoked before the touch
22292     * event is given to the view.
22293     */
22294    public interface OnTouchListener {
22295        /**
22296         * Called when a touch event is dispatched to a view. This allows listeners to
22297         * get a chance to respond before the target view.
22298         *
22299         * @param v The view the touch event has been dispatched to.
22300         * @param event The MotionEvent object containing full information about
22301         *        the event.
22302         * @return True if the listener has consumed the event, false otherwise.
22303         */
22304        boolean onTouch(View v, MotionEvent event);
22305    }
22306
22307    /**
22308     * Interface definition for a callback to be invoked when a hover event is
22309     * dispatched to this view. The callback will be invoked before the hover
22310     * event is given to the view.
22311     */
22312    public interface OnHoverListener {
22313        /**
22314         * Called when a hover event is dispatched to a view. This allows listeners to
22315         * get a chance to respond before the target view.
22316         *
22317         * @param v The view the hover event has been dispatched to.
22318         * @param event The MotionEvent object containing full information about
22319         *        the event.
22320         * @return True if the listener has consumed the event, false otherwise.
22321         */
22322        boolean onHover(View v, MotionEvent event);
22323    }
22324
22325    /**
22326     * Interface definition for a callback to be invoked when a generic motion event is
22327     * dispatched to this view. The callback will be invoked before the generic motion
22328     * event is given to the view.
22329     */
22330    public interface OnGenericMotionListener {
22331        /**
22332         * Called when a generic motion event is dispatched to a view. This allows listeners to
22333         * get a chance to respond before the target view.
22334         *
22335         * @param v The view the generic motion event has been dispatched to.
22336         * @param event The MotionEvent object containing full information about
22337         *        the event.
22338         * @return True if the listener has consumed the event, false otherwise.
22339         */
22340        boolean onGenericMotion(View v, MotionEvent event);
22341    }
22342
22343    /**
22344     * Interface definition for a callback to be invoked when a view has been clicked and held.
22345     */
22346    public interface OnLongClickListener {
22347        /**
22348         * Called when a view has been clicked and held.
22349         *
22350         * @param v The view that was clicked and held.
22351         *
22352         * @return true if the callback consumed the long click, false otherwise.
22353         */
22354        boolean onLongClick(View v);
22355    }
22356
22357    /**
22358     * Interface definition for a callback to be invoked when a drag is being dispatched
22359     * to this view.  The callback will be invoked before the hosting view's own
22360     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
22361     * onDrag(event) behavior, it should return 'false' from this callback.
22362     *
22363     * <div class="special reference">
22364     * <h3>Developer Guides</h3>
22365     * <p>For a guide to implementing drag and drop features, read the
22366     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22367     * </div>
22368     */
22369    public interface OnDragListener {
22370        /**
22371         * Called when a drag event is dispatched to a view. This allows listeners
22372         * to get a chance to override base View behavior.
22373         *
22374         * @param v The View that received the drag event.
22375         * @param event The {@link android.view.DragEvent} object for the drag event.
22376         * @return {@code true} if the drag event was handled successfully, or {@code false}
22377         * if the drag event was not handled. Note that {@code false} will trigger the View
22378         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
22379         */
22380        boolean onDrag(View v, DragEvent event);
22381    }
22382
22383    /**
22384     * Interface definition for a callback to be invoked when the focus state of
22385     * a view changed.
22386     */
22387    public interface OnFocusChangeListener {
22388        /**
22389         * Called when the focus state of a view has changed.
22390         *
22391         * @param v The view whose state has changed.
22392         * @param hasFocus The new focus state of v.
22393         */
22394        void onFocusChange(View v, boolean hasFocus);
22395    }
22396
22397    /**
22398     * Interface definition for a callback to be invoked when a view is clicked.
22399     */
22400    public interface OnClickListener {
22401        /**
22402         * Called when a view has been clicked.
22403         *
22404         * @param v The view that was clicked.
22405         */
22406        void onClick(View v);
22407    }
22408
22409    /**
22410     * Interface definition for a callback to be invoked when a view is context clicked.
22411     */
22412    public interface OnContextClickListener {
22413        /**
22414         * Called when a view is context clicked.
22415         *
22416         * @param v The view that has been context clicked.
22417         * @return true if the callback consumed the context click, false otherwise.
22418         */
22419        boolean onContextClick(View v);
22420    }
22421
22422    /**
22423     * Interface definition for a callback to be invoked when the context menu
22424     * for this view is being built.
22425     */
22426    public interface OnCreateContextMenuListener {
22427        /**
22428         * Called when the context menu for this view is being built. It is not
22429         * safe to hold onto the menu after this method returns.
22430         *
22431         * @param menu The context menu that is being built
22432         * @param v The view for which the context menu is being built
22433         * @param menuInfo Extra information about the item for which the
22434         *            context menu should be shown. This information will vary
22435         *            depending on the class of v.
22436         */
22437        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
22438    }
22439
22440    /**
22441     * Interface definition for a callback to be invoked when the status bar changes
22442     * visibility.  This reports <strong>global</strong> changes to the system UI
22443     * state, not what the application is requesting.
22444     *
22445     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
22446     */
22447    public interface OnSystemUiVisibilityChangeListener {
22448        /**
22449         * Called when the status bar changes visibility because of a call to
22450         * {@link View#setSystemUiVisibility(int)}.
22451         *
22452         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22453         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
22454         * This tells you the <strong>global</strong> state of these UI visibility
22455         * flags, not what your app is currently applying.
22456         */
22457        public void onSystemUiVisibilityChange(int visibility);
22458    }
22459
22460    /**
22461     * Interface definition for a callback to be invoked when this view is attached
22462     * or detached from its window.
22463     */
22464    public interface OnAttachStateChangeListener {
22465        /**
22466         * Called when the view is attached to a window.
22467         * @param v The view that was attached
22468         */
22469        public void onViewAttachedToWindow(View v);
22470        /**
22471         * Called when the view is detached from a window.
22472         * @param v The view that was detached
22473         */
22474        public void onViewDetachedFromWindow(View v);
22475    }
22476
22477    /**
22478     * Listener for applying window insets on a view in a custom way.
22479     *
22480     * <p>Apps may choose to implement this interface if they want to apply custom policy
22481     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
22482     * is set, its
22483     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
22484     * method will be called instead of the View's own
22485     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
22486     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
22487     * the View's normal behavior as part of its own.</p>
22488     */
22489    public interface OnApplyWindowInsetsListener {
22490        /**
22491         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
22492         * on a View, this listener method will be called instead of the view's own
22493         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
22494         *
22495         * @param v The view applying window insets
22496         * @param insets The insets to apply
22497         * @return The insets supplied, minus any insets that were consumed
22498         */
22499        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
22500    }
22501
22502    private final class UnsetPressedState implements Runnable {
22503        @Override
22504        public void run() {
22505            setPressed(false);
22506        }
22507    }
22508
22509    /**
22510     * Base class for derived classes that want to save and restore their own
22511     * state in {@link android.view.View#onSaveInstanceState()}.
22512     */
22513    public static class BaseSavedState extends AbsSavedState {
22514        String mStartActivityRequestWhoSaved;
22515
22516        /**
22517         * Constructor used when reading from a parcel. Reads the state of the superclass.
22518         *
22519         * @param source
22520         */
22521        public BaseSavedState(Parcel source) {
22522            super(source);
22523            mStartActivityRequestWhoSaved = source.readString();
22524        }
22525
22526        /**
22527         * Constructor called by derived classes when creating their SavedState objects
22528         *
22529         * @param superState The state of the superclass of this view
22530         */
22531        public BaseSavedState(Parcelable superState) {
22532            super(superState);
22533        }
22534
22535        @Override
22536        public void writeToParcel(Parcel out, int flags) {
22537            super.writeToParcel(out, flags);
22538            out.writeString(mStartActivityRequestWhoSaved);
22539        }
22540
22541        public static final Parcelable.Creator<BaseSavedState> CREATOR =
22542                new Parcelable.Creator<BaseSavedState>() {
22543            public BaseSavedState createFromParcel(Parcel in) {
22544                return new BaseSavedState(in);
22545            }
22546
22547            public BaseSavedState[] newArray(int size) {
22548                return new BaseSavedState[size];
22549            }
22550        };
22551    }
22552
22553    /**
22554     * A set of information given to a view when it is attached to its parent
22555     * window.
22556     */
22557    final static class AttachInfo {
22558        interface Callbacks {
22559            void playSoundEffect(int effectId);
22560            boolean performHapticFeedback(int effectId, boolean always);
22561        }
22562
22563        /**
22564         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
22565         * to a Handler. This class contains the target (View) to invalidate and
22566         * the coordinates of the dirty rectangle.
22567         *
22568         * For performance purposes, this class also implements a pool of up to
22569         * POOL_LIMIT objects that get reused. This reduces memory allocations
22570         * whenever possible.
22571         */
22572        static class InvalidateInfo {
22573            private static final int POOL_LIMIT = 10;
22574
22575            private static final SynchronizedPool<InvalidateInfo> sPool =
22576                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
22577
22578            View target;
22579
22580            int left;
22581            int top;
22582            int right;
22583            int bottom;
22584
22585            public static InvalidateInfo obtain() {
22586                InvalidateInfo instance = sPool.acquire();
22587                return (instance != null) ? instance : new InvalidateInfo();
22588            }
22589
22590            public void recycle() {
22591                target = null;
22592                sPool.release(this);
22593            }
22594        }
22595
22596        final IWindowSession mSession;
22597
22598        final IWindow mWindow;
22599
22600        final IBinder mWindowToken;
22601
22602        final Display mDisplay;
22603
22604        final Callbacks mRootCallbacks;
22605
22606        IWindowId mIWindowId;
22607        WindowId mWindowId;
22608
22609        /**
22610         * The top view of the hierarchy.
22611         */
22612        View mRootView;
22613
22614        IBinder mPanelParentWindowToken;
22615
22616        boolean mHardwareAccelerated;
22617        boolean mHardwareAccelerationRequested;
22618        ThreadedRenderer mHardwareRenderer;
22619        List<RenderNode> mPendingAnimatingRenderNodes;
22620
22621        /**
22622         * The state of the display to which the window is attached, as reported
22623         * by {@link Display#getState()}.  Note that the display state constants
22624         * declared by {@link Display} do not exactly line up with the screen state
22625         * constants declared by {@link View} (there are more display states than
22626         * screen states).
22627         */
22628        int mDisplayState = Display.STATE_UNKNOWN;
22629
22630        /**
22631         * Scale factor used by the compatibility mode
22632         */
22633        float mApplicationScale;
22634
22635        /**
22636         * Indicates whether the application is in compatibility mode
22637         */
22638        boolean mScalingRequired;
22639
22640        /**
22641         * Left position of this view's window
22642         */
22643        int mWindowLeft;
22644
22645        /**
22646         * Top position of this view's window
22647         */
22648        int mWindowTop;
22649
22650        /**
22651         * Indicates whether views need to use 32-bit drawing caches
22652         */
22653        boolean mUse32BitDrawingCache;
22654
22655        /**
22656         * For windows that are full-screen but using insets to layout inside
22657         * of the screen areas, these are the current insets to appear inside
22658         * the overscan area of the display.
22659         */
22660        final Rect mOverscanInsets = new Rect();
22661
22662        /**
22663         * For windows that are full-screen but using insets to layout inside
22664         * of the screen decorations, these are the current insets for the
22665         * content of the window.
22666         */
22667        final Rect mContentInsets = new Rect();
22668
22669        /**
22670         * For windows that are full-screen but using insets to layout inside
22671         * of the screen decorations, these are the current insets for the
22672         * actual visible parts of the window.
22673         */
22674        final Rect mVisibleInsets = new Rect();
22675
22676        /**
22677         * For windows that are full-screen but using insets to layout inside
22678         * of the screen decorations, these are the current insets for the
22679         * stable system windows.
22680         */
22681        final Rect mStableInsets = new Rect();
22682
22683        /**
22684         * For windows that include areas that are not covered by real surface these are the outsets
22685         * for real surface.
22686         */
22687        final Rect mOutsets = new Rect();
22688
22689        /**
22690         * In multi-window we force show the navigation bar. Because we don't want that the surface
22691         * size changes in this mode, we instead have a flag whether the navigation bar size should
22692         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
22693         */
22694        boolean mAlwaysConsumeNavBar;
22695
22696        /**
22697         * The internal insets given by this window.  This value is
22698         * supplied by the client (through
22699         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
22700         * be given to the window manager when changed to be used in laying
22701         * out windows behind it.
22702         */
22703        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
22704                = new ViewTreeObserver.InternalInsetsInfo();
22705
22706        /**
22707         * Set to true when mGivenInternalInsets is non-empty.
22708         */
22709        boolean mHasNonEmptyGivenInternalInsets;
22710
22711        /**
22712         * All views in the window's hierarchy that serve as scroll containers,
22713         * used to determine if the window can be resized or must be panned
22714         * to adjust for a soft input area.
22715         */
22716        final ArrayList<View> mScrollContainers = new ArrayList<View>();
22717
22718        final KeyEvent.DispatcherState mKeyDispatchState
22719                = new KeyEvent.DispatcherState();
22720
22721        /**
22722         * Indicates whether the view's window currently has the focus.
22723         */
22724        boolean mHasWindowFocus;
22725
22726        /**
22727         * The current visibility of the window.
22728         */
22729        int mWindowVisibility;
22730
22731        /**
22732         * Indicates the time at which drawing started to occur.
22733         */
22734        long mDrawingTime;
22735
22736        /**
22737         * Indicates whether or not ignoring the DIRTY_MASK flags.
22738         */
22739        boolean mIgnoreDirtyState;
22740
22741        /**
22742         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
22743         * to avoid clearing that flag prematurely.
22744         */
22745        boolean mSetIgnoreDirtyState = false;
22746
22747        /**
22748         * Indicates whether the view's window is currently in touch mode.
22749         */
22750        boolean mInTouchMode;
22751
22752        /**
22753         * Indicates whether the view has requested unbuffered input dispatching for the current
22754         * event stream.
22755         */
22756        boolean mUnbufferedDispatchRequested;
22757
22758        /**
22759         * Indicates that ViewAncestor should trigger a global layout change
22760         * the next time it performs a traversal
22761         */
22762        boolean mRecomputeGlobalAttributes;
22763
22764        /**
22765         * Always report new attributes at next traversal.
22766         */
22767        boolean mForceReportNewAttributes;
22768
22769        /**
22770         * Set during a traveral if any views want to keep the screen on.
22771         */
22772        boolean mKeepScreenOn;
22773
22774        /**
22775         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
22776         */
22777        int mSystemUiVisibility;
22778
22779        /**
22780         * Hack to force certain system UI visibility flags to be cleared.
22781         */
22782        int mDisabledSystemUiVisibility;
22783
22784        /**
22785         * Last global system UI visibility reported by the window manager.
22786         */
22787        int mGlobalSystemUiVisibility;
22788
22789        /**
22790         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
22791         * attached.
22792         */
22793        boolean mHasSystemUiListeners;
22794
22795        /**
22796         * Set if the window has requested to extend into the overscan region
22797         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
22798         */
22799        boolean mOverscanRequested;
22800
22801        /**
22802         * Set if the visibility of any views has changed.
22803         */
22804        boolean mViewVisibilityChanged;
22805
22806        /**
22807         * Set to true if a view has been scrolled.
22808         */
22809        boolean mViewScrollChanged;
22810
22811        /**
22812         * Set to true if high contrast mode enabled
22813         */
22814        boolean mHighContrastText;
22815
22816        /**
22817         * Set to true if a pointer event is currently being handled.
22818         */
22819        boolean mHandlingPointerEvent;
22820
22821        /**
22822         * Global to the view hierarchy used as a temporary for dealing with
22823         * x/y points in the transparent region computations.
22824         */
22825        final int[] mTransparentLocation = new int[2];
22826
22827        /**
22828         * Global to the view hierarchy used as a temporary for dealing with
22829         * x/y points in the ViewGroup.invalidateChild implementation.
22830         */
22831        final int[] mInvalidateChildLocation = new int[2];
22832
22833        /**
22834         * Global to the view hierarchy used as a temporary for dealng with
22835         * computing absolute on-screen location.
22836         */
22837        final int[] mTmpLocation = new int[2];
22838
22839        /**
22840         * Global to the view hierarchy used as a temporary for dealing with
22841         * x/y location when view is transformed.
22842         */
22843        final float[] mTmpTransformLocation = new float[2];
22844
22845        /**
22846         * The view tree observer used to dispatch global events like
22847         * layout, pre-draw, touch mode change, etc.
22848         */
22849        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
22850
22851        /**
22852         * A Canvas used by the view hierarchy to perform bitmap caching.
22853         */
22854        Canvas mCanvas;
22855
22856        /**
22857         * The view root impl.
22858         */
22859        final ViewRootImpl mViewRootImpl;
22860
22861        /**
22862         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
22863         * handler can be used to pump events in the UI events queue.
22864         */
22865        final Handler mHandler;
22866
22867        /**
22868         * Temporary for use in computing invalidate rectangles while
22869         * calling up the hierarchy.
22870         */
22871        final Rect mTmpInvalRect = new Rect();
22872
22873        /**
22874         * Temporary for use in computing hit areas with transformed views
22875         */
22876        final RectF mTmpTransformRect = new RectF();
22877
22878        /**
22879         * Temporary for use in computing hit areas with transformed views
22880         */
22881        final RectF mTmpTransformRect1 = new RectF();
22882
22883        /**
22884         * Temporary list of rectanges.
22885         */
22886        final List<RectF> mTmpRectList = new ArrayList<>();
22887
22888        /**
22889         * Temporary for use in transforming invalidation rect
22890         */
22891        final Matrix mTmpMatrix = new Matrix();
22892
22893        /**
22894         * Temporary for use in transforming invalidation rect
22895         */
22896        final Transformation mTmpTransformation = new Transformation();
22897
22898        /**
22899         * Temporary for use in querying outlines from OutlineProviders
22900         */
22901        final Outline mTmpOutline = new Outline();
22902
22903        /**
22904         * Temporary list for use in collecting focusable descendents of a view.
22905         */
22906        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
22907
22908        /**
22909         * The id of the window for accessibility purposes.
22910         */
22911        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
22912
22913        /**
22914         * Flags related to accessibility processing.
22915         *
22916         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
22917         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
22918         */
22919        int mAccessibilityFetchFlags;
22920
22921        /**
22922         * The drawable for highlighting accessibility focus.
22923         */
22924        Drawable mAccessibilityFocusDrawable;
22925
22926        /**
22927         * Show where the margins, bounds and layout bounds are for each view.
22928         */
22929        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
22930
22931        /**
22932         * Point used to compute visible regions.
22933         */
22934        final Point mPoint = new Point();
22935
22936        /**
22937         * Used to track which View originated a requestLayout() call, used when
22938         * requestLayout() is called during layout.
22939         */
22940        View mViewRequestingLayout;
22941
22942        /**
22943         * Used to track views that need (at least) a partial relayout at their current size
22944         * during the next traversal.
22945         */
22946        List<View> mPartialLayoutViews = new ArrayList<>();
22947
22948        /**
22949         * Swapped with mPartialLayoutViews during layout to avoid concurrent
22950         * modification. Lazily assigned during ViewRootImpl layout.
22951         */
22952        List<View> mEmptyPartialLayoutViews;
22953
22954        /**
22955         * Used to track the identity of the current drag operation.
22956         */
22957        IBinder mDragToken;
22958
22959        /**
22960         * The drag shadow surface for the current drag operation.
22961         */
22962        public Surface mDragSurface;
22963
22964        /**
22965         * Creates a new set of attachment information with the specified
22966         * events handler and thread.
22967         *
22968         * @param handler the events handler the view must use
22969         */
22970        AttachInfo(IWindowSession session, IWindow window, Display display,
22971                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
22972            mSession = session;
22973            mWindow = window;
22974            mWindowToken = window.asBinder();
22975            mDisplay = display;
22976            mViewRootImpl = viewRootImpl;
22977            mHandler = handler;
22978            mRootCallbacks = effectPlayer;
22979        }
22980    }
22981
22982    /**
22983     * <p>ScrollabilityCache holds various fields used by a View when scrolling
22984     * is supported. This avoids keeping too many unused fields in most
22985     * instances of View.</p>
22986     */
22987    private static class ScrollabilityCache implements Runnable {
22988
22989        /**
22990         * Scrollbars are not visible
22991         */
22992        public static final int OFF = 0;
22993
22994        /**
22995         * Scrollbars are visible
22996         */
22997        public static final int ON = 1;
22998
22999        /**
23000         * Scrollbars are fading away
23001         */
23002        public static final int FADING = 2;
23003
23004        public boolean fadeScrollBars;
23005
23006        public int fadingEdgeLength;
23007        public int scrollBarDefaultDelayBeforeFade;
23008        public int scrollBarFadeDuration;
23009
23010        public int scrollBarSize;
23011        public ScrollBarDrawable scrollBar;
23012        public float[] interpolatorValues;
23013        public View host;
23014
23015        public final Paint paint;
23016        public final Matrix matrix;
23017        public Shader shader;
23018
23019        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23020
23021        private static final float[] OPAQUE = { 255 };
23022        private static final float[] TRANSPARENT = { 0.0f };
23023
23024        /**
23025         * When fading should start. This time moves into the future every time
23026         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23027         */
23028        public long fadeStartTime;
23029
23030
23031        /**
23032         * The current state of the scrollbars: ON, OFF, or FADING
23033         */
23034        public int state = OFF;
23035
23036        private int mLastColor;
23037
23038        public final Rect mScrollBarBounds = new Rect();
23039
23040        public static final int NOT_DRAGGING = 0;
23041        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23042        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23043        public int mScrollBarDraggingState = NOT_DRAGGING;
23044
23045        public float mScrollBarDraggingPos = 0;
23046
23047        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23048            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23049            scrollBarSize = configuration.getScaledScrollBarSize();
23050            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23051            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23052
23053            paint = new Paint();
23054            matrix = new Matrix();
23055            // use use a height of 1, and then wack the matrix each time we
23056            // actually use it.
23057            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23058            paint.setShader(shader);
23059            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23060
23061            this.host = host;
23062        }
23063
23064        public void setFadeColor(int color) {
23065            if (color != mLastColor) {
23066                mLastColor = color;
23067
23068                if (color != 0) {
23069                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23070                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23071                    paint.setShader(shader);
23072                    // Restore the default transfer mode (src_over)
23073                    paint.setXfermode(null);
23074                } else {
23075                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23076                    paint.setShader(shader);
23077                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23078                }
23079            }
23080        }
23081
23082        public void run() {
23083            long now = AnimationUtils.currentAnimationTimeMillis();
23084            if (now >= fadeStartTime) {
23085
23086                // the animation fades the scrollbars out by changing
23087                // the opacity (alpha) from fully opaque to fully
23088                // transparent
23089                int nextFrame = (int) now;
23090                int framesCount = 0;
23091
23092                Interpolator interpolator = scrollBarInterpolator;
23093
23094                // Start opaque
23095                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23096
23097                // End transparent
23098                nextFrame += scrollBarFadeDuration;
23099                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23100
23101                state = FADING;
23102
23103                // Kick off the fade animation
23104                host.invalidate(true);
23105            }
23106        }
23107    }
23108
23109    /**
23110     * Resuable callback for sending
23111     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23112     */
23113    private class SendViewScrolledAccessibilityEvent implements Runnable {
23114        public volatile boolean mIsPending;
23115
23116        public void run() {
23117            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23118            mIsPending = false;
23119        }
23120    }
23121
23122    /**
23123     * <p>
23124     * This class represents a delegate that can be registered in a {@link View}
23125     * to enhance accessibility support via composition rather via inheritance.
23126     * It is specifically targeted to widget developers that extend basic View
23127     * classes i.e. classes in package android.view, that would like their
23128     * applications to be backwards compatible.
23129     * </p>
23130     * <div class="special reference">
23131     * <h3>Developer Guides</h3>
23132     * <p>For more information about making applications accessible, read the
23133     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23134     * developer guide.</p>
23135     * </div>
23136     * <p>
23137     * A scenario in which a developer would like to use an accessibility delegate
23138     * is overriding a method introduced in a later API version then the minimal API
23139     * version supported by the application. For example, the method
23140     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23141     * in API version 4 when the accessibility APIs were first introduced. If a
23142     * developer would like his application to run on API version 4 devices (assuming
23143     * all other APIs used by the application are version 4 or lower) and take advantage
23144     * of this method, instead of overriding the method which would break the application's
23145     * backwards compatibility, he can override the corresponding method in this
23146     * delegate and register the delegate in the target View if the API version of
23147     * the system is high enough i.e. the API version is same or higher to the API
23148     * version that introduced
23149     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23150     * </p>
23151     * <p>
23152     * Here is an example implementation:
23153     * </p>
23154     * <code><pre><p>
23155     * if (Build.VERSION.SDK_INT >= 14) {
23156     *     // If the API version is equal of higher than the version in
23157     *     // which onInitializeAccessibilityNodeInfo was introduced we
23158     *     // register a delegate with a customized implementation.
23159     *     View view = findViewById(R.id.view_id);
23160     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23161     *         public void onInitializeAccessibilityNodeInfo(View host,
23162     *                 AccessibilityNodeInfo info) {
23163     *             // Let the default implementation populate the info.
23164     *             super.onInitializeAccessibilityNodeInfo(host, info);
23165     *             // Set some other information.
23166     *             info.setEnabled(host.isEnabled());
23167     *         }
23168     *     });
23169     * }
23170     * </code></pre></p>
23171     * <p>
23172     * This delegate contains methods that correspond to the accessibility methods
23173     * in View. If a delegate has been specified the implementation in View hands
23174     * off handling to the corresponding method in this delegate. The default
23175     * implementation the delegate methods behaves exactly as the corresponding
23176     * method in View for the case of no accessibility delegate been set. Hence,
23177     * to customize the behavior of a View method, clients can override only the
23178     * corresponding delegate method without altering the behavior of the rest
23179     * accessibility related methods of the host view.
23180     * </p>
23181     * <p>
23182     * <strong>Note:</strong> On platform versions prior to
23183     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23184     * views in the {@code android.widget.*} package are called <i>before</i>
23185     * host methods. This prevents certain properties such as class name from
23186     * being modified by overriding
23187     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23188     * as any changes will be overwritten by the host class.
23189     * <p>
23190     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23191     * methods are called <i>after</i> host methods, which all properties to be
23192     * modified without being overwritten by the host class.
23193     */
23194    public static class AccessibilityDelegate {
23195
23196        /**
23197         * Sends an accessibility event of the given type. If accessibility is not
23198         * enabled this method has no effect.
23199         * <p>
23200         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23201         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23202         * been set.
23203         * </p>
23204         *
23205         * @param host The View hosting the delegate.
23206         * @param eventType The type of the event to send.
23207         *
23208         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23209         */
23210        public void sendAccessibilityEvent(View host, int eventType) {
23211            host.sendAccessibilityEventInternal(eventType);
23212        }
23213
23214        /**
23215         * Performs the specified accessibility action on the view. For
23216         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23217         * <p>
23218         * The default implementation behaves as
23219         * {@link View#performAccessibilityAction(int, Bundle)
23220         *  View#performAccessibilityAction(int, Bundle)} for the case of
23221         *  no accessibility delegate been set.
23222         * </p>
23223         *
23224         * @param action The action to perform.
23225         * @return Whether the action was performed.
23226         *
23227         * @see View#performAccessibilityAction(int, Bundle)
23228         *      View#performAccessibilityAction(int, Bundle)
23229         */
23230        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23231            return host.performAccessibilityActionInternal(action, args);
23232        }
23233
23234        /**
23235         * Sends an accessibility event. This method behaves exactly as
23236         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23237         * empty {@link AccessibilityEvent} and does not perform a check whether
23238         * accessibility is enabled.
23239         * <p>
23240         * The default implementation behaves as
23241         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23242         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23243         * the case of no accessibility delegate been set.
23244         * </p>
23245         *
23246         * @param host The View hosting the delegate.
23247         * @param event The event to send.
23248         *
23249         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23250         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23251         */
23252        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23253            host.sendAccessibilityEventUncheckedInternal(event);
23254        }
23255
23256        /**
23257         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23258         * to its children for adding their text content to the event.
23259         * <p>
23260         * The default implementation behaves as
23261         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23262         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23263         * the case of no accessibility delegate been set.
23264         * </p>
23265         *
23266         * @param host The View hosting the delegate.
23267         * @param event The event.
23268         * @return True if the event population was completed.
23269         *
23270         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23271         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23272         */
23273        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23274            return host.dispatchPopulateAccessibilityEventInternal(event);
23275        }
23276
23277        /**
23278         * Gives a chance to the host View to populate the accessibility event with its
23279         * text content.
23280         * <p>
23281         * The default implementation behaves as
23282         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23283         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23284         * the case of no accessibility delegate been set.
23285         * </p>
23286         *
23287         * @param host The View hosting the delegate.
23288         * @param event The accessibility event which to populate.
23289         *
23290         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23291         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23292         */
23293        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23294            host.onPopulateAccessibilityEventInternal(event);
23295        }
23296
23297        /**
23298         * Initializes an {@link AccessibilityEvent} with information about the
23299         * the host View which is the event source.
23300         * <p>
23301         * The default implementation behaves as
23302         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23303         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23304         * the case of no accessibility delegate been set.
23305         * </p>
23306         *
23307         * @param host The View hosting the delegate.
23308         * @param event The event to initialize.
23309         *
23310         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23311         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23312         */
23313        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23314            host.onInitializeAccessibilityEventInternal(event);
23315        }
23316
23317        /**
23318         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
23319         * <p>
23320         * The default implementation behaves as
23321         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23322         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
23323         * the case of no accessibility delegate been set.
23324         * </p>
23325         *
23326         * @param host The View hosting the delegate.
23327         * @param info The instance to initialize.
23328         *
23329         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23330         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23331         */
23332        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
23333            host.onInitializeAccessibilityNodeInfoInternal(info);
23334        }
23335
23336        /**
23337         * Called when a child of the host View has requested sending an
23338         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
23339         * to augment the event.
23340         * <p>
23341         * The default implementation behaves as
23342         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23343         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
23344         * the case of no accessibility delegate been set.
23345         * </p>
23346         *
23347         * @param host The View hosting the delegate.
23348         * @param child The child which requests sending the event.
23349         * @param event The event to be sent.
23350         * @return True if the event should be sent
23351         *
23352         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23353         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23354         */
23355        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
23356                AccessibilityEvent event) {
23357            return host.onRequestSendAccessibilityEventInternal(child, event);
23358        }
23359
23360        /**
23361         * Gets the provider for managing a virtual view hierarchy rooted at this View
23362         * and reported to {@link android.accessibilityservice.AccessibilityService}s
23363         * that explore the window content.
23364         * <p>
23365         * The default implementation behaves as
23366         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
23367         * the case of no accessibility delegate been set.
23368         * </p>
23369         *
23370         * @return The provider.
23371         *
23372         * @see AccessibilityNodeProvider
23373         */
23374        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
23375            return null;
23376        }
23377
23378        /**
23379         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
23380         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
23381         * This method is responsible for obtaining an accessibility node info from a
23382         * pool of reusable instances and calling
23383         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
23384         * view to initialize the former.
23385         * <p>
23386         * <strong>Note:</strong> The client is responsible for recycling the obtained
23387         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
23388         * creation.
23389         * </p>
23390         * <p>
23391         * The default implementation behaves as
23392         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
23393         * the case of no accessibility delegate been set.
23394         * </p>
23395         * @return A populated {@link AccessibilityNodeInfo}.
23396         *
23397         * @see AccessibilityNodeInfo
23398         *
23399         * @hide
23400         */
23401        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
23402            return host.createAccessibilityNodeInfoInternal();
23403        }
23404    }
23405
23406    private class MatchIdPredicate implements Predicate<View> {
23407        public int mId;
23408
23409        @Override
23410        public boolean apply(View view) {
23411            return (view.mID == mId);
23412        }
23413    }
23414
23415    private class MatchLabelForPredicate implements Predicate<View> {
23416        private int mLabeledId;
23417
23418        @Override
23419        public boolean apply(View view) {
23420            return (view.mLabelForId == mLabeledId);
23421        }
23422    }
23423
23424    private class SendViewStateChangedAccessibilityEvent implements Runnable {
23425        private int mChangeTypes = 0;
23426        private boolean mPosted;
23427        private boolean mPostedWithDelay;
23428        private long mLastEventTimeMillis;
23429
23430        @Override
23431        public void run() {
23432            mPosted = false;
23433            mPostedWithDelay = false;
23434            mLastEventTimeMillis = SystemClock.uptimeMillis();
23435            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
23436                final AccessibilityEvent event = AccessibilityEvent.obtain();
23437                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
23438                event.setContentChangeTypes(mChangeTypes);
23439                sendAccessibilityEventUnchecked(event);
23440            }
23441            mChangeTypes = 0;
23442        }
23443
23444        public void runOrPost(int changeType) {
23445            mChangeTypes |= changeType;
23446
23447            // If this is a live region or the child of a live region, collect
23448            // all events from this frame and send them on the next frame.
23449            if (inLiveRegion()) {
23450                // If we're already posted with a delay, remove that.
23451                if (mPostedWithDelay) {
23452                    removeCallbacks(this);
23453                    mPostedWithDelay = false;
23454                }
23455                // Only post if we're not already posted.
23456                if (!mPosted) {
23457                    post(this);
23458                    mPosted = true;
23459                }
23460                return;
23461            }
23462
23463            if (mPosted) {
23464                return;
23465            }
23466
23467            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
23468            final long minEventIntevalMillis =
23469                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
23470            if (timeSinceLastMillis >= minEventIntevalMillis) {
23471                removeCallbacks(this);
23472                run();
23473            } else {
23474                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
23475                mPostedWithDelay = true;
23476            }
23477        }
23478    }
23479
23480    private boolean inLiveRegion() {
23481        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23482            return true;
23483        }
23484
23485        ViewParent parent = getParent();
23486        while (parent instanceof View) {
23487            if (((View) parent).getAccessibilityLiveRegion()
23488                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23489                return true;
23490            }
23491            parent = parent.getParent();
23492        }
23493
23494        return false;
23495    }
23496
23497    /**
23498     * Dump all private flags in readable format, useful for documentation and
23499     * sanity checking.
23500     */
23501    private static void dumpFlags() {
23502        final HashMap<String, String> found = Maps.newHashMap();
23503        try {
23504            for (Field field : View.class.getDeclaredFields()) {
23505                final int modifiers = field.getModifiers();
23506                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
23507                    if (field.getType().equals(int.class)) {
23508                        final int value = field.getInt(null);
23509                        dumpFlag(found, field.getName(), value);
23510                    } else if (field.getType().equals(int[].class)) {
23511                        final int[] values = (int[]) field.get(null);
23512                        for (int i = 0; i < values.length; i++) {
23513                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
23514                        }
23515                    }
23516                }
23517            }
23518        } catch (IllegalAccessException e) {
23519            throw new RuntimeException(e);
23520        }
23521
23522        final ArrayList<String> keys = Lists.newArrayList();
23523        keys.addAll(found.keySet());
23524        Collections.sort(keys);
23525        for (String key : keys) {
23526            Log.d(VIEW_LOG_TAG, found.get(key));
23527        }
23528    }
23529
23530    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
23531        // Sort flags by prefix, then by bits, always keeping unique keys
23532        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
23533        final int prefix = name.indexOf('_');
23534        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
23535        final String output = bits + " " + name;
23536        found.put(key, output);
23537    }
23538
23539    /** {@hide} */
23540    public void encode(@NonNull ViewHierarchyEncoder stream) {
23541        stream.beginObject(this);
23542        encodeProperties(stream);
23543        stream.endObject();
23544    }
23545
23546    /** {@hide} */
23547    @CallSuper
23548    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
23549        Object resolveId = ViewDebug.resolveId(getContext(), mID);
23550        if (resolveId instanceof String) {
23551            stream.addProperty("id", (String) resolveId);
23552        } else {
23553            stream.addProperty("id", mID);
23554        }
23555
23556        stream.addProperty("misc:transformation.alpha",
23557                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
23558        stream.addProperty("misc:transitionName", getTransitionName());
23559
23560        // layout
23561        stream.addProperty("layout:left", mLeft);
23562        stream.addProperty("layout:right", mRight);
23563        stream.addProperty("layout:top", mTop);
23564        stream.addProperty("layout:bottom", mBottom);
23565        stream.addProperty("layout:width", getWidth());
23566        stream.addProperty("layout:height", getHeight());
23567        stream.addProperty("layout:layoutDirection", getLayoutDirection());
23568        stream.addProperty("layout:layoutRtl", isLayoutRtl());
23569        stream.addProperty("layout:hasTransientState", hasTransientState());
23570        stream.addProperty("layout:baseline", getBaseline());
23571
23572        // layout params
23573        ViewGroup.LayoutParams layoutParams = getLayoutParams();
23574        if (layoutParams != null) {
23575            stream.addPropertyKey("layoutParams");
23576            layoutParams.encode(stream);
23577        }
23578
23579        // scrolling
23580        stream.addProperty("scrolling:scrollX", mScrollX);
23581        stream.addProperty("scrolling:scrollY", mScrollY);
23582
23583        // padding
23584        stream.addProperty("padding:paddingLeft", mPaddingLeft);
23585        stream.addProperty("padding:paddingRight", mPaddingRight);
23586        stream.addProperty("padding:paddingTop", mPaddingTop);
23587        stream.addProperty("padding:paddingBottom", mPaddingBottom);
23588        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
23589        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
23590        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
23591        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
23592        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
23593
23594        // measurement
23595        stream.addProperty("measurement:minHeight", mMinHeight);
23596        stream.addProperty("measurement:minWidth", mMinWidth);
23597        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
23598        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
23599
23600        // drawing
23601        stream.addProperty("drawing:elevation", getElevation());
23602        stream.addProperty("drawing:translationX", getTranslationX());
23603        stream.addProperty("drawing:translationY", getTranslationY());
23604        stream.addProperty("drawing:translationZ", getTranslationZ());
23605        stream.addProperty("drawing:rotation", getRotation());
23606        stream.addProperty("drawing:rotationX", getRotationX());
23607        stream.addProperty("drawing:rotationY", getRotationY());
23608        stream.addProperty("drawing:scaleX", getScaleX());
23609        stream.addProperty("drawing:scaleY", getScaleY());
23610        stream.addProperty("drawing:pivotX", getPivotX());
23611        stream.addProperty("drawing:pivotY", getPivotY());
23612        stream.addProperty("drawing:opaque", isOpaque());
23613        stream.addProperty("drawing:alpha", getAlpha());
23614        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
23615        stream.addProperty("drawing:shadow", hasShadow());
23616        stream.addProperty("drawing:solidColor", getSolidColor());
23617        stream.addProperty("drawing:layerType", mLayerType);
23618        stream.addProperty("drawing:willNotDraw", willNotDraw());
23619        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
23620        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
23621        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
23622        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
23623
23624        // focus
23625        stream.addProperty("focus:hasFocus", hasFocus());
23626        stream.addProperty("focus:isFocused", isFocused());
23627        stream.addProperty("focus:isFocusable", isFocusable());
23628        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
23629
23630        stream.addProperty("misc:clickable", isClickable());
23631        stream.addProperty("misc:pressed", isPressed());
23632        stream.addProperty("misc:selected", isSelected());
23633        stream.addProperty("misc:touchMode", isInTouchMode());
23634        stream.addProperty("misc:hovered", isHovered());
23635        stream.addProperty("misc:activated", isActivated());
23636
23637        stream.addProperty("misc:visibility", getVisibility());
23638        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
23639        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
23640
23641        stream.addProperty("misc:enabled", isEnabled());
23642        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
23643        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
23644
23645        // theme attributes
23646        Resources.Theme theme = getContext().getTheme();
23647        if (theme != null) {
23648            stream.addPropertyKey("theme");
23649            theme.encode(stream);
23650        }
23651
23652        // view attribute information
23653        int n = mAttributes != null ? mAttributes.length : 0;
23654        stream.addProperty("meta:__attrCount__", n/2);
23655        for (int i = 0; i < n; i += 2) {
23656            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
23657        }
23658
23659        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
23660
23661        // text
23662        stream.addProperty("text:textDirection", getTextDirection());
23663        stream.addProperty("text:textAlignment", getTextAlignment());
23664
23665        // accessibility
23666        CharSequence contentDescription = getContentDescription();
23667        stream.addProperty("accessibility:contentDescription",
23668                contentDescription == null ? "" : contentDescription.toString());
23669        stream.addProperty("accessibility:labelFor", getLabelFor());
23670        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
23671    }
23672}
23673